Pine Script v4 · Strategy
Breakout Trend Trading Strategy - V2
A Pine Script v4 strategy built on ATR (supertrendLength), Supertrend (supertrendMult, supertrendLength) and Percentrank (source, 50). It has 9 order rules, 5 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade commits 100% of equity and pays 0.01% commission. 28 settings; defaults include Exit Strategy when in Range Disabled, Trade Type all and Display Mode Targets.
Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.
- Does Breakout Trend Trading Strategy - V2 repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
- How did Breakout Trend Trading Strategy - V2 do on BTCUSDT 1D with default settings?
- −1.20%
- From 26 Jan 2024 to 21 Oct 2026, over 1 closed trade, against +102.5% for buy and hold. A backtest, not investment advice.
- Can Breakout Trend Trading Strategy - V2 be converted to Pine Script v5?
- Yes
- The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
- Does Breakout Trend Trading Strategy - V2 use a stop loss?
- Yes
- strategy.exit sets a stop on line 361, 365.
- Does Breakout Trend Trading Strategy - V2 run in Zeal Terminal?
- Yes
- It compiles in 88 ms and runs 1,000 bars in 331 ms, in the browser.
BTCUSDT · 1D · default settings
- UpTarget
- DownTarget
- DownStop
- UpStop
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- −1.20%
- −$23.91
- Buy and hold
- +102.5%
- same period
- Closed trades
- 1
- 0 won · 1 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- 0.00
- gross profit ÷ gross loss
- Max drawdown
- 9.79%
- −$195.75
One run with the author's default settings, $2,000 starting capital, commission as the script sets it. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.
Review
What a careful reader of this script would point out, found by checking the source and the backtest.
-
Check
Every trade uses all the equity
default_qty_value is 100% of equity.
-
Note
21 settings have no label
In the settings dialog exitOnSignal (line 6), allowImmediateCompound (line 8), showTrailingStop (line 12), showTargetLevels (line 13), showPreviousLevels (line 14), stopMultiplyer (line 15), compoundMultiplyer (line 16), rangeBars (line 17), backtestYears (line 18), shortHighLowPeriod (line 20), longHighLowPeriod (line 21), LookbackPeriod (line 23), includePartiallyAligned (line 24), alignmentIndexThreshold (line 26), LookbackPeriodPR (line 27), considerWeeklySupertrend (line 28), SupertrendWMult (line 29), SupertrendWPd (line 30), considerMonthlySupertrend (line 31), SupertrendMMult (line 32), SupertrendMPd (line 33) show an empty name. The labels on this page come from the variable names.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses an argument v6 removed
when = on line 357, 358, 359, 360, 362, 363, 364. The upgraded version below moves each call inside an if block.
Upgrade and export
Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.
- Upgrading to v5 renames abs → math.abs, max → math.max, security → request.security, min → math.min, sma → ta.sma, ema → ta.ema, hma → ta.hma, rma → ta.rma, vwma → ta.vwma, wma → ta.wma, atr → ta.atr, crossover → ta.crossover, crossunder → ta.crossunder, highest → ta.highest, lowest → ta.lowest, tostring → str.tostring, supertrend → ta.supertrend, sum → math.sum, percentrank → ta.percentrank, bb → ta.bb.
- 7 strategy calls use the when = argument (line 357, 358, 359, 360, 362, 363, 364). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
VerifiedSame 1 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 3: //@version=4 → //@version=5
- Line 112: abs → math.abs
- Line 116: abs → math.abs
- Line 120: abs → math.abs
- Line 143: max → math.max
- Line 143: max → math.max
48 more edits
- Line 143: abs → math.abs
- Line 143: abs → math.abs
- Line 164: security → request.security
- Line 165: security → request.security
- Line 171: max → math.max
- Line 171: max → math.max
- Line 171: min → math.min
- Line 173: min → math.min
- Line 173: min → math.min
- Line 173: max → math.max
- Line 179: sma → ta.sma
- Line 181: ema → ta.ema
- Line 183: hma → ta.hma
- Line 185: rma → ta.rma
- Line 187: vwma → ta.vwma
- Line 189: wma → ta.wma
- Line 212: atr → ta.atr
- Line 217: max → math.max
- Line 221: min → math.min
- Line 233: crossover → ta.crossover
- Line 233: crossover → ta.crossover
- Line 234: crossunder → ta.crossunder
- Line 234: crossunder → ta.crossunder
- Line 235: crossunder → ta.crossunder
- Line 235: crossunder → ta.crossunder
- Line 236: crossover → ta.crossover
- Line 236: crossover → ta.crossover
- Line 240: highest → ta.highest
- Line 240: highest → ta.highest
- Line 241: lowest → ta.lowest
- Line 241: lowest → ta.lowest
- Line 264: range is reserved in v5: renamed range_
- Line 272: max → math.max
- Line 273: min → math.min
- Line 277: min → math.min
- Line 278: max → math.max
- Line 287: tostring → str.tostring
- Line 298: supertrend → ta.supertrend
- Line 299: atr → ta.atr
- Line 307: sum → math.sum
- Line 319: percentrank → ta.percentrank
- Line 320: security → request.security
- Line 320: supertrend → ta.supertrend
- Line 321: security → request.security
- Line 321: supertrend → ta.supertrend
- Line 324: bb → ta.bb
- Line 325: crossover → ta.crossover
- Line 326: crossunder → ta.crossunder
⋯// © HeWhoMustNotBeNamed-//@version=4+//@version=5strategy("Breakout Trend Trading - V2", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)⋯ trendBreakout = false- if(abs(close[1] - close) > atr * trendTargetMult) or (high-low > 2 * atr * trendTargetMult and considerOpenCloseBreakout)+ if(math.abs(close[1] - close) > atr * trendTargetMult) or (high-low > 2 * atr * trendTargetMult and considerOpenCloseBreakout) trendBreakout := true⋯ reverseBreakout = false- if(abs(close[1] - close) > atr * reverseTargetMult) or (high-low > 2 * atr * reverseTargetMult and considerOpenCloseBreakout)+ if(math.abs(close[1] - close) > atr * reverseTargetMult) or (high-low > 2 * atr * reverseTargetMult and considerOpenCloseBreakout) reverseBreakout := true⋯ highBreakout = false- if(abs(close[1] - close) > atr * highBreakoutMult) or (high-low > 2 * atr * highBreakoutMult and considerOpenCloseBreakout)+ if(math.abs(close[1] - close) > atr * highBreakoutMult) or (high-low > 2 * atr * highBreakoutMult and considerOpenCloseBreakout) highBreakout:=true⋯f_getTargets(barState, trendValueMarkup, reverseValueMarkup, stopMultFactor, dir, atr)=>- diff = max(high-low, max(abs(high-close[1]), abs(low-close[1])))+ diff = math.max(high-low, math.max(math.abs(high-close[1]), math.abs(low-close[1]))) upTarget = (barState == 1) ? high + ((dir==-1?trendValueMarkup:reverseValueMarkup)/100)*diff : na⋯f_getYearlyHighLowCondition(considerYearlyHighLow)=>- yhigh = security(syminfo.tickerid, '12M', high[1]) + yhigh = request.security(syminfo.tickerid, '12M', high[1]) - ylow = security(syminfo.tickerid, '12M', low[1]) + ylow = request.security(syminfo.tickerid, '12M', low[1]) yhighlast = yhigh[365]⋯ - yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))+ yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > math.max(yhigh,yhighlast) : close > math.max(yhigh, math.min(yhighlast, yhighllast)) yearlyHighCondition = ( (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow- yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))+ yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < math.min(ylow,ylowlast) : close < math.min(ylow, math.max(ylowlast, ylowllast)) yearlyLowCondition = ( (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow⋯f_getMovingAverage(source, MAType, length)=>- ma = sma(source, length)+ ma = ta.sma(source, length) if(MAType == "ema")- ma := ema(source,length)+ ma := ta.ema(source,length) if(MAType == "hma")- ma := hma(source,length)+ ma := ta.hma(source,length) if(MAType == "rma")- ma := rma(source,length)+ ma := ta.rma(source,length) if(MAType == "vwma")- ma := vwma(source,length)+ ma := ta.vwma(source,length) if(MAType == "wma")- ma := wma(source,length)+ ma := ta.wma(source,length) ma⋯f_supertrendOnMa(source, MaType, MaLength, supertrendLength, supertrendMult)=>- supertrendDistance = supertrendMult * atr(supertrendLength)+ supertrendDistance = supertrendMult * ta.atr(supertrendLength) ⋯ longStopPrev = nz(longStop[1], longStop)- longStop := ma > longStopPrev ? max(longStop, longStopPrev) : longStop+ longStop := ma > longStopPrev ? math.max(longStop, longStopPrev) : longStop ⋯ shortStopPrev = nz(shortStop[1], shortStop)- shortStop := ma < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop+ shortStop := ma < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop ⋯ redBreakout = (lastBreakout < 0) or ignoreReverseBreakout- buySignal = dir==-1? false : (crossover(low, upLine[1]) and greenBreakout and close > downLine[1]) or (crossover(low, stopDownLine[1]) and redBreakout) + buySignal = dir==-1? false : (ta.crossover(low, upLine[1]) and greenBreakout and close > downLine[1]) or (ta.crossover(low, stopDownLine[1]) and redBreakout) - stopBuySignal = (crossunder(dir==-1?close:low, downLine[1]) or crossunder(dir==-1?close:low, stopUpLine[1]))+ stopBuySignal = (ta.crossunder(dir==-1?close:low, downLine[1]) or ta.crossunder(dir==-1?close:low, stopUpLine[1]))- sellSignal = dir==1? false : (crossunder(high, downLine[1]) and redBreakout and close < upLine[1]) or (crossunder(high, stopUpLine[1]) and greenBreakout)+ sellSignal = dir==1? false : (ta.crossunder(high, downLine[1]) and redBreakout and close < upLine[1]) or (ta.crossunder(high, stopUpLine[1]) and greenBreakout)- stopSellSignal = (crossover(dir==1?close:high, upLine[1]) or crossover(dir==1?close:high, stopDownLine[1]))+ stopSellSignal = (ta.crossover(dir==1?close:high, upLine[1]) or ta.crossover(dir==1?close:high, stopDownLine[1])) [buySignal,stopBuySignal,sellSignal,stopSellSignal]⋯f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=>- newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows+ newHigh = ta.highest(shortHighLowPeriod) == ta.highest(longHighLowPeriod) or not considerNewLongTermHighLows- newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows+ newLow = ta.lowest(shortHighLowPeriod) == ta.lowest(longHighLowPeriod) or not considerNewLongTermHighLows [newHigh,newLow]⋯ sellStop = target + (stopMultiplyer * atr)- range = false+ range_ = false- range := range[1] and exitOnBB? close > buyStop[1] and close < sellStop[1]:strategy.position_size != 0 and buyStop[1] == buyStop[rangeBars+1] and sellStop[1] == sellStop[rangeBars+1] + range_ := range_[1] and exitOnBB? close > buyStop[1] and close < sellStop[1]:strategy.position_size != 0 and buyStop[1] == buyStop[rangeBars+1] and sellStop[1] == sellStop[rangeBars+1] - if(range and exitOnBB)+ if(range_ and exitOnBB) buyStop := buyStop[1]⋯ sellStop := target + (compoundMultiplyer * atr)- buyStop := range and exitOnTrailingStopWhenInRange? max(buyStop, buyStop[1]): (buyStop < buyStop[1] or close < sellStop[1])? buyStop[1] : buyStop+ buyStop := range_ and exitOnTrailingStopWhenInRange? math.max(buyStop, buyStop[1]): (buyStop < buyStop[1] or close < sellStop[1])? buyStop[1] : buyStop- sellStop := range and exitOnTrailingStopWhenInRange? min(sellStop, sellStop[1]): (sellStop < sellStop[1] or close < sellStop[1]) ? sellStop[1] : sellStop+ sellStop := range_ and exitOnTrailingStopWhenInRange? math.min(sellStop, sellStop[1]): (sellStop < sellStop[1] or close < sellStop[1]) ? sellStop[1] : sellStop else if(barState < 0 or strategy.position_size < 0)⋯ sellStop := target + (stopMultiplyer * atr)- sellStop := range and exitOnTrailingStopWhenInRange? min(sellStop, sellStop[1]) : (sellStop > sellStop[1] or close > buyStop[1])? sellStop[1] : sellStop+ sellStop := range_ and exitOnTrailingStopWhenInRange? math.min(sellStop, sellStop[1]) : (sellStop > sellStop[1] or close > buyStop[1])? sellStop[1] : sellStop- buyStop := range and exitOnTrailingStopWhenInRange? max(buyStop, buyStop[1]): (buyStop > buyStop[1] or close > buyStop[1]) ? buyStop[1] : buyStop+ buyStop := range_ and exitOnTrailingStopWhenInRange? math.max(buyStop, buyStop[1]): (buyStop > buyStop[1] or close > buyStop[1]) ? buyStop[1] : buyStop- [target, buyStop, sellStop, range]+ [target, buyStop, sellStop, range_] ⋯ targetLine = line.new(x1=line_x1, y1=target, x2=line_x2, y2=target, color=linecolor, xloc=xloc.bar_time)- targetLabel = label.new(x=label_x, y=target, text=lbl + " : "+tostring(target), xloc=xloc.bar_time, style=label.style_none, textcolor=color.black, size=size.normal)+ targetLabel = label.new(x=label_x, y=target, text=lbl + " : "+str.tostring(target), xloc=xloc.bar_time, style=label.style_none, textcolor=color.black, size=size.normal) [targetLine,targetLabel]⋯vmareverse = f_getMovingAverage(volume, volumeMaType, reverseVolumeLength)-[superTrend, dir] = supertrend(supertrendMult, supertrendLength)+[superTrend, dir] = ta.supertrend(supertrendMult, supertrendLength)-atr = atr(atrlength)+atr = ta.atr(atrlength)[trendBreakout, reverseBreakout, highBreakout] = f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)⋯maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)-alignedMaIndex = sum(maAlignment,LookbackPeriod)+alignedMaIndex = math.sum(maAlignment,LookbackPeriod)maHigh = alignedMaIndex > alignmentIndexThreshold or not considerMaAlignment⋯[buyEntry, sellEntry, stopBuyEntry, stopSellEntry, breakout, pullback, reverse] = f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange, tradeType, newHigh, maHigh, newLow, maLow)-[target, buyStop, sellStop, range] = f_calculateStopAndCompound(buyEntry, sellEntry, breakout, pullback, reverse, upLine, stopUpLine, downLine, stopDownLine, atr, stopMultiplyer, compoundMultiplyer, barState, exitOnTrailingStopWhenInRange, exitOnBB)+[target, buyStop, sellStop, range_] = f_calculateStopAndCompound(buyEntry, sellEntry, breakout, pullback, reverse, upLine, stopUpLine, downLine, stopDownLine, atr, stopMultiplyer, compoundMultiplyer, barState, exitOnTrailingStopWhenInRange, exitOnBB)//crossedCompound = (strategy.position_size > 0 ? strategy.position_avg_price < buyStop : strategy.position_size < 0 ? strategy.position_avg_price > sellStop : true) or allowImmediateCompoundcrossedCompound = (strategy.position_size > 0 ? close > sellStop : strategy.position_size < 0 ? close < buyStop : true) or allowImmediateCompound-percentRank = percentrank(source, LookbackPeriodPR)+percentRank = ta.percentrank(source, LookbackPeriodPR)-[SupertrendW, DirW] = security(syminfo.tickerid, 'W', supertrend(SupertrendWMult, SupertrendWPd), lookahead = true)+[SupertrendW, DirW] = request.security(syminfo.tickerid, 'W', ta.supertrend(SupertrendWMult, SupertrendWPd), lookahead = true)-[SupertrendM, DirM] = security(syminfo.tickerid, 'M', supertrend(SupertrendMMult, SupertrendMPd), lookahead = true)+[SupertrendM, DirM] = request.security(syminfo.tickerid, 'M', ta.supertrend(SupertrendMMult, SupertrendMPd), lookahead = true)buyEntry := buyEntry and (((dirMa == 1 or not considerMaSupertrend) and percentRank > 50) or strategy.netprofit >= 0) and (DirW == -1 or not considerWeeklySupertrend) and (DirM == -1 or not considerMonthlySupertrend)sellEntry := sellEntry and (((dirMa == -1 or not considerMaSupertrend) and percentRank < 50) or strategy.netprofit >= 0) and (DirW == 1 or not considerWeeklySupertrend) and (DirM == 1 or not considerMonthlySupertrend)-[middle, upper, lower] = bb(close, 100, 2.5)+[middle, upper, lower] = ta.bb(close, 100, 2.5)-rangeBuyEntry = range and crossover(close, lower) and exitOnBB+rangeBuyEntry = range_ and ta.crossover(close, lower) and exitOnBB-rangeSellEntry = range and crossunder(close, upper) and exitOnBB+rangeSellEntry = range_ and ta.crossunder(close, upper) and exitOnBB//////////////////////////////////////// Plot //////////////////////////////////////////////////////⋯channelview = showChannel or showUpChannel or showDownChannel-buyStopLineColor = range ? color.purple : strategy.position_size > 0 ?color.red:strategy.position_size < 0 ?color.green:color.blue+buyStopLineColor = range_ ? color.purple : strategy.position_size > 0 ?color.red:strategy.position_size < 0 ?color.green:color.blue-sellStopLineColor = range ? color.purple : strategy.position_size > 0?color.green:strategy.position_size < 0 ?color.red:color.blue+sellStopLineColor = range_ ? color.purple : strategy.position_size > 0?color.green:strategy.position_size < 0 ?color.red:color.blue-showStopCompound = showTrailingStop and (range or strategy.position_size != 0) and not channelview+showStopCompound = showTrailingStop and (range_ or strategy.position_size != 0) and not channelviewplot(showStopCompound? buyStop : na, title="DownStop", color=buyStopLineColor, linewidth=2, style=plot.style_stepline)⋯strategy.risk.allow_entry_in(tradeDirection)-strategy.entry("Buy", strategy.long, when=buyEntry and reverse and crossedCompound and (not range or not exitOnBB), oca_name="oca_buy", oca_type=strategy.oca.cancel)+strategy.entry("Buy", strategy.long, when=buyEntry and reverse and crossedCompound and (not range_ or not exitOnBB), oca_name="oca_buy", oca_type=strategy.oca.cancel)-strategy.entry("Buy", strategy.long, when=buyEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB), stop=target, oca_name="oca_buy", oca_type=strategy.oca.cancel)+strategy.entry("Buy", strategy.long, when=buyEntry and (breakout or pullback) and crossedCompound and (not range_ or not exitOnBB), stop=target, oca_name="oca_buy", oca_type=strategy.oca.cancel)strategy.entry("Buy", strategy.long, when=rangeBuyEntry, oca_name="oca_buy", oca_type=strategy.oca.cancel)-strategy.close("Buy", when=(stopBuyEntry and (exitOnSignal or (exitOnSignalWhenInRange and range))) or rangeSellEntry)+strategy.close("Buy", when=(stopBuyEntry and (exitOnSignal or (exitOnSignalWhenInRange and range_))) or rangeSellEntry)strategy.exit("ExitBuy", "Buy", stop = buyStop)-strategy.entry("Sell", strategy.short, when=sellEntry and reverse and crossedCompound and (not range or not exitOnBB), oca_name="oca_sell", oca_type=strategy.oca.cancel)+strategy.entry("Sell", strategy.short, when=sellEntry and reverse and crossedCompound and (not range_ or not exitOnBB), oca_name="oca_sell", oca_type=strategy.oca.cancel)-strategy.entry("Sell", strategy.short, when=sellEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB), stop=target, oca_name="oca_sell", oca_type=strategy.oca.cancel)+strategy.entry("Sell", strategy.short, when=sellEntry and (breakout or pullback) and crossedCompound and (not range_ or not exitOnBB), stop=target, oca_name="oca_sell", oca_type=strategy.oca.cancel)-strategy.close("Sell", when=stopSellEntry and (exitOnSignal or (exitOnSignalWhenInRange and range)))+strategy.close("Sell", when=stopSellEntry and (exitOnSignal or (exitOnSignalWhenInRange and range_)))strategy.exit("ExitSell", "Sell", stop = sellStop)Same 1 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 6: input() → input.bool()
- Line 7: input() → input.string()
- Line 8: input() → input.bool()
- Line 10: input() → input.string()
- Line 11: input() → input.string()
- Line 12: input() → input.bool()
28 more edits
- Line 13: input() → input.bool()
- Line 14: input() → input.bool()
- Line 15: input() → input.int()
- Line 16: input() → input.int()
- Line 17: input() → input.int()
- Line 18: input() → input.int()
- Line 19: input() → input.bool()
- Line 20: input() → input.int()
- Line 21: input() → input.int()
- Line 22: input() → input.bool()
- Line 23: input() → input.int()
- Line 24: input() → input.bool()
- Line 25: input() → input.string()
- Line 26: input() → input.int()
- Line 27: input() → input.int()
- Line 28: input() → input.bool()
- Line 29: input() → input.int()
- Line 30: input() → input.int()
- Line 31: input() → input.bool()
- Line 32: input() → input.int()
- Line 33: input() → input.int()
- Line 357: when = buyEntry and reverse and crossedCompound and (not range_ or not exitOnBB) → if block
- Line 358: when = buyEntry and (breakout or pullback) and crossedCompound and (not range_ or not exitOnBB) → if block
- Line 359: when = rangeBuyEntry → if block
- Line 360: when = (stopBuyEntry and (exitOnSignal or (exitOnSignalWhenInRange and range_))) or rangeSellEntry → if block
- Line 362: when = sellEntry and reverse and crossedCompound and (not range_ or not exitOnBB) → if block
- Line 363: when = sellEntry and (breakout or pullback) and crossedCompound and (not range_ or not exitOnBB) → if block
- Line 364: when = stopSellEntry and (exitOnSignal or (exitOnSignalWhenInRange and range_)) → if block
⋯///////////////////////////////////////// Input ////////////////////////////////////////////////////////////////////-exitOnSignal = input(false)+exitOnSignal = input.bool(false)-exitStrategyOnRangingCondition = input(title="Exit Strategy when in Range", defval="Disabled", options=["Disabled", "ExitOnSignal", "TrailStopLoss", "BollingerBands"])+exitStrategyOnRangingCondition = input.string(title="Exit Strategy when in Range", defval="Disabled", options=["Disabled", "ExitOnSignal", "TrailStopLoss", "BollingerBands"])-allowImmediateCompound = input(false)+allowImmediateCompound = input.bool(false)tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])-tradeType = input(title="Trade Type", defval="all", options=["all", "pullback", "breakout", "reverse", "pullback + breakout"])+tradeType = input.string(title="Trade Type", defval="all", options=["all", "pullback", "breakout", "reverse", "pullback + breakout"])-displayMode = input(title="Display Mode", defval="Targets", options=["Targets", "Target Channel", "Target with Stops", "Up Channel", "Down Channel"])+displayMode = input.string(title="Display Mode", defval="Targets", options=["Targets", "Target Channel", "Target with Stops", "Up Channel", "Down Channel"])-showTrailingStop = input(true)+showTrailingStop = input.bool(true)-showTargetLevels = input(true)+showTargetLevels = input.bool(true)-showPreviousLevels = input(false)+showPreviousLevels = input.bool(false)-stopMultiplyer = input(6, minval=1, maxval=10, step=0.5)+stopMultiplyer = input.int(6, minval=1, maxval=10, step=0.5)-compoundMultiplyer = input(4, minval=1, maxval=10, step=0.5)+compoundMultiplyer = input.int(4, minval=1, maxval=10, step=0.5)-rangeBars = input(100, step=5)+rangeBars = input.int(100, step=5)-backtestYears = input(10, minval=1, step=1)+backtestYears = input.int(10, minval=1, step=1)-considerNewLongTermHighLows = input(true,"Filter Highs/Lows for entry")+considerNewLongTermHighLows = input.bool(true,"Filter Highs/Lows for entry")-shortHighLowPeriod = input(100, step=10)+shortHighLowPeriod = input.int(100, step=10)-longHighLowPeriod = input(200, step=10)+longHighLowPeriod = input.int(200, step=10)-considerMaAlignment = input(true,"Check recent moving average alignment")+considerMaAlignment = input.bool(true,"Check recent moving average alignment")-LookbackPeriod = input(300, step=10)+LookbackPeriod = input.int(300, step=10)-includePartiallyAligned = input(true)+includePartiallyAligned = input.bool(true)-MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])+MAType = input.string(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])-alignmentIndexThreshold = input(50, step=10)+alignmentIndexThreshold = input.int(50, step=10)-LookbackPeriodPR = input(50, step=10)+LookbackPeriodPR = input.int(50, step=10)-considerWeeklySupertrend = input(false)+considerWeeklySupertrend = input.bool(false)-SupertrendWMult = input(1)+SupertrendWMult = input.int(1)-SupertrendWPd = input(26)+SupertrendWPd = input.int(26)-considerMonthlySupertrend = input(false)+considerMonthlySupertrend = input.bool(false)-SupertrendMMult = input(2)+SupertrendMMult = input.int(2)-SupertrendMPd = input(6)+SupertrendMPd = input.int(6)//supertrendMult = input(6, minval=1, maxval=10, step=0.5)⋯strategy.risk.allow_entry_in(tradeDirection)-strategy.entry("Buy", strategy.long, when=buyEntry and reverse and crossedCompound and (not range_ or not exitOnBB), oca_name="oca_buy", oca_type=strategy.oca.cancel)+if buyEntry and reverse and crossedCompound and (not range_ or not exitOnBB)+ strategy.entry("Buy", strategy.long, oca_name="oca_buy", oca_type=strategy.oca.cancel)-strategy.entry("Buy", strategy.long, when=buyEntry and (breakout or pullback) and crossedCompound and (not range_ or not exitOnBB), stop=target, oca_name="oca_buy", oca_type=strategy.oca.cancel)+if buyEntry and (breakout or pullback) and crossedCompound and (not range_ or not exitOnBB)+ strategy.entry("Buy", strategy.long, stop=target, oca_name="oca_buy", oca_type=strategy.oca.cancel)-strategy.entry("Buy", strategy.long, when=rangeBuyEntry, oca_name="oca_buy", oca_type=strategy.oca.cancel)+if rangeBuyEntry+ strategy.entry("Buy", strategy.long, oca_name="oca_buy", oca_type=strategy.oca.cancel)-strategy.close("Buy", when=(stopBuyEntry and (exitOnSignal or (exitOnSignalWhenInRange and range_))) or rangeSellEntry)+if (stopBuyEntry and (exitOnSignal or (exitOnSignalWhenInRange and range_))) or rangeSellEntry+ strategy.close("Buy")strategy.exit("ExitBuy", "Buy", stop = buyStop)-strategy.entry("Sell", strategy.short, when=sellEntry and reverse and crossedCompound and (not range_ or not exitOnBB), oca_name="oca_sell", oca_type=strategy.oca.cancel)+if sellEntry and reverse and crossedCompound and (not range_ or not exitOnBB)+ strategy.entry("Sell", strategy.short, oca_name="oca_sell", oca_type=strategy.oca.cancel)-strategy.entry("Sell", strategy.short, when=sellEntry and (breakout or pullback) and crossedCompound and (not range_ or not exitOnBB), stop=target, oca_name="oca_sell", oca_type=strategy.oca.cancel)+if sellEntry and (breakout or pullback) and crossedCompound and (not range_ or not exitOnBB)+ strategy.entry("Sell", strategy.short, stop=target, oca_name="oca_sell", oca_type=strategy.oca.cancel)-strategy.close("Sell", when=stopSellEntry and (exitOnSignal or (exitOnSignalWhenInRange and range_)))+if stopSellEntry and (exitOnSignal or (exitOnSignalWhenInRange and range_))+ strategy.close("Sell")strategy.exit("ExitSell", "Sell", stop = sellStop)Does it run in Pine Script v6?
Yes
Same 1 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.
⋯// © HeWhoMustNotBeNamed-//@version=5+//@version=6strategy("Breakout Trend Trading - V2", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)⋯Settings
Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Exit On Signal (no label in the script) | false | bool | close Buy close Sell |
| Exit Strategy when in Range | Disabled | string · options ["Disabled", "ExitOnSignal", "TrailStopLoss", "BollingerBands"] | exitOnSignalWhenInRange exitOnTrailingStopWhenInRange exitOnBB line 101 line 103 line 105 |
| Allow Immediate Compound (no label in the script) | false | bool | crossedCompound |
| Trade Direction | strategy.direction.long | value · options [strategy.direction.all, strategy.direction.long, strategy.direction.short] | line 356 |
| Trade Type | all | string · options ["all", "pullback", "breakout", "reverse", "pullback + breakout"] | buyEntry sellEntry stopBuyEntry stopSellEntry reverse breakout pullback |
| Display Mode | Targets | string · options ["Targets", "Target Channel", "Target with Stops", "Up Channel", "Down Channel"] | showTargets showChannel showTargetStops showUpChannel showDownChannel line 86 line 88 line 90 line 92 line 94 |
| Show Trailing Stop (no label in the script) | true | bool | showStopCompound |
| Show Target Levels (no label in the script) | true | bool | line 346 |
| Show Previous Levels (no label in the script) | false | bool | line 348 |
| Stop Multiplyer (no label in the script) | 6 | int · min 1 · max 10 · step 0.5 | target buyStop sellStop range |
| Compound Multiplyer (no label in the script) | 4 | int · min 1 · max 10 · step 0.5 | target buyStop sellStop range |
| Range Bars (no label in the script) | 100 | int · step 5 | range |
| Backtest Years (no label in the script) | 10 | int · min 1 · step 1 | inDateRange |
| Filter Highs/Lows for entry | true | bool | newHigh newLow |
| Short High Low Period (no label in the script) | 100 | int · step 10 | newHigh newLow |
| Long High Low Period (no label in the script) | 200 | int · step 10 | newHigh newLow |
| Check recent moving average alignment | true | bool | maHigh maLow |
| Lookback Period (no label in the script) | 300 | int · step 10 | alignedMaIndex |
| Include Partially Aligned (no label in the script) | true | bool | maAlignment line 210 |
| Moving Average Type | sma | string · options ["ema", "sma", "hma", "rma", "vwma", "wma"] | ma5 ma10 ma20 ma30 ma50 ma100 ma200 maAlignment line 180 line 182 line 184 line 186 line 188 |
| Alignment Index Threshold (no label in the script) | 50 | int · step 10 | maHigh maLow |
| Lookback Period PR (no label in the script) | 50 | int · step 10 | percentRank |
| Consider Weekly Supertrend (no label in the script) | false | bool | buyEntry sellEntry |
| Supertrend WMult (no label in the script) | 1 | int | SupertrendW DirW |
| Supertrend WPd (no label in the script) | 26 | int | SupertrendW DirW |
| Consider Monthly Supertrend (no label in the script) | false | bool | buyEntry sellEntry |
| Supertrend MMult (no label in the script) | 2 | int | SupertrendM DirM |
| Supertrend MPd (no label in the script) | 6 | int | SupertrendM DirM |
What it calculates
- ATR (
atr,ta.atrin v5)supertrendLengthsupertrendDistance · line 212 - Supertrend (
supertrend,ta.supertrendin v5)supertrendMult, supertrendLengthdir · line 298 - Supertrend (
supertrend,ta.supertrendin v5)supertrendMult, supertrendLengthsuperTrend · line 298 - ATR (
atr,ta.atrin v5)atrlengthatr · line 299 - Percentrank (
percentrank,ta.percentrankin v5)source, Lookback Period PR (50)percentRank · line 319 - Supertrend (
supertrend,ta.supertrendin v5)Supertrend WMult (1), Supertrend WPd (26)SupertrendW · line 320 - Supertrend (
supertrend,ta.supertrendin v5)Supertrend WMult (1), Supertrend WPd (26)DirW · line 320 - Supertrend (
supertrend,ta.supertrendin v5)Supertrend MMult (2), Supertrend MPd (6)SupertrendM · line 321 - Supertrend (
supertrend,ta.supertrendin v5)Supertrend MMult (2), Supertrend MPd (6)DirM · line 321 - BB (
bb,ta.bbin v5)close, 100, 2.5middle · line 324 - BB (
bb,ta.bbin v5)close, 100, 2.5upper · line 324 - BB (
bb,ta.bbin v5)close, 100, 2.5lower · line 324
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
The script has 103 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Buy long | buyEntry and reverse and crossedCompound and (not range or not exitOnBB) | On | 357 |
| Open Buy long | buyEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB) | On | 358 |
| Open Buy long | rangeBuyEntryrange and crossover(close, lower) and exitOnBB | On | 359 |
| Close Buy | (stopBuyEntry and (exitOnSignal or (exitOnSignalWhenInRange and range))) or rangeSellEntry | On | 360 |
| Exit ExitBuy stop | every bar | On | 361 |
| Open Sell short | sellEntry and reverse and crossedCompound and (not range or not exitOnBB) | On | 362 |
| Open Sell short | sellEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB) | On | 363 |
| Close Sell | stopSellEntry and (exitOnSignal or (exitOnSignalWhenInRange and range)) | On | 364 |
| Exit ExitSell stop | every bar | On | 365 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
No
No repainting patterns in the source.
- ClearHigher-timeframe data4 security call(s), none with lookahead on.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
- ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | −1.2% | +102.5% | 1 | 0% | 0.00 | 9.8% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | 0.0% | +5.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | 0.0% | +9.8% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | 0.0% | +8.4% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | 0.0% | +16.7% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | 0.0% | +21.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −40.5% | +148.3% | 2 | 50% | 0.23 | 47.0% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | 0.0% | +17.1% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
Higher-timeframe data for request.security(): BINANCE:BTCUSDT 12M (aggregated from Binance BTCUSDT 1M), BINANCE:BTCUSDT W (Binance BTCUSDT 1w), BINANCE:BTCUSDT M (Binance BTCUSDT 1M), fetched from Binance's public market data for each market.
Backtests are simulations on historical data and are not investment advice.
The trades
By market direction
| At entry, last 90 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 1 | 0% | −$23.91 |
| Sideways market | 0 | — | $0.00 |
| Falling market | 0 | — | $0.00 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
1.2%
The 95th percentile of the worst drawdown when the same 1 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 1.2% to 1.2%; the tick is what actually happened, 1.2%. Order luck alone moves it this much.
All 1 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 9 Jun 2025 108,843.00 | 29 Aug 2025 107,563.00 | 81 | −$23.91 |
Similar scripts
Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Breakout Trend Trading Strategy - V2 this page | — | v4 strategy | −1.2% | 1 | 9.8% |
| Breakout Trend Trading Strategy - V1 by Trendoscope | atr supertrend percentrank | v4 strategy | −23.1% | 3 | 32.5% |
| Bollinger Band Reversion Strategy by Zeal Terminal | bb atr | v5 strategy | +1.4% | 22 | 2.7% |
| TrendMaAlignmentStrategy - Long term trades by Trendoscope | atr bb | v4 strategy | −22.0% | 8 | 46.3% |
| Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN] by myncrypto | atr supertrend | v5 strategy | does not run in Zeal Terminal | ||
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 88 ms | With a workaround 1,000 bars in 331 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © HeWhoMustNotBeNamed//@version=4strategy("Breakout Trend Trading - V2", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)///////////////////////////////////////// Input ////////////////////////////////////////////////////////////////////exitOnSignal = input(false)exitStrategyOnRangingCondition = input(title="Exit Strategy when in Range", defval="Disabled", options=["Disabled", "ExitOnSignal", "TrailStopLoss", "BollingerBands"])allowImmediateCompound = input(false)tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])tradeType = input(title="Trade Type", defval="all", options=["all", "pullback", "breakout", "reverse", "pullback + breakout"])displayMode = input(title="Display Mode", defval="Targets", options=["Targets", "Target Channel", "Target with Stops", "Up Channel", "Down Channel"])showTrailingStop = input(true)showTargetLevels = input(true)showPreviousLevels = input(false)stopMultiplyer = input(6, minval=1, maxval=10, step=0.5)compoundMultiplyer = input(4, minval=1, maxval=10, step=0.5)rangeBars = input(100, step=5)backtestYears = input(10, minval=1, step=1)considerNewLongTermHighLows = input(true,"Filter Highs/Lows for entry")shortHighLowPeriod = input(100, step=10)longHighLowPeriod = input(200, step=10)considerMaAlignment = input(true,"Check recent moving average alignment")LookbackPeriod = input(300, step=10)includePartiallyAligned = input(true)MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])alignmentIndexThreshold = input(50, step=10)LookbackPeriodPR = input(50, step=10)considerWeeklySupertrend = input(false)SupertrendWMult = input(1)SupertrendWPd = input(26)considerMonthlySupertrend = input(false)SupertrendMMult = input(2)SupertrendMPd = input(6)//supertrendMult = input(6, minval=1, maxval=10, step=0.5)//supertrendLength = input(22, minval=1)//volumelength = input(title="Volume MA Length", defval=20, minval=10, step=10)//reverseVolumeLength = input(title="Volume MA Length", defval=20, minval=10, step=10)//volumeMaType = input(title="Volume MA Type", defval="hma", options=["ema", "sma", "hma", "rma", "swma", "vwma", "wma"])//trendVolumeMarkup = input(15, minval=0, maxval=100, step=5)//reverseVolumeMarkup = input(25, minval=0, maxval=100, step=5)//highVolumeMultiplyer = input(5, minval=2, maxval=10, step=1)//atrlength = input(22, minval=1)//trendTargetMult = input(1, minval=1, maxval=10, step=0.5)//reverseTargetMult = input(1, minval=1, maxval=10, step=0.5)//highBreakoutMult = input(2, minval=2, maxval=10, step=1)//trendValueMarkup = input(15, minval=0, maxval=100, step=5)//reverseValueMarkup = input(30, minval=0, maxval=100, step=5)//stopMultFactor = input(1, minval=0.5, maxval=10, step=0.5)//considerMaSupertrend = input(true)//source = input(ohlc4)//MaTypeMa = input(title="Volume MA Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])//MaLengthMa = input(10, step=10)//supertrendLengthMa = input(10, step=10)//supertrendMultMa = input(1, step=1)considerMaSupertrend = truesource = ohlc4MaTypeMa = "sma"MaLengthMa = 10supertrendLengthMa = 10supertrendMultMa = 1ignoreReverseBreakout = trueconsiderYearlyHighLow = trueconsiderOpenCloseBreakout = falsesupertrendMult = 6supertrendLength = 22volumelength = 20reverseVolumeLength = 20volumeMaType = "hma"trendVolumeMarkup = 15reverseVolumeMarkup = 25highVolumeMultiplyer = 5atrlength = 22trendTargetMult = 1reverseTargetMult = 1highBreakoutMult = 2trendValueMarkup = 15reverseValueMarkup = 30stopMultFactor = 1///////////////////////////// Display mode calculation ////////////////////////////////////////////////f_getDisplayModeVeriables(displayMode)=> bool showTargets = false bool showChannel = false bool showTargetStops = false bool showUpChannel = false bool showDownChannel = false if(displayMode == "Targets") showTargets := true if(displayMode == "Target Channel") showChannel := true if(displayMode == "Target with Stops") showTargetStops := true if(displayMode == "Up Channel") showUpChannel := true if(displayMode == "Down Channel") showDownChannel := true [showTargets,showChannel,showTargetStops,showUpChannel,showDownChannel]f_getRangeExitStrategy(exitStrategyOnRangingCondition)=> exitOnSignalWhenInRange = false exitOnTrailingStopWhenInRange = false exitOnBB = false if(exitStrategyOnRangingCondition == "ExitOnSignal") exitOnSignalWhenInRange := true if(exitStrategyOnRangingCondition == "TrailStopLoss") exitOnTrailingStopWhenInRange := true if(exitStrategyOnRangingCondition == "BollingerBands") exitOnBB := true [exitOnSignalWhenInRange, exitOnTrailingStopWhenInRange, exitOnBB] ///////////////////////////// Get Price breakout values ////////////////////////////////////////////////f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)=> trendBreakout = false if(abs(close[1] - close) > atr * trendTargetMult) or (high-low > 2 * atr * trendTargetMult and considerOpenCloseBreakout) trendBreakout := true reverseBreakout = false if(abs(close[1] - close) > atr * reverseTargetMult) or (high-low > 2 * atr * reverseTargetMult and considerOpenCloseBreakout) reverseBreakout := true highBreakout = false if(abs(close[1] - close) > atr * highBreakoutMult) or (high-low > 2 * atr * highBreakoutMult and considerOpenCloseBreakout) highBreakout:=true [trendBreakout, reverseBreakout, highBreakout]///////////////////////////// Get Volume breakout values ////////////////////////////////////////////////f_getVolumeBreakout(vma, vmareverse, trendVolumeMarkup, reverseVolumeMarkup, highVolumeMarkup)=> vmaMarkup = vma * (1+(trendVolumeMarkup/100)) vmaReverseMarkup = vmareverse * (1+(reverseVolumeMarkup/100)) vmaHighVolumeMarkup = vma * highVolumeMarkup trendVolumeBreakout = vmaMarkup < volume or na(volume) stopVolumeBreakout = vmaReverseMarkup < volume or na(volume) highVolumeBreakout = vmaHighVolumeMarkup < volume and not na(volume) [trendVolumeBreakout, stopVolumeBreakout, highVolumeBreakout]//////////////////////////////////// Get Candle color //////////////////////////////////////////////////f_getBarState(dir,trendBreakout, reverseBreakout, highBreakout, trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout)=> barState = 0 if(close > close[1] and ( (dir == -1 and trendBreakout and trendVolumeBreakout) or (dir == 1 and reverseBreakout and reverseVolumeBreakout) or highVolumeBreakout or highBreakout)) barState := 1 if(close < close[1] and ( (dir == 1 and trendBreakout and trendVolumeBreakout) or (dir == -1 and reverseBreakout and reverseVolumeBreakout) or highVolumeBreakout or highBreakout)) barState := -1 barState//////////////////////////////////// Calculate target values //////////////////////////////////////////////////f_getTargets(barState, trendValueMarkup, reverseValueMarkup, stopMultFactor, dir, atr)=> diff = max(high-low, max(abs(high-close[1]), abs(low-close[1]))) upTarget = (barState == 1) ? high + ((dir==-1?trendValueMarkup:reverseValueMarkup)/100)*diff : na downTarget = (barState == -1) ? low - ((dir==1?trendValueMarkup:reverseValueMarkup)/100)*diff : na stopUpTarget = (barState == 1) ? low - atr * stopMultFactor : na stopDownTarget = (barState == -1) ? high + atr * stopMultFactor : na lastBreakout = barState lastBreakout:= lastBreakout == 0? nz(lastBreakout[1], 0): lastBreakout [upTarget,stopUpTarget,downTarget,stopDownTarget,lastBreakout]//////////////////////////////////// Calculate target values //////////////////////////////////////////////////f_getChannels(upTarget, stopUpTarget, downTarget, stopDownTarget)=> upLine = upTarget downLine = downTarget stopUpLine = stopUpTarget stopDownLine = stopDownTarget upLine := na(upLine) ? nz(upLine[1],na) : upLine downLine := na(downLine) ? nz(downLine[1],na) : downLine stopUpLine := na(stopUpLine) ? nz(stopUpLine[1],na) : stopUpLine stopDownLine := na(stopDownLine) ? nz(stopDownLine[1],na) : stopDownLine [upLine,stopUpLine,downLine,stopDownLine]//////////////////////////////////// Calculate Yearly High Low //////////////////////////////////////////////////f_getYearlyHighLowCondition(considerYearlyHighLow)=> yhigh = security(syminfo.tickerid, '12M', high[1]) ylow = security(syminfo.tickerid, '12M', low[1]) yhighlast = yhigh[365] ylowlast = ylow[365] yhighllast = yhigh[2 * 365] ylowllast = ylow[2 * 365] yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast)) yearlyHighCondition = ( (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast)) yearlyLowCondition = ( (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow label_x = time+(60*60*24*1000*1) [yearlyHighCondition,yearlyLowCondition]f_getMovingAverage(source, MAType, length)=> ma = sma(source, length) if(MAType == "ema") ma := ema(source,length) if(MAType == "hma") ma := hma(source,length) if(MAType == "rma") ma := rma(source,length) if(MAType == "vwma") ma := vwma(source,length) if(MAType == "wma") ma := wma(source,length) maf_getMaAlignment(MAType, includePartiallyAligned)=> ma5 = f_getMovingAverage(close,MAType,5) ma10 = f_getMovingAverage(close,MAType,10) ma20 = f_getMovingAverage(close,MAType,20) ma30 = f_getMovingAverage(close,MAType,30) ma50 = f_getMovingAverage(close,MAType,50) ma100 = f_getMovingAverage(close,MAType,100) ma200 = f_getMovingAverage(close,MAType,200) upwardScore = 0 upwardScore := close > ma5? upwardScore+1:upwardScore upwardScore := ma5 > ma10? upwardScore+1:upwardScore upwardScore := ma10 > ma20? upwardScore+1:upwardScore upwardScore := ma20 > ma30? upwardScore+1:upwardScore upwardScore := ma30 > ma50? upwardScore+1:upwardScore upwardScore := ma50 > ma100? upwardScore+1:upwardScore upwardScore := ma100 > ma200? upwardScore+1:upwardScore upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200 downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200 upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0f_supertrendOnMa(source, MaType, MaLength, supertrendLength, supertrendMult)=> supertrendDistance = supertrendMult * atr(supertrendLength) ma = f_getMovingAverage(source,MaType, MaLength) longStop = ma - supertrendDistance longStopPrev = nz(longStop[1], longStop) longStop := ma > longStopPrev ? max(longStop, longStopPrev) : longStop shortStop = ma + supertrendDistance shortStopPrev = nz(shortStop[1], shortStop) shortStop := ma < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop dir = 1 dir := nz(dir[1], dir) dir := dir == -1 and ma > shortStopPrev ? 1 : dir == 1 and ma < longStopPrev ? -1 : dir supertrend = dir==1 ? longStop: shortStop [supertrend, ma, dir] //////////////////////////////////// Calculate Buy Sell signals //////////////////////////////////////////////////f_calculateSignals(dir,lastBreakout,ignoreReverseBreakout, upLine, stopUpLine, downLine, stopDownLine)=> greenBreakout = (lastBreakout > 0) or ignoreReverseBreakout redBreakout = (lastBreakout < 0) or ignoreReverseBreakout buySignal = dir==-1? false : (crossover(low, upLine[1]) and greenBreakout and close > downLine[1]) or (crossover(low, stopDownLine[1]) and redBreakout) stopBuySignal = (crossunder(dir==-1?close:low, downLine[1]) or crossunder(dir==-1?close:low, stopUpLine[1])) sellSignal = dir==1? false : (crossunder(high, downLine[1]) and redBreakout and close < upLine[1]) or (crossunder(high, stopUpLine[1]) and greenBreakout) stopSellSignal = (crossover(dir==1?close:high, upLine[1]) or crossover(dir==1?close:high, stopDownLine[1])) [buySignal,stopBuySignal,sellSignal,stopSellSignal]//////////////////////////////////// Calculate new high low condition //////////////////////////////////////////////////f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=> newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows [newHigh,newLow] //////////////////////////////////// Calculate Trade Flags /////////////////////////////////////////////////////f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange, tradeType, newHigh, maHigh, newLow, maLow)=> buyPrerequisites = inDateRange and yearlyHighCondition and newHigh and maHigh sellPrerequisites = inDateRange and yearlyLowCondition and newLow and maLow buyEntry = buyPrerequisites? (dir == -1 and barState != 0) ? true : buySignal : false sellEntry = sellPrerequisites? dir == 1 and barState != 0 ? true : sellSignal : false stopBuyEntry = stopBuySignal and barState != 1 and inDateRange stopSellEntry = stopSellSignal and barState != -1 and inDateRange reverse = (buySignal or sellSignal and (buyPrerequisites or sellPrerequisites)) and (tradeType == "all" or tradeType == "reverse") breakout = ((buyPrerequisites and dir == -1 and barState == 1) or (sellPrerequisites and dir == 1 and barState == -1)) and (tradeType == "all" or tradeType == "breakout" or tradeType == "pullback + breakout") pullback = ((buyPrerequisites and dir == -1 and barState == -1) or (sellPrerequisites and dir == 1 and barState == 1)) and (tradeType == "all" or tradeType == "pullback" or tradeType == "pullback + breakout") [buyEntry, sellEntry, stopBuyEntry, stopSellEntry, breakout, pullback, reverse]//////////////////////////////////// Calculate trailing stop //////////////////////////////////////////////////f_calculateTrailingStop(stop)=> strategy.position_size > 0? (stop > stop[1]? stop : stop[1]) : strategy.position_size < 0 ? (stop < stop[1]? stop : stop[1]) : stop//////////////////////////////////// Calculate stop and compound //////////////////////////////////////////////////f_calculateStopAndCompound(buyEntry, sellEntry, breakout, pullback, reverse, upLine, stopUpLine, downLine, stopDownLine, atr, stopMultiplyer, compoundMultiplyer, barState, exitOnTrailingStopWhenInRange, exitOnBB)=> target = reverse ? close: breakout and buyEntry ? upLine : breakout and sellEntry? downLine: buyEntry and pullback ? stopDownLine : sellEntry and pullback? stopUpLine : strategy.position_size > 0 ? low : strategy.position_size < 0? high : close buyStop = target - (stopMultiplyer * atr) sellStop = target + (stopMultiplyer * atr) range = false range := range[1] and exitOnBB? close > buyStop[1] and close < sellStop[1]:strategy.position_size != 0 and buyStop[1] == buyStop[rangeBars+1] and sellStop[1] == sellStop[rangeBars+1] if(range and exitOnBB) buyStop := buyStop[1] sellStop := sellStop[1] else if(barState > 0 or strategy.position_size > 0) buyStop := target - (stopMultiplyer * atr) sellStop := target + (compoundMultiplyer * atr) buyStop := range and exitOnTrailingStopWhenInRange? max(buyStop, buyStop[1]): (buyStop < buyStop[1] or close < sellStop[1])? buyStop[1] : buyStop sellStop := range and exitOnTrailingStopWhenInRange? min(sellStop, sellStop[1]): (sellStop < sellStop[1] or close < sellStop[1]) ? sellStop[1] : sellStop else if(barState < 0 or strategy.position_size < 0) buyStop := target - (compoundMultiplyer * atr) sellStop := target + (stopMultiplyer * atr) sellStop := range and exitOnTrailingStopWhenInRange? min(sellStop, sellStop[1]) : (sellStop > sellStop[1] or close > buyStop[1])? sellStop[1] : sellStop buyStop := range and exitOnTrailingStopWhenInRange? max(buyStop, buyStop[1]): (buyStop > buyStop[1] or close > buyStop[1]) ? buyStop[1] : buyStop [target, buyStop, sellStop, range] //////////////////////////////////// Draw Lines with labels //////////////////////////////////////////////////f_drawLinesWithLabels(target, lbl, linecolor)=> line_x1 = time+(60*60*24*1000*1) line_x2 = time+(60*60*24*1000*7) label_x = time+(60*60*24*1000*4) targetLine = line.new(x1=line_x1, y1=target, x2=line_x2, y2=target, color=linecolor, xloc=xloc.bar_time) targetLabel = label.new(x=label_x, y=target, text=lbl + " : "+tostring(target), xloc=xloc.bar_time, style=label.style_none, textcolor=color.black, size=size.normal) [targetLine,targetLabel]//////////////////////////////////// Delete Lines with labels //////////////////////////////////////////////////f_deleteLinesWithLabels(targetLine, targetLabel, last)=> line.delete(id=last?targetLine[1]:targetLine) label.delete(id=last?targetLabel[1]:targetLabel)/////////////////////////////////////////////////// Calculate Trend //////////////////////////////////////////////////////inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)[showTargets,showChannel,showTargetStops,showUpChannel,showDownChannel] = f_getDisplayModeVeriables(displayMode)vma = f_getMovingAverage(volume, volumeMaType, volumelength)vmareverse = f_getMovingAverage(volume, volumeMaType, reverseVolumeLength)[superTrend, dir] = supertrend(supertrendMult, supertrendLength)atr = atr(atrlength)[trendBreakout, reverseBreakout, highBreakout] = f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)[trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout] = f_getVolumeBreakout(vma, vmareverse, trendVolumeMarkup, reverseVolumeMarkup, highVolumeMultiplyer)barState = f_getBarState(dir,trendBreakout, reverseBreakout, highBreakout, trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout)[upTarget,stopUpTarget,downTarget,stopDownTarget, lastBreakout] = f_getTargets(barState, trendValueMarkup, reverseValueMarkup, stopMultFactor, dir, atr)[upLine,stopUpLine,downLine,stopDownLine] = f_getChannels(upTarget, stopUpTarget, downTarget, stopDownTarget)[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)alignedMaIndex = sum(maAlignment,LookbackPeriod)maHigh = alignedMaIndex > alignmentIndexThreshold or not considerMaAlignmentmaLow = alignedMaIndex < -alignmentIndexThreshold or not considerMaAlignment[newHigh, newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)[supertrendMa, ma, dirMa] = f_supertrendOnMa(source, MaTypeMa, MaLengthMa, supertrendLengthMa, supertrendMultMa)//////////////////////////////////////// Calculate Trade //////////////////////////////////////////////////////[exitOnSignalWhenInRange, exitOnTrailingStopWhenInRange, exitOnBB] = f_getRangeExitStrategy(exitStrategyOnRangingCondition)[buySignal,stopBuySignal,sellSignal,stopSellSignal] = f_calculateSignals(dir,lastBreakout,ignoreReverseBreakout, upLine, stopUpLine, downLine, stopDownLine)[buyEntry, sellEntry, stopBuyEntry, stopSellEntry, breakout, pullback, reverse] = f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange, tradeType, newHigh, maHigh, newLow, maLow)[target, buyStop, sellStop, range] = f_calculateStopAndCompound(buyEntry, sellEntry, breakout, pullback, reverse, upLine, stopUpLine, downLine, stopDownLine, atr, stopMultiplyer, compoundMultiplyer, barState, exitOnTrailingStopWhenInRange, exitOnBB)//crossedCompound = (strategy.position_size > 0 ? strategy.position_avg_price < buyStop : strategy.position_size < 0 ? strategy.position_avg_price > sellStop : true) or allowImmediateCompoundcrossedCompound = (strategy.position_size > 0 ? close > sellStop : strategy.position_size < 0 ? close < buyStop : true) or allowImmediateCompoundpercentRank = percentrank(source, LookbackPeriodPR)[SupertrendW, DirW] = security(syminfo.tickerid, 'W', supertrend(SupertrendWMult, SupertrendWPd), lookahead = true)[SupertrendM, DirM] = security(syminfo.tickerid, 'M', supertrend(SupertrendMMult, SupertrendMPd), lookahead = true)buyEntry := buyEntry and (((dirMa == 1 or not considerMaSupertrend) and percentRank > 50) or strategy.netprofit >= 0) and (DirW == -1 or not considerWeeklySupertrend) and (DirM == -1 or not considerMonthlySupertrend)sellEntry := sellEntry and (((dirMa == -1 or not considerMaSupertrend) and percentRank < 50) or strategy.netprofit >= 0) and (DirW == 1 or not considerWeeklySupertrend) and (DirM == 1 or not considerMonthlySupertrend)[middle, upper, lower] = bb(close, 100, 2.5)rangeBuyEntry = range and crossover(close, lower) and exitOnBBrangeSellEntry = range and crossunder(close, upper) and exitOnBB//////////////////////////////////////// Plot //////////////////////////////////////////////////////plot(showChannel?upLine:na, title="UpChannel", color=color.green, linewidth=2, style=plot.style_line)plot(showChannel?downLine:na, title="downChannel", color=color.red, linewidth=2, style=plot.style_line)plotshape(showTargets or showTargetStops?upTarget:na, title="UpTarget", color=color.green, style=shape.arrowup, location = location.absolute, size=size.tiny)plotshape(showTargets or showTargetStops?downTarget:na, title="DownTarget", color=color.red, style=shape.arrowdown, location = location.absolute, size=size.tiny)plotshape(showTargetStops?stopUpTarget:na, title="UpStop", color=color.green, style=shape.arrowup, location = location.absolute, size=size.tiny)plotshape(showTargetStops?stopDownTarget:na, title="DownStop", color=color.red, style=shape.arrowdown, location = location.absolute, size=size.tiny)plot(showUpChannel?upLine:na, title="UpChannel", color=color.green, linewidth=2, style=plot.style_line)plot(showUpChannel?stopUpLine:na, title="StopUpChannel", color=color.red, linewidth=2, style=plot.style_line)plot(showDownChannel?stopDownLine:na, title="StopDownChannel", color=color.green, linewidth=2, style=plot.style_line)plot(showDownChannel?downLine:na, title="DownChannel", color=color.red, linewidth=2, style=plot.style_line)channelview = showChannel or showUpChannel or showDownChannelbuyStopLineColor = range ? color.purple : strategy.position_size > 0 ?color.red:strategy.position_size < 0 ?color.green:color.bluesellStopLineColor = range ? color.purple : strategy.position_size > 0?color.green:strategy.position_size < 0 ?color.red:color.blueshowStopCompound = showTrailingStop and (range or strategy.position_size != 0) and not channelviewplot(showStopCompound? buyStop : na, title="DownStop", color=buyStopLineColor, linewidth=2, style=plot.style_stepline)plot(showStopCompound? sellStop : na, title="UpStop", color=sellStopLineColor, linewidth=2, style=plot.style_stepline)barcolor(barState==1?color.lime:barState==-1?color.orange:color.silver)//////////////////////////////////////// Plot Trade //////////////////////////////////////////////////////if(buyEntry or sellEntry) and (showTargetLevels) and (breakout or pullback or reverse) [targetLine, targetLabel] = f_drawLinesWithLabels(target,buyEntry?"Long":"Short",color.blue) if(not showPreviousLevels) f_deleteLinesWithLabels(targetLine, targetLabel, true)if(buyEntry or sellEntry or strategy.position_size != 0) [stopLine, stopLabel] = f_drawLinesWithLabels(buyEntry or strategy.position_size > 0?buyStop:sellStop,"Stop",color.red) [compoundLine, compoundLabel] = f_drawLinesWithLabels(buyEntry or strategy.position_size > 0?sellStop:buyStop,"Compound",color.green) f_deleteLinesWithLabels(stopLine, stopLabel, true) f_deleteLinesWithLabels(compoundLine, compoundLabel, true)//////////////////////////////////////// Trade //////////////////////////////////////////////////////strategy.risk.allow_entry_in(tradeDirection)strategy.entry("Buy", strategy.long, when=buyEntry and reverse and crossedCompound and (not range or not exitOnBB), oca_name="oca_buy", oca_type=strategy.oca.cancel)strategy.entry("Buy", strategy.long, when=buyEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB), stop=target, oca_name="oca_buy", oca_type=strategy.oca.cancel)strategy.entry("Buy", strategy.long, when=rangeBuyEntry, oca_name="oca_buy", oca_type=strategy.oca.cancel)strategy.close("Buy", when=(stopBuyEntry and (exitOnSignal or (exitOnSignalWhenInRange and range))) or rangeSellEntry)strategy.exit("ExitBuy", "Buy", stop = buyStop)strategy.entry("Sell", strategy.short, when=sellEntry and reverse and crossedCompound and (not range or not exitOnBB), oca_name="oca_sell", oca_type=strategy.oca.cancel)strategy.entry("Sell", strategy.short, when=sellEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB), stop=target, oca_name="oca_sell", oca_type=strategy.oca.cancel)strategy.close("Sell", when=stopSellEntry and (exitOnSignal or (exitOnSignalWhenInRange and range)))strategy.exit("ExitSell", "Sell", stop = sellStop)