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
- 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
VerifiedSame 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) =>⋯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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| stop loss %% | 5 | int | stopLevel exit x |
| take profit 1 %% | 5 | int | stopLevel line 54 |
| take profit 2 %% | 10 | int | trailOffsetLevelTmp line 56 exit x |
| take profit 3 %% | 15 | int | profitLevel trailOffsetLevelTmp exit x |
| activate trailing on third stage (tp3 is amount, tp2 is offset level) | false | bool | profitLevel 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open My Long Entry Id long | (crossover(sma(close, 14), sma(close, 28))) | On | 18 |
| Exit x stop and limit | curStage == 1 | On | 97 |
| Exit x stop and limit | curStage == 2 | On | 100 |
| Exit x stop | activateTrailingOnThirdStep | Off “activate trailing on third stage (tp3 is amount, tp2 is offset level)” | 105 |
| Exit x stop and limit | activateTrailingOnThirdStep | Off “activate trailing on third stage (tp3 is amount, tp2 is offset level)” | 107 |
| cancel x | curStage == 3 | On | 109 |
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.
- 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | −9.5% | +102.5% | 21 | 24% | 0.80 | 25.1% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +2.8% | +5.5% | 8 | 25% | 1.26 | 13.1% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −0.0% | +9.8% | 19 | 37% | 1.00 | 0.8% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −0.1% | +8.4% | 12 | 25% | 0.92 | 0.4% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +0.0% | +16.7% | 16 | 38% | 1.51 | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −0.0% | +21.5% | 14 | 21% | 0.75 | 0.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +0.1% | +148.3% | 17 | 29% | 1.30 | 0.2% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +0.0% | +17.1% | 9 | 33% | 1.14 | 0.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 6 | 33% | $626.57 |
| Sideways market | 11 | 18% | −$4,222.36 |
| Falling market | 4 | 25% | −$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.
All 21 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 6 Apr 2024 67,820.60 | 10 Apr 2024 67,820.60 | 4 | $0.00 |
| long | 19 May 2024 66,915.20 | 23 May 2024 66,915.20 | 4 | $0.00 |
| long | 21 Jul 2024 67,140.00 | 25 Jul 2024 63,783.00 | 4 | −$3,357.00 |
| long | 27 Aug 2024 62,834.00 | 28 Aug 2024 59,415.00 | 1 | −$3,419.00 |
| long | 22 Sep 2024 63,349.00 | 1 Oct 2024 60,181.50 | 9 | −$3,167.45 |
| long | 18 Oct 2024 67,421.80 | 4 Nov 2024 67,421.80 | 17 | $0.00 |
| long | 15 Jan 2025 96,560.90 | 20 Jan 2025 101,332.00 | 5 | $4,770.72 |
| long | 31 Mar 2025 82,390.00 | 3 Apr 2025 82,390.00 | 3 | $0.00 |
| long | 22 Apr 2025 87,516.20 | 8 May 2025 100,644.00 | 16 | $13,127.40 |
| long | 20 Jun 2025 104,659.00 | 22 Jun 2025 99,425.70 | 2 | −$5,232.93 |
| long | 5 Jul 2025 107,984.00 | 1 Aug 2025 113,383.00 | 27 | $5,399.21 |
| long | 17 Aug 2025 117,381.00 | 24 Aug 2025 111,512.00 | 7 | −$5,869.04 |
| long | 15 Sep 2025 115,268.00 | 25 Sep 2025 109,505.00 | 10 | −$5,763.41 |
| long | 6 Oct 2025 123,482.00 | 10 Oct 2025 117,308.00 | 4 | −$6,174.12 |
| long | 11 Dec 2025 92,015.40 | 15 Dec 2025 87,414.60 | 4 | −$4,600.77 |
| long | 7 Jan 2026 93,748.00 | 20 Jan 2026 89,060.60 | 13 | −$4,687.40 |
| long | 10 Mar 2026 68,432.20 | 18 Mar 2026 71,853.80 | 8 | $3,421.60 |
| long | 14 Apr 2026 74,418.00 | 19 Apr 2026 74,418.00 | 5 | $0.00 |
| long | 14 Jul 2026 62,334.50 | 1 Aug 2026 62,334.50 | 18 | $0.00 |
| long | 20 Aug 2026 69,334.80 | 24 Aug 2026 79,735.00 | 4 | $10,400.20 |
| long | 23 Sep 2026 86,208.60 | 8 Oct 2026 81,898.10 | 15 | −$4,310.43 |
Similar scripts
No other indicator or strategy here shares enough of its calculations.
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 30 ms | Yes 1,000 bars in 53 ms | Not measured |
| PineTS | No 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)