Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Stepped trailing strategy example

A Pine Script v4 strategy with no technical-analysis calculation. It has 6 order rules, 1 entry among them, and trades long only with the default settings. Exits use a stop loss and a profit target. Each trade is one contract and pays no commission. 5 settings; defaults include stop loss %% 5, take profit 1 %% 5 and take profit 2 %% 10.

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 Stepped trailing strategy example repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 6 of 6 trades.
How did Stepped trailing strategy example do on BTCUSDT 1D with default settings?
−9.46%
From 26 Jan 2024 to 21 Oct 2026, over 21 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Stepped trailing strategy example 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 Stepped trailing strategy example use a stop loss?
Yes
strategy.exit sets a stop on line 97, 100, 105, 107.
Does Stepped trailing strategy example run in Zeal Terminal?
Yes
It compiles in 30 ms and runs 1,000 bars in 53 ms, in the browser.

BTCUSDT · 1D · default settings

  • Plot
  • Plot
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (5)
50,00075,000100,000125,000AprJulOct2025AprJulOct2026AprJulOct$90,541$202,527Equity from $100,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots.
Net profit
−9.46%
−$9,462.36
Buy and hold
+102.5%
same period
Closed trades
21
5 won · 10 lost
Profitable
23.8%
of closed trades
Profit factor
0.80
gross profit ÷ gross loss
Max drawdown
25.10%
−$27,135.50

One run with the author's default settings, $100,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

    No commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

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 crossover → ta.crossover, sma → ta.sma, max → math.max, min → math.min.

v4 → v5

Verified

Same 21 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 14: //@version=4 → //@version=5
  • Line 17: crossover → ta.crossover
  • Line 17: sma → ta.sma
  • Line 17: sma → ta.sma
  • Line 65: max → math.max
  • Line 67: max → math.max
  • Line 70: min → math.min
  • Line 72: min → math.min
⋯//--------------------------------------------------//@version=4+//@version=5strategy("Stepped trailing strategy example", overlay=true)// random entry condition-if (crossover(sma(close, 14), sma(close, 28)))+if (ta.crossover(ta.sma(close, 14), ta.sma(close, 28)))    strategy.entry("My Long Entry Id", strategy.long)⋯            if not na(level[1])-                level := max(level[1], level)+                level := math.max(level[1], level)            if not na(level)-                level := max(high, level)+                level := math.max(high, level)        else if strategy.position_size < 0            if not na(level[1])-                level := min(level[1], level)+                level := math.min(level[1], level)            if not na(level)-                level := min(low, level)+                level := math.min(low, level)calcTrailingOffsetLevel(points, offset) =>⋯

Clean v5

VerifiedDownload the v5 script

Same 21 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 25: input() → input.int()
  • Line 26: input() → input.int()
  • Line 27: input() → input.int()
  • Line 28: input() → input.int()
  • Line 29: input() → input.bool()
⋯// sl & tp in %%-sl = percent2points(input(5, title = "stop loss %%"))+sl = percent2points(input.int(5, title = "stop loss %%"))-tp1 = percent2points(input(5, title = "take profit 1 %%"))+tp1 = percent2points(input.int(5, title = "take profit 1 %%"))-tp2 = percent2points(input(10, title = "take profit 2 %%"))+tp2 = percent2points(input.int(10, title = "take profit 2 %%"))-tp3 = percent2points(input(15, title = "take profit 3 %%"))+tp3 = percent2points(input.int(15, title = "take profit 3 %%"))-activateTrailingOnThirdStep = input(false, title = "activate trailing on third stage (tp3 is amount, tp2 is offset level)")+activateTrailingOnThirdStep = input.bool(false, title = "activate trailing on third stage (tp3 is amount, tp2 is offset level)")curProfitInPts() =>⋯

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: 21 before, 12 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.

⋯//--------------------------------------------------//@version=5+//@version=6strategy("Stepped trailing strategy example", overlay=true)⋯

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
stop loss %%5intstopLevel exit x
take profit 1 %%5intstopLevel line 54
take profit 2 %%10inttrailOffsetLevelTmp line 56 exit x
take profit 3 %%15intprofitLevel trailOffsetLevelTmp exit x
activate trailing on third stage (tp3 is amount, tp2 is offset level)falseboolprofitLevel exit x exit x line 103

What it calculates

No technical-analysis calculation: the script works on prices and settings directly.

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.

lowlowprice datahighhighprice dataslstop loss %%setting · 5tp1take profit 1 %%setting · 5tp3take profit 3 %%setting · 15tp2take profit 2 %%setting · 10closecloseprice datalevellevelvalueresultresultvalueamountLevelamountLevelvaluetrailActiveDifftrailActiveDiffvaluestopLevelstopLevelvaluetrailOffsetLeveltrailOffsetLevelvalueprofitLevelprofitLevelvaluetrailOffsetLevelTmptrailOffsetLevelTmpvalueentry:My Long Entry IdOpen My Long Entry Idstrategy.entryexit:xexit xstrategy.exitcancel:xcancel xstrategy.cancelplot:112plotplotplot:113plotplotplot:114plotplot

Order rules

OrderFires whenBy defaultLine
Open My Long Entry Id long(crossover(sma(close, 14), sma(close, 28)))On18
Exit x stop and limitcurStage == 1On97
Exit x stop and limitcurStage == 2On100
Exit x stopactivateTrailingOnThirdStepOff “activate trailing on third stage (tp3 is amount, tp2 is offset level)”105
Exit x stop and limitactivateTrailingOnThirdStepOff “activate trailing on third stage (tp3 is amount, tp2 is offset level)”107
cancel xcurStage == 3On109

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, and the live replay matched history.

6/6trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • 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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D−9.5%+102.5%2124%0.8025.1%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+2.8%+5.5%825%1.2613.1%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−0.0%+9.8%1937%1.000.8%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−0.1%+8.4%1225%0.920.4%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+0.0%+16.7%1638%1.510.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−0.0%+21.5%1421%0.750.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+0.1%+148.3%1729%1.300.2%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+0.0%+17.1%933%1.140.1%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market633%$626.57
Sideways market1118%−$4,222.36
Falling market425%−$5,866.57

Rising and falling mean the market moved more than 15% over the 90 bars before entry.

How bad could the drawdown be?

32.8%

The 95th percentile of the worst drawdown when the same 21 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 15.9% to 32.8%; the tick is what actually happened, 25.1%. Order luck alone moves it this much.

0%38%
All 21 trades
SideEntryExitBarsP&L
long6 Apr 2024 67,820.6010 Apr 2024 67,820.604$0.00
long19 May 2024 66,915.2023 May 2024 66,915.204$0.00
long21 Jul 2024 67,140.0025 Jul 2024 63,783.004−$3,357.00
long27 Aug 2024 62,834.0028 Aug 2024 59,415.001−$3,419.00
long22 Sep 2024 63,349.001 Oct 2024 60,181.509−$3,167.45
long18 Oct 2024 67,421.804 Nov 2024 67,421.8017$0.00
long15 Jan 2025 96,560.9020 Jan 2025 101,332.005$4,770.72
long31 Mar 2025 82,390.003 Apr 2025 82,390.003$0.00
long22 Apr 2025 87,516.208 May 2025 100,644.0016$13,127.40
long20 Jun 2025 104,659.0022 Jun 2025 99,425.702−$5,232.93
long5 Jul 2025 107,984.001 Aug 2025 113,383.0027$5,399.21
long17 Aug 2025 117,381.0024 Aug 2025 111,512.007−$5,869.04
long15 Sep 2025 115,268.0025 Sep 2025 109,505.0010−$5,763.41
long6 Oct 2025 123,482.0010 Oct 2025 117,308.004−$6,174.12
long11 Dec 2025 92,015.4015 Dec 2025 87,414.604−$4,600.77
long7 Jan 2026 93,748.0020 Jan 2026 89,060.6013−$4,687.40
long10 Mar 2026 68,432.2018 Mar 2026 71,853.808$3,421.60
long14 Apr 2026 74,418.0019 Apr 2026 74,418.005$0.00
long14 Jul 2026 62,334.501 Aug 2026 62,334.5018$0.00
long20 Aug 2026 69,334.8024 Aug 2026 79,735.004$10,400.20
long23 Sep 2026 86,208.608 Oct 2026 81,898.1015−$4,310.43

Similar scripts

No other indicator or strategy here shares enough of its calculations.

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 30 msYes 1,000 bars in 53 msNot measured
PineTSNo v5 and v6 only—Not measured

“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/// © adolgov// @description//-------------------------------------------------// activateTrailingOnThirdStep == false (default)//  - when tp1 is reached, sl is moved to break-even//  - when tp2 is reached, sl is moved to tp1//  - when tp3 is reached - exit//-------------------------------------------------// activateTrailingOnThirdStep == true//  - when tp1 is reached, sl is moved to break-even//  - when tp2 is reached, sl is moved to tp1 and trailing stop is activated with tp2 amount level and tp1 offset level//-------------------------------------------------//@version=4strategy("Stepped trailing strategy example", overlay=true)// random entry conditionif (crossover(sma(close, 14), sma(close, 28)))    strategy.entry("My Long Entry Id", strategy.long)        // exit logic    percent2points(percent) =>    strategy.position_avg_price * percent / 100 / syminfo.mintick// sl & tp in %%sl = percent2points(input(5, title = "stop loss %%"))tp1 = percent2points(input(5, title = "take profit 1 %%"))tp2 = percent2points(input(10, title = "take profit 2 %%"))tp3 = percent2points(input(15, title = "take profit 3 %%"))activateTrailingOnThirdStep = input(false, title = "activate trailing on third stage (tp3 is amount, tp2 is offset level)")curProfitInPts() =>    if strategy.position_size > 0        (high - strategy.position_avg_price) / syminfo.mintick    else if strategy.position_size < 0        (strategy.position_avg_price - low) / syminfo.mintick    else        0        calcStopLossPrice(OffsetPts) =>    if strategy.position_size > 0        strategy.position_avg_price - OffsetPts * syminfo.mintick    else if strategy.position_size < 0        strategy.position_avg_price + OffsetPts * syminfo.mintick    else        na        calcProfitTrgtPrice(OffsetPts) =>    calcStopLossPrice(-OffsetPts)getCurrentStage() =>    var stage = 0    if strategy.position_size == 0         stage := 0    if stage == 0 and strategy.position_size != 0        stage := 1    else if stage == 1 and curProfitInPts() >= tp1        stage := 2    else if stage == 2 and curProfitInPts() >= tp2        stage := 3    stagecalcTrailingAmountLevel(points) =>    var float level = na    level := calcProfitTrgtPrice(points)    if not na(level)        if strategy.position_size > 0            if not na(level[1])                level := max(level[1], level)            if not na(level)                level := max(high, level)        else if strategy.position_size < 0            if not na(level[1])                level := min(level[1], level)            if not na(level)                level := min(low, level)calcTrailingOffsetLevel(points, offset) =>    float result = na    amountLevel = calcTrailingAmountLevel(points)    if strategy.position_size > 0        trailActiveDiff = amountLevel - calcProfitTrgtPrice(points)        if trailActiveDiff > 0            result := trailActiveDiff + calcProfitTrgtPrice(offset)    else if strategy.position_size < 0        trailActiveDiff = calcProfitTrgtPrice(points) - amountLevel        if trailActiveDiff > 0            result := calcProfitTrgtPrice(offset) - trailActiveDiff    resultfloat stopLevel = nafloat trailOffsetLevel = nafloat profitLevel = activateTrailingOnThirdStep ? calcTrailingAmountLevel(tp3) : calcProfitTrgtPrice(tp3)// note: calcTrailingOffsetLevel uses calcTrailingAmountLevel and last one has a state (level).//       therefor we needs calculate it on every bar for correct result.//       if we inline it the Pine compiler give us warning "The function '***' should be called on each calculation for consistency. It is recommended to extract the call from this scope."trailOffsetLevelTmp = calcTrailingOffsetLevel(tp3, tp2)// based on current stage set up exit// note: we use same exit ids ("x") consciously, for MODIFY the exit's parameterscurStage = getCurrentStage()if curStage == 1    stopLevel := calcStopLossPrice(sl)    strategy.exit("x", loss = sl, profit = tp3, comment = "sl or tp3")else if curStage == 2    stopLevel := calcStopLossPrice(0)    strategy.exit("x", stop = stopLevel, profit = tp3, comment = "breakeven or tp3")else if curStage == 3    stopLevel := calcStopLossPrice(-tp1)    if activateTrailingOnThirdStep        trailOffsetLevel := trailOffsetLevelTmp        strategy.exit("x", stop = stopLevel, trail_points = tp3, trail_offset = tp3-tp2, comment = "stop tp1 or trailing tp3 with offset tp2")    else        strategy.exit("x", stop = stopLevel, profit = tp3, comment = "tp1 or tp3")else    strategy.cancel("x")    // this is debug plots for visulalize TP & SL levelsplot(stopLevel, style = plot.style_linebr, color = color.red)plot(profitLevel, style = plot.style_linebr, color = color.blue)plot(trailOffsetLevel, style = plot.style_linebr, color = color.green)