Pine Script v4 · Strategy
Breakout Trend Trading Strategy - V1
A Pine Script v4 strategy built on ATR (supertrendLength), Supertrend (supertrendMult, supertrendLength) and Percentrank (source, LookbackPeriod). It has 6 order rules, 2 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 2 commission. 10 settings; defaults include Display Mode Targets, Stop Multiplyer 6 and Compound Multiplyer 1.
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 - V1 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 - V1 do on BTCUSDT 1D with default settings?
- −23.14%
- From 26 Jan 2024 to 21 Oct 2026, over 3 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can Breakout Trend Trading Strategy - V1 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 - V1 use a stop loss?
- Yes
- strategy.exit sets a stop on line 328, 331.
- Does Breakout Trend Trading Strategy - V1 run in Zeal Terminal?
- Yes
- It compiles in 83 ms and runs 1,000 bars in 328 ms, in the browser.
BTCUSDT · 1D · default settings
- UpTarget
- DownTarget
- DownStop
- UpStop
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- −23.14%
- −$462.77
- Buy and hold
- +102.5%
- same period
- Closed trades
- 3
- 1 won · 2 lost
- Profitable
- 33.3%
- of closed trades
- Profit factor
- 0.23
- gross profit ÷ gross loss
- Max drawdown
- 32.53%
- −$650.55
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
8 settings have no label
In the settings dialog exitOnSignal (line 67), allowImmediateCompound (line 69), showTrailingStop (line 71), showTargetLevels (line 72), showPreviousLevels (line 73), stopMultiplyer (line 74), compoundMultiplyer (line 75), backtestYears (line 76) 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 326, 327, 329, 330. 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, percentrank → ta.percentrank, sum → math.sum.
- 4 strategy calls use the when = argument (line 326, 327, 329, 330). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
VerifiedSame 3 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 3: //@version=4 → //@version=5
- Line 98: abs → math.abs
- Line 102: abs → math.abs
- Line 106: abs → math.abs
- Line 129: max → math.max
- Line 129: max → math.max
36 more edits
- Line 129: abs → math.abs
- Line 129: abs → math.abs
- Line 150: security → request.security
- Line 151: security → request.security
- Line 157: max → math.max
- Line 157: max → math.max
- Line 157: min → math.min
- Line 159: min → math.min
- Line 159: min → math.min
- Line 159: max → math.max
- Line 174: sma → ta.sma
- Line 176: ema → ta.ema
- Line 178: hma → ta.hma
- Line 180: rma → ta.rma
- Line 182: vwma → ta.vwma
- Line 184: wma → ta.wma
- Line 187: atr → ta.atr
- Line 192: max → math.max
- Line 196: min → math.min
- Line 227: crossover → ta.crossover
- Line 227: crossover → ta.crossover
- Line 228: crossunder → ta.crossunder
- Line 228: crossunder → ta.crossunder
- Line 229: crossunder → ta.crossunder
- Line 229: crossunder → ta.crossunder
- Line 230: crossover → ta.crossover
- Line 230: crossover → ta.crossover
- Line 234: highest → ta.highest
- Line 234: highest → ta.highest
- Line 235: lowest → ta.lowest
- Line 235: lowest → ta.lowest
- Line 263: tostring → str.tostring
- Line 273: supertrend → ta.supertrend
- Line 274: atr → ta.atr
- Line 283: percentrank → ta.percentrank
- Line 290: sum → math.sum
⋯// © HeWhoMustNotBeNamed-//@version=4+//@version=5strategy("Breakout Trend Trading - V1", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.cash_per_order, pyramiding = 1, commission_value = 2)⋯ 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) maf_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 = ((crossover(dir==-1?high:low, upLine[1]) and greenBreakout and close > downLine[1]) or (crossover(dir==-1?high:low, stopDownLine[1]) and redBreakout) or ((barState == 1) and (dir==-1?high:low) > upLine[1]))+ buySignal = ((ta.crossover(dir==-1?high:low, upLine[1]) and greenBreakout and close > downLine[1]) or (ta.crossover(dir==-1?high:low, stopDownLine[1]) and redBreakout) or ((barState == 1) and (dir==-1?high:low) > upLine[1]))- 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 = ((crossunder(dir==1?low:high, downLine[1]) and redBreakout and close < upLine[1]) or (crossunder(dir==1?low:high, stopUpLine[1]) and greenBreakout) or (barState == -1) and (dir==1?low:high) < downLine[1])+ sellSignal = ((ta.crossunder(dir==1?low:high, downLine[1]) and redBreakout and close < upLine[1]) or (ta.crossunder(dir==1?low:high, stopUpLine[1]) and greenBreakout) or (barState == -1) and (dir==1?low:high) < downLine[1])- 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]⋯ 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]⋯vma = f_getMovingAverage(volume, volumeMaType, volumelength)-[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)⋯//////////////////////////////////////// Calculate Trade //////////////////////////////////////////////////////-percentRank = percentrank(source, LookbackPeriod)+percentRank = ta.percentrank(source, LookbackPeriod)[buySignal,stopBuySignal,sellSignal,stopSellSignal] = f_calculateBuySellFlags(dir,lastBreakout,ignoreReverseBreakout, barState, upLine, stopUpLine, downLine, stopDownLine)⋯maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)-alignedMaIndex = sum(maAlignment,LookbackPeriod)+alignedMaIndex = math.sum(maAlignment,LookbackPeriod)maHigh = alignedMaIndex > alignmentIndexThreshold or not considerMaAlignment⋯Same 3 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 67: input() → input.bool()
- Line 69: input() → input.bool()
- Line 70: input() → input.string()
- Line 71: input() → input.bool()
- Line 72: input() → input.bool()
- Line 73: input() → input.bool()
7 more edits
- Line 74: input() → input.int()
- Line 75: input() → input.int()
- Line 76: input() → input.int()
- Line 326: when = buyEntry and crossedCompound → if block
- Line 327: when = stopBuyEntry and exitOnSignal → if block
- Line 329: when = sellEntry and crossedCompound → if block
- Line 330: when = stopSellEntry and exitOnSignal → if block
⋯supertrendMultMa = 1-exitOnSignal = input(false)+exitOnSignal = input.bool(false)tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])-allowImmediateCompound = input(false)+allowImmediateCompound = input.bool(false)-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(1, minval=1, maxval=10, step=0.5)+compoundMultiplyer = input.int(1, minval=1, maxval=10, step=0.5)-backtestYears = input(10, minval=1, step=1)+backtestYears = input.int(10, minval=1, step=1)///////////////////////////// Display mode calculation ////////////////////////////////////////////////⋯strategy.risk.allow_entry_in(tradeDirection)-strategy.entry("Buy", strategy.long, when=buyEntry and crossedCompound)+if buyEntry and crossedCompound+ strategy.entry("Buy", strategy.long)-strategy.close("Buy", when=stopBuyEntry and exitOnSignal)+if stopBuyEntry and exitOnSignal+ strategy.close("Buy")strategy.exit("ExitBuy", "Buy", stop = buyStop)-strategy.entry("Sell", strategy.short, when=sellEntry and crossedCompound)+if sellEntry and crossedCompound+ strategy.entry("Sell", strategy.short)-strategy.close("Sell", when=stopSellEntry and exitOnSignal)+if stopSellEntry and exitOnSignal+ strategy.close("Sell")strategy.exit("ExitSell", "Sell", stop = sellStop)Does it run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 3 before, 8 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// © HeWhoMustNotBeNamed-//@version=5+//@version=6strategy("Breakout Trend Trading - V1", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.cash_per_order, pyramiding = 1, commission_value = 2)⋯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 |
| Trade Direction | strategy.direction.long | value · options [strategy.direction.all, strategy.direction.long, strategy.direction.short] | line 325 |
| Allow Immediate Compound (no label in the script) | false | bool | crossedCompound |
| Display Mode | Targets | string · options ["Targets", "Target Channel", "Target with Stops", "Up Channel", "Down Channel"] | showTargets showChannel showTargetStops showUpChannel showDownChannel line 84 line 86 line 88 line 90 line 92 |
| Show Trailing Stop (no label in the script) | true | bool | DownStop UpStop |
| Show Target Levels (no label in the script) | true | bool | line 314 |
| Show Previous Levels (no label in the script) | false | bool | line 316 |
| Stop Multiplyer (no label in the script) | 6 | int · min 1 · max 10 · step 0.5 | buyStop sellStop |
| Compound Multiplyer (no label in the script) | 1 | int · min 1 · max 10 · step 0.5 | buyStop sellStop |
| Backtest Years (no label in the script) | 10 | int · min 1 · step 1 | inDateRange |
What it calculates
- ATR (
atr,ta.atrin v5)supertrendLengthsupertrendDistance · line 187 - Supertrend (
supertrend,ta.supertrendin v5)supertrendMult, supertrendLengthdir · line 273 - Supertrend (
supertrend,ta.supertrendin v5)supertrendMult, supertrendLengthsuperTrend · line 273 - ATR (
atr,ta.atrin v5)atrlengthatr · line 274 - Percentrank (
percentrank,ta.percentrankin v5)source, LookbackPeriodpercentRank · line 283
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 75 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 crossedCompound | On | 326 |
| Close Buy | stopBuyEntry and exitOnSignal | On | 327 |
| Exit ExitBuy stop | every bar | On | 328 |
| Open Sell short | sellEntry and crossedCompound | On | 329 |
| Close Sell | stopSellEntry and exitOnSignal | On | 330 |
| Exit ExitSell stop | every bar | On | 331 |
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 data2 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 | −23.1% | +102.5% | 3 | 33% | 0.23 | 32.5% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −6.2% | +5.5% | 1 | 0% | 0.00 | 6.2% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −52.8% | +9.8% | 2 | 0% | 0.00 | 52.8% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −8.8% | +8.4% | 1 | 0% | 0.00 | 8.8% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −67.8% | +16.7% | 3 | 0% | 0.00 | 67.8% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +51.0% | +21.5% | 1 | 100% | — | 10.3% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +7.7% | +148.3% | 5 | 40% | 1.08 | 49.8% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −18.2% | +17.1% | 2 | 0% | 0.00 | 18.2% | 8 May 2026 – 21 Oct 2026 |
Higher-timeframe data for request.security(): BINANCE:BTCUSDT 12M (aggregated from 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 | 2 | 0% | −$597.75 |
| Sideways market | 1 | 100% | $134.98 |
| 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?
29.9%
The 95th percentile of the worst drawdown when the same 3 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 23.1% to 29.9%; the tick is what actually happened, 29.9%. Order luck alone moves it this much.
All 3 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 29 Feb 2024 62,432.10 | 5 Jul 2024 56,214.70 | 127 | −$203.18 |
| long | 16 Dec 2024 104,464.00 | 28 Feb 2025 81,756.60 | 74 | −$394.58 |
| long | 3 May 2025 96,887.10 | 10 Oct 2025 106,490.00 | 160 | $134.98 |
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 - V1 this page | — | v4 strategy | −23.1% | 3 | 32.5% |
| Breakout Trend Trading Strategy - V2 by Trendoscope | atr supertrend percentrank | v4 strategy | −1.2% | 1 | 9.8% |
| 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 83 ms | With a workaround 1,000 bars in 328 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 - V1", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.cash_per_order, pyramiding = 1, commission_value = 2)///////////////////////////////////////// Input //////////////////////////////////////////////////////////////////////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)//volumeMaType = input(title="Volume MA Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])//trendVolumeMarkup = input(15, minval=0, maxval=100, step=5)//reverseVolumeMarkup = input(15, 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)//considerNewLongTermHighLows = input(true,"Filter Highs/Lows for entry")//shortHighLowPeriod = input(120, step=10)//longHighLowPeriod = input(180, step=10)//considerMaAlignment = input(true,"Check recent moving average alignment")//MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])//LookbackPeriod = input(200, step=10)//alignmentIndexThreshold = input(0, step=10)//includePartiallyAligned = input(true)//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)supertrendMult = 6supertrendLength = 22volumelength = 20volumeMaType = "sma"trendVolumeMarkup = 15reverseVolumeMarkup = 25highVolumeMultiplyer = 5atrlength = 22trendTargetMult = 1reverseTargetMult = 1highBreakoutMult = 2trendValueMarkup = 15reverseValueMarkup = 30stopMultFactor = 1considerYearlyHighLow = trueignoreReverseBreakout = true//allowImmediateCompound = trueconsiderOpenCloseBreakout = falseallowReduceCompound = trueconsiderNewLongTermHighLows = trueshortHighLowPeriod = 120longHighLowPeriod = 180considerMaAlignment = trueMAType = "sma"LookbackPeriod = 280alignmentIndexThreshold = 0includePartiallyAligned = trueconsiderMaSupertrend = truesource = ohlc4MaTypeMa = "sma"MaLengthMa = 10supertrendLengthMa = 10supertrendMultMa = 1exitOnSignal = input(false)tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])allowImmediateCompound = input(false)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(1, minval=1, maxval=10, step=0.5)backtestYears = input(10, minval=1, step=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]///////////////////////////// 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, trendVolumeMarkup, reverseVolumeMarkup, highVolumeMarkup)=> vmaMarkup = vma * (1+(trendVolumeMarkup/100)) vmaReverseMarkup = vma * (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 [yearlyHighCondition,yearlyLowCondition]//////////////////////////////////// Calculate Trade Flags /////////////////////////////////////////////////////f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange)=> buyPrerequisites = inDateRange and yearlyHighCondition sellPrerequisites = inDateRange and yearlyLowCondition buyEntry = buySignal and yearlyHighCondition and barState != -1 and inDateRange sellEntry = sellSignal and yearlyLowCondition and barState != 1 and inDateRange stopBuyEntry = stopBuySignal and barState != 1 and inDateRange stopSellEntry = stopSellSignal and barState != -1 and inDateRange [buyEntry, sellEntry, stopBuyEntry, stopSellEntry]//////////////////////////////////// Get Moving average ///////////////////////////////////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_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]f_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) : 0//////////////////////////////////// Calculate Buy Sell signals //////////////////////////////////////////////////f_calculateBuySellFlags(dir,lastBreakout,ignoreReverseBreakout, barState, upLine, stopUpLine, downLine, stopDownLine)=> greenBreakout = (lastBreakout > 0) or ignoreReverseBreakout redBreakout = (lastBreakout < 0) or ignoreReverseBreakout buySignal = ((crossover(dir==-1?high:low, upLine[1]) and greenBreakout and close > downLine[1]) or (crossover(dir==-1?high:low, stopDownLine[1]) and redBreakout) or ((barState == 1) and (dir==-1?high:low) > upLine[1])) stopBuySignal = (crossunder(dir==-1?close:low, downLine[1]) or crossunder(dir==-1?close:low, stopUpLine[1])) sellSignal = ((crossunder(dir==1?low:high, downLine[1]) and redBreakout and close < upLine[1]) or (crossunder(dir==1?low:high, stopUpLine[1]) and greenBreakout) or (barState == -1) and (dir==1?low:high) < downLine[1]) 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 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(target, atr, stopMultiplyer, compoundMultiplyer, barState)=> buyStop = target - (stopMultiplyer * atr) sellStop = target + (stopMultiplyer * atr) if(barState > 0 or strategy.position_size > 0) buyStop := target - (stopMultiplyer * atr) sellStop := target + (compoundMultiplyer * atr) buyStop := (buyStop < buyStop[1] or close < sellStop[1])? buyStop[1] : buyStop sellStop := (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 := (sellStop > sellStop[1] or close > buyStop[1])? sellStop[1] : sellStop buyStop := (buyStop > buyStop[1] or close > buyStop[1]) ? buyStop[1] : buyStop [buyStop, sellStop] //////////////////////////////////// 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)[superTrend, dir] = supertrend(supertrendMult, supertrendLength)atr = atr(atrlength)[trendBreakout, reverseBreakout, highBreakout] = f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)[trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout] = f_getVolumeBreakout(vma, 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)[supertrendMa, ma, dirMa] = f_supertrendOnMa(source, MaTypeMa, MaLengthMa, supertrendLengthMa, supertrendMultMa)//////////////////////////////////////// Calculate Trade //////////////////////////////////////////////////////percentRank = percentrank(source, LookbackPeriod)[buySignal,stopBuySignal,sellSignal,stopSellSignal] = f_calculateBuySellFlags(dir,lastBreakout,ignoreReverseBreakout, barState, upLine, stopUpLine, downLine, stopDownLine)[newHigh, newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)[buyEntry, sellEntry, stopBuyEntry, stopSellEntry] = f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange)[buyStop, sellStop] = f_calculateStopAndCompound(close, atr, stopMultiplyer, compoundMultiplyer, barState)crossedCompound = (strategy.position_size > 0 ? close > sellStop : strategy.position_size < 0 ? close < buyStop : true) or allowImmediateCompoundmaAlignment = f_getMaAlignment(MAType,includePartiallyAligned)alignedMaIndex = sum(maAlignment,LookbackPeriod)maHigh = alignedMaIndex > alignmentIndexThreshold or not considerMaAlignmentmaLow = alignedMaIndex < -alignmentIndexThreshold or not considerMaAlignment//buyEntry := buyEntry and ((newHigh and maHigh and percentRank > 50) or strategy.netprofit >= 0)//sellEntry := sellEntry and ((newLow and maLow and percentRank < 50) or strategy.netprofit >= 0)buyEntry := buyEntry and ((newHigh and maHigh and (dirMa == 1 or not considerMaSupertrend) and percentRank > 70) or strategy.netprofit >= 0)sellEntry := sellEntry and ((newLow and maLow and (dirMa == -1 or not considerMaSupertrend) and percentRank < 30) or strategy.netprofit >= 0)//////////////////////////////////////// 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.triangleup, location = location.absolute)plotshape(showTargets or showTargetStops?downTarget:na, title="DownTarget", color=color.red, style=shape.triangledown, location = location.absolute)plotshape(showTargetStops?stopUpTarget:na, title="UpStop", color=color.green, style=shape.triangleup, location = location.absolute)plotshape(showTargetStops?stopDownTarget:na, title="DownStop", color=color.red, style=shape.triangledown, location = location.absolute)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 showDownChannelplot(showTrailingStop and strategy.position_size != 0 and not channelview? buyStop : na, title="DownStop", color=(strategy.position_size > 0?color.green:strategy.position_size < 0 ?color.red:color.blue), linewidth=2, style=plot.style_stepline)plot(showTrailingStop and strategy.position_size != 0 and not channelview? sellStop : na, title="UpStop", color=(strategy.position_size > 0?color.green:strategy.position_size < 0 ?color.red:color.blue), linewidth=2, style=plot.style_stepline)//plot(percentValue, title="percentRank", color=color.blue, 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) [targetLine, targetLabel] = f_drawLinesWithLabels(close,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?buyStop:sellStop,"Stop",color.red) [compoundLine, compoundLabel] = f_drawLinesWithLabels(buyEntry?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 crossedCompound)strategy.close("Buy", when=stopBuyEntry and exitOnSignal)strategy.exit("ExitBuy", "Buy", stop = buyStop)strategy.entry("Sell", strategy.short, when=sellEntry and crossedCompound)strategy.close("Sell", when=stopSellEntry and exitOnSignal)strategy.exit("ExitSell", "Sell", stop = sellStop)