Strategy · Pine Script v5 · On the chart

Bitcoin Regime Pyramid Strategy

by Web3Degenerate

Calculates higher timeframe Exponential Moving Averages, Average True Range, and optional RSI momentum filters to determine market regimes.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code93
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago13 Sep 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

93 lines of Pine Script v5 from advanced-pine-script/9.Strategy-Scripts/19.How-to-Pyramid-Trades.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

19.How-to-Pyramid-Trades.pine
//This  expands on the Bitcoin Momentum Strategy by demonstrating how to enable pyramiding. For those who don't know, "pyramiding" is the practice of opening multiple positions in the same direction as your original trade and is typically used to increase your average position size as a trade moves in your favor.

//Update 20th June 2023: I changed the security function  call to reflect the latest 'best practice' for non-repainting code as mentioned in the Trading View Docs: https://www.tradingview.com/pine-script-docs/en/v5/concepts/Repainting.html#repainting-request-security-calls

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// @version=5
strategy("Bitcoin Regime Pyramid Strategy", 
     overlay=true, 
     initial_capital=10000, 
     currency=currency.USDT,
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100,
     commission_type=strategy.commission.percent,
     commission_value=0.1)
                 
// Get user input
res         = input.timeframe(title="Timeframe", defval="W")
len         = input.int(title="EMA Length", defval=20)
marketTF    = input.timeframe(title="Market Timeframe", defval="D")
useRsi      = input.bool(title="Use RSI Momentum Filter", defval=false)
rsiMom      = input.int(title="RSI Momentum Threshold", defval=70)
startTime   = input.time(title="Start Filter", defval=timestamp("01 Jan 2000 13:30 +0000"), group="Time Filter", tooltip="Start date & time to begin searching for setups")
endTime     = input.time(title="End Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), group="Time Filter", tooltip="End date & time to stop searching for setups")
pyramid     = input.bool(title="Pyramid?", defval=false)
pyramidAmt  = input.float(title="Pyramid After X%", defval=10)

// Define custom security function
f_sec(_market, _res, _exp) => request.security(_market, _res, _exp[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]

// Define date filter
dateFilter(int st, int et) => time >= st and time <= et

// Get EMA value
ema = ta.ema(close, len)
htfEmaValue = f_sec(syminfo.tickerid, res, ema)

// Get ATR value
atrValue = ta.atr(5)

// Check if price is above or below EMA filter
marketPrice = f_sec(syminfo.tickerid, marketTF, close)
regimeFilter = marketPrice > (htfEmaValue + (atrValue * 0.25))

// Calculate RSI
rsiValue = ta.rsi(close, 7)

// Get bullish momentum filter
bullish = regimeFilter and (rsiValue > rsiMom or not useRsi)

// Check for bearish volatility caution
caution = bullish and ta.highest(high, 7) - low > (atrValue * 1.5)

// Set momentum color
bgCol = color.red
if bullish[1]
    bgCol := color.green
if caution[1]
    bgCol := color.orange

// Change background color
plotshape(1, color=bgCol, style=shape.square, location=location.bottom, size=size.auto, title="Momentum Strength")
plot(htfEmaValue, color=close > htfEmaValue ? color.green : color.red, linewidth=2)

// Store trailing ratchet stop loss
var float trailStop = na

// Handle strategy entry
if bullish and strategy.position_size == 0 and dateFilter(startTime, endTime) and not caution
    strategy.entry(id="Buy", direction=strategy.long)

// Handle scale-in pyramiding
if strategy.position_size > 0 and dateFilter(startTime, endTime)
    dist = (close - strategy.position_avg_price) / strategy.position_avg_price
    if bullish and not caution and dist >= (pyramidAmt / 100)
        strategy.entry(id="Buy", direction=strategy.long)
        //strategy.entry(id="Buy2", direction=strategy.long)

// Handle trailing stop
temp_trailStop = ta.highest(low, 7) - (caution[1] ? atrValue * 0.2 : atrValue)
if strategy.position_size > 0
    if temp_trailStop > trailStop or na(trailStop)
        trailStop := temp_trailStop

// Handle strategy exit
if (close < trailStop or close < htfEmaValue)
    strategy.close("Buy", comment="Sell")
    trailStop := na

//strategy.exit(id="Pyramid Exit", from_entry="Buy2", stop=trailStop)

// Draw stop
plot(strategy.position_size[1] > 0 ? trailStop : na, style=plot.style_linebr, color=color.red, title="Stop Loss")

Overview

Enters long positions during bullish regimes and allows scaling in through pyramiding as price advances by a user-defined percentage. Features adjustable EMA length, higher timeframe resolution, RSI thresholds, and scale-in step percentages. Plots HTF EMA levels and regime status indicators directly on the price chart.

Details

Published by

Web3Degenerate on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages, Oscillators & momentum

Markets

Crypto

Timeframes

H4 and above

Risk Notes

  • The strategy can add several entries in the same direction
  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
TimeframetimeframeWres
EMA Lengthint20len
Market TimeframetimeframeDmarketTF
Use RSI Momentum FilterboolfalseuseRsi
RSI Momentum Thresholdint70rsiMom
Start Filtertimetimestamp("01 Jan 2000 13:30 +0000")startTime
End Filtertimetimestamp("1 Jan 2099 19:30 +0000")endTime
Pyramid?boolfalsepyramid
Pyramid After X%float10pyramidAmt
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy

This strategy combines Arnaud Legoux Moving Average percentage price change calculations with an adaptive Gaussian Moving Average to generate trend-following signals. Long and short entries are triggered when the ALMA change calculation crosses above or below

Strategy v5 Moving averagesOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of ESM2024 - ALMA Smoothed Gaussian Moving Average
218 stars

This strategy generates trading signals based on a selectable momentum engine, supporting MACD, RSI, Stochastic, or Rate of Change. Entries trigger on signal crosses, zero-line crosses, or threshold crosses, with an optional moving average trend filter. Risk m

Strategy v6 Oscillators & momentumTrend
Updated 3 months ago · None stated GitHub repository of Momentum Strategy Template

255 EMA Strategy

by hasnocool
106 stars

255 EMA Strategy combines an exponential moving average with Average True Range bands and standard MACD crossovers to generate entry signals. Drawn directly on the price chart, it plots the central 255 EMA along with upper and lower volatility envelopes. Trade

Strategy v4 Moving averagesOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 255 EMA Strategy

SMA RSI Strategy

by PythonForForex
64 stars

This strategy evaluates simple moving averages and the Relative Strength Index to generate trading signals. It calculates a 10-period SMA, a 30-period SMA, and a 14-period RSI. Long positions are entered when the fast SMA crosses above the slow SMA while RSI i

Strategy v5 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of SMA RSI Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers