Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Combining Trailing Stop and Stop loss (- of instrument price)

A Pine Script v5 strategy built on EMA (close, 20), Crossover (fastEMA, slowEMA) and Crossunder (fastEMA, slowEMA). It has 6 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade is one contract and pays no commission. 11 settings; defaults include Fast EMA period 20, Slow EMA period 50 and Long Trailing Stop (%) 7.

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 Combining Trailing Stop and Stop loss (- of instrument price) repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 10 of 10 trades.
How did Combining Trailing Stop and Stop loss (- of instrument price) do on BTCUSDT 1D with default settings?
+0.64%
From 26 Jan 2024 to 21 Oct 2026, over 39 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does Combining Trailing Stop and Stop loss (- of instrument price) 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: 39 before, 34 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download.
Does Combining Trailing Stop and Stop loss (- of instrument price) use a stop loss?
Yes
strategy.exit sets a stop on line 141, 145.
Does Combining Trailing Stop and Stop loss (- of instrument price) run in Zeal Terminal?
Yes
It compiles in 50 ms and runs 1,000 bars in 69 ms, in the browser.

BTCUSDT · 1D · default settings

  • Fast SMA
  • Slow SMA
  • Entry Price
  • Long Trail Stop
  • Short Trail Stop
  • Long Stop Loss
  • Short Stop Loss
  • Long TP
  • Short TP
  • Long TP Stop Loss
  • Short TP Stop Loss
  • 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 (11)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,006,420$2,025,273Equity from $1,000,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. 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.
Net profit
+0.64%
$6,421.07
Buy and hold
+102.5%
same period
Closed trades
39
27 won · 12 lost
Profitable
69.2%
of closed trades
Profit factor
1.32
gross profit ÷ gross loss
Max drawdown
1.35%
−$13,545.50

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

Settings

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

SettingDefaultType and rangeFeeds
Fast EMA period20int · min 0fastEMA
Slow EMA period50int · min 0slowEMA
Long Trailing Stop (%)7float · min 0.0 · step 0.1longTrailPrice stopValue
Short Trailing Stop (%)7float · min 0.0 · step 0.1shortTrailPrice stopValue
Long Stop Loss (%)2float · min 0.0 · step 0.1longLossPrice
Short Stop Loss (%)2float · min 0.0 · step 0.1shortLossPrice
Long Take Profit (%)2float · min 0.0 · step 0.1longTP
Short Take Profit (%)2float · min 0.0 · step 0.1shortTP
Unwind Postion Size % @ TPExample: 50 closing 50% of the position once TP is reached50float · step 1exit Buy TP exit Sell TP
Long Stop Loss after TP1float · min 0.0 · step 0.1longStopTP
Short Stop Loss after TP1float · min 0.0 · step 0.1shortStopTP

What it calculates

  • EMAclose, Fast EMA period (20)fastEMA · line 15
  • EMAclose, Slow EMA period (50)slowEMA · line 16
  • CrossoverfastEMA, slowEMAbuy · line 22
  • CrossunderfastEMA, slowEMAsell · line 23

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.

closecloseprice datai_FastEMAFast EMA periodsetting · 20i_SlowEMASlow EMA periodsetting · 50lowlowprice datashortTrailPercShort Trailing Stop (%)setting · 7longStopTpPercLong Stop Loss after TPsetting · 1shortStopTpPercShort Stop Loss after TPsetting · 1longTpPercLong Take Profit (%)setting · 2shortTpPercShort Take Profit (%)setting · 2longStopPercLong Stop Loss (%)setting · 2shortStopPercShort Stop Loss (%)setting · 2highhighprice datalongTrailPercLong Trailing Stop (%)setting · 7fastEMAEMA→ fastEMAslowEMAEMA→ slowEMAbuyCrossover→ buysellCrossunder→ sellstopValuestopValuevalueentryPrice, current_position_sizeentryPrice · current_po…2 valueslongStopTPlongStopTPvalueshortStopTPshortStopTPvaluelongTPlongTPvalueshortTPshortTPvaluelongLossPricelongLossPricevalueshortLossPriceshortLossPricevaluelongStopPricelongStopPricevalueshortStopPriceshortStopPricevaluelongTrailPricelongTrailPriceconditionshortTrailPriceshortTrailPriceconditioninitial_position_sizeinitial_position_sizeconditionentry:BuyOpen Buystrategy.entryentry:SellOpen Sellstrategy.entryexit:Buy TPexit Buy TPstrategy.exitexit:Buy Stopexit Buy Stopstrategy.exitexit:Sell TPexit Sell TPstrategy.exitexit:Sell Stopexit Sell Stopstrategy.exitplot:18Fast SMAplotplot:19Slow SMAplotplot:78Entry Priceplotplot:79Long Trail Stopplotplot:82Short Trail Stopplotplot:85Long Stop Lossplotplot:88Short Stop Lossplotplot:92Long TPplotplot:95Short TPplotplot:99Long TP Stop Lossplotplot:102Short TP Stop Lossplot

Order rules

OrderFires whenBy defaultLine
Open Buy long(buy)On108
Open Sell short(sell)On110
Exit Buy TP limit(strategy.position_size > 0)On140
Exit Buy Stop stop(strategy.position_size > 0)On141
Exit Sell TP limit(strategy.position_size < 0)On143
Exit Sell Stop stop(strategy.position_size < 0)On145

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.

10/10trades 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+0.6%+102.5%3969%1.321.3%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+0.9%+5.5%2264%2.670.5%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+0.0%+9.8%3259%1.010.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−0.0%+8.4%3142%0.670.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−0.0%+16.7%4755%0.710.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+0.0%+21.5%2378%5.490.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+0.0%+148.3%2463%1.270.0%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−0.0%+17.1%4848%0.710.0%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 market771%$1,205.52
Sideways market2673%$8,404.95
Falling market650%−$3,189.40

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 39 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 0.5% to 1.2%; the tick is what actually happened, 1.2%. Order luck alone moves it this much.

0%1%
All 39 trades
SideEntryExitBarsP&L
short4 May 2024 62,882.005 May 2024 63,892.001−$1,010.02
long5 May 2024 63,892.006 May 2024 65,169.901$638.92
long5 May 2024 63,892.007 May 2024 63,165.202−$363.43
short8 May 2024 62,312.109 May 2024 61,065.801$623.12
short8 May 2024 62,312.109 May 2024 61,688.901$311.56
long18 May 2024 67,024.0020 May 2024 68,364.502$670.24
long18 May 2024 67,024.0023 May 2024 67,694.205$335.12
short24 Jun 2024 63,210.0025 Jun 2024 60,293.301$1,458.35
short24 Jun 2024 63,210.0030 Jun 2024 62,490.106$359.94
long23 Jul 2024 67,532.0024 Jul 2024 65,936.001−$798.00
long23 Jul 2024 67,532.0027 Jul 2024 68,882.604$675.32
short6 Aug 2024 54,018.807 Aug 2024 56,022.001−$1,001.59
short6 Aug 2024 54,018.806 Sep 2024 52,938.4031$540.19
long23 Sep 2024 63,578.8026 Sep 2024 64,850.303$635.79
long23 Sep 2024 63,578.8030 Sep 2024 64,214.507$317.89
short18 Feb 2025 95,780.0019 Feb 2025 95,671.701$54.13
short18 Feb 2025 95,780.0024 Feb 2025 93,864.406$957.80
long25 Apr 2025 93,980.501 May 2025 95,860.106$939.80
long25 Apr 2025 93,980.504 May 2025 94,920.309$469.90
short30 Aug 2025 108,377.002 Sep 2025 110,545.003−$1,083.78
short30 Aug 2025 108,377.0016 Sep 2025 115,350.0017−$3,486.16
long16 Sep 2025 115,350.0018 Sep 2025 117,657.002$1,153.49
long16 Sep 2025 115,350.0019 Sep 2025 116,503.003$576.75
short26 Sep 2025 108,994.0028 Sep 2025 111,174.002−$1,089.94
short26 Sep 2025 108,994.002 Oct 2025 118,595.006−$4,800.25
long2 Oct 2025 118,595.003 Oct 2025 119,781.001$592.97
long2 Oct 2025 118,595.003 Oct 2025 120,967.001$1,185.95
short18 Oct 2025 106,432.0019 Oct 2025 108,560.001−$1,064.32
short18 Oct 2025 106,432.004 Nov 2025 104,303.0017$1,064.31
long18 Jan 2026 95,147.8019 Jan 2026 93,244.801−$951.48
long18 Jan 2026 95,147.8021 Jan 2026 88,427.703−$3,360.06
short21 Jan 2026 88,427.7022 Jan 2026 90,196.201−$884.28
short21 Jan 2026 88,427.7025 Jan 2026 86,659.104$884.27
long16 Apr 2026 74,810.0017 Apr 2026 76,306.201$748.10
long16 Apr 2026 74,810.0018 Apr 2026 75,558.102$374.05
short1 Jun 2026 73,674.402 Jun 2026 71,408.901$1,132.75
short1 Jun 2026 73,674.407 Jun 2026 63,270.106$5,202.15
long21 Aug 2026 73,027.0022 Aug 2026 78,338.001$2,655.50
long21 Aug 2026 73,027.0010 Sep 2026 76,539.0020$1,755.99

Similar scripts

Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.

ScriptSharesTypeNetTradesMax drawdown
Combining Trailing Stop and Stop loss (- of instrument price) this page—v5 strategy+0.6%391.3%
EMA Slope AyE by fajardoarelysemav4 strategyNo trades on this market
ROoT by realisticDove62527emav5 strategy−4.7%2259.4%
sachin5986 by mohitesachin78emav4 strategy+32.1%3517.6%
sonu1997 by Sonu1997emav4 strategy+960.7%21,103.8%
Moving Average Crossover by Muh4mm4demav4 strategy+19,990.1%301,274.2%

Upgrade and export

Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.

  • No v6-only features. v6 is not needed to run this script.

Clean v5

Verified

Nothing to change.

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: 39 before, 34 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.

⋯//thereby assuming full responsibility in the risks taken while trading.-//@version=5+//@version=6strategy(title=" Combining Trailing Stop, Take Profit and Stop loss (% of instrument price)",⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 50 msWith a workaround 1,000 bars in 69 msNot measured
PineTSNot testedNot testedNot 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.

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/// © wouterpruym1828//DISCLAIMER: This is not a trading strategy. Rather, it is a template from which you can take chunks of code and implement them in your own script.//I do not take any responsibility in case of resulting losses while using parts of this script or the script as a whole. It is up to the user to decide how to use this script, //thereby assuming full responsibility in the risks taken while trading.//@version=5strategy(title=" Combining Trailing Stop, Take Profit and Stop loss (% of instrument price)",     overlay=true, pyramiding=1, shorttitle="TSL&TP&SL%")//INDICATOR SECTION// Indicator Input options+i_FastEMA = input.int(title = "Fast EMA period", minval = 0, defval = 20)i_SlowEMA = input.int(title = "Slow EMA period", minval = 0, defval = 50)     // Calculate moving averagesfastEMA = ta.ema(close, i_FastEMA)slowEMA = ta.ema(close, i_SlowEMA)// Plot moving averagesplot(fastEMA, title="Fast SMA", color=color.blue)plot(slowEMA, title="Slow SMA", color=color.orange)//STRATEGY SECTION  // Calculate trading conditionsbuy  = ta.crossover(fastEMA, slowEMA)sell = ta.crossunder(fastEMA, slowEMA)// STEP 1:// Configure trail stop loss level with input options (optional)longTrailPerc = input.float(title="Long Trailing Stop (%)", minval=0.0, step=0.1, defval=7) * 0.01shortTrailPerc = input.float(title="Short Trailing Stop (%)", minval=0.0, step=0.1, defval=7) * 0.01//Configure stop loss level with input options (optional)longStopPerc = input.float(title="Long Stop Loss (%)", minval=0.0, step=0.1, defval=2)*0.01shortStopPerc = input.float(title="Short Stop Loss (%)", minval=0.0, step=0.1, defval=2)*0.01//Configure take profit price level and take profit ratio with input options (optional)longTpPerc = input.float(title="Long Take Profit (%)", minval=0.0, step=0.1, defval=2) shortTpPerc = input.float(title="Short Take Profit (%)", minval=0.0, step=0.1, defval=2) TP_Ratio = input.float(title="Unwind Postion Size % @ TP", defval=50, step=1, tooltip="Example: 50 closing 50% of the position once TP is reached")/100//Configure stop loss after take profit with input options (optional)longStopTpPerc = input.float(title="Long Stop Loss after TP", minval=0.0, step=0.1, defval=1)shortStopTpPerc = input.float(title="Short Stop Loss after TP", minval=0.0, step=0.1, defval=1)// STEP 2:// Determine trail stop loss priceslongTrailPrice = 0.0, shortTrailPrice = 0.0longTrailPrice := if (strategy.position_size > 0)    stopValue = high * (1 - longTrailPerc)    math.max(stopValue, longTrailPrice[1])else    0shortTrailPrice := if (strategy.position_size < 0)    stopValue = low * (1 + shortTrailPerc)    math.min(stopValue, shortTrailPrice[1])else    999999//Determine entry priceentryPrice = 0.0entryPrice := strategy.opentrades.entry_price(strategy.opentrades - 1)//Determine stop loss after reaching TPlongStopTP = 0.0, shortStopTP = 0.0longStopTP := entryPrice + (entryPrice * (longStopTpPerc / 100))shortStopTP := entryPrice - (entryPrice * (shortStopTpPerc / 100))// Determine take profit pricespercentAsPoints(pcnt) =>    strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)percentAsPrice(pcnt) =>    strategy.position_size != 0 ? ((pcnt / 100.0) + 1.0) * strategy.position_avg_price : float(na) current_position_size = math.abs(strategy.position_size)initial_position_size = math.abs(ta.valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))   longTP  = strategy.position_avg_price + percentAsPoints(longTpPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)bool stageLongTP = falseif high > longTP    stageLongTP := trueshortTP  = strategy.position_avg_price + percentAsPoints(shortTpPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)bool stageShortTP = falseif low < shortTP    stageShortTP := true// Determine stop loss priceslongLossPrice =  entryPrice * (1 - longStopPerc)shortLossPrice =  entryPrice * (1 + shortStopPerc)// Plot trail stop, stop loss and take profit values for confirmationplot(entryPrice, color=color.black, style=plot.style_cross, linewidth=2, title="Entry Price")plot(series=(strategy.position_size > 0) ? longTrailPrice : na,     color=color.fuchsia, style=plot.style_cross,     linewidth=2, title="Long Trail Stop")plot(series=(strategy.position_size < 0) ? shortTrailPrice : na,     color=color.fuchsia, style=plot.style_cross,     linewidth=2, title="Short Trail Stop")plot(series=(strategy.position_size > 0) ? longLossPrice : na,     color=color.olive, style=plot.style_cross,     linewidth=2, title="Long Stop Loss")plot(series=(strategy.position_size < 0) ? shortLossPrice : na,     color=color.olive, style=plot.style_cross,     linewidth=2, title="Short Stop Loss")     plot(series=(strategy.position_size > 0) ? longTP : na,     color=color.green, style=plot.style_cross,     linewidth=2, title="Long TP")plot(series=(strategy.position_size < 0) ? shortTP : na,     color=color.green, style=plot.style_cross,     linewidth=2, title="Short TP")     plot(series=(strategy.position_size > 0) ? longStopTP : na,     color=color.aqua, style=plot.style_cross,     linewidth=2, title="Long TP Stop Loss")plot(series=(strategy.position_size < 0) ? shortStopTP : na,     color=color.aqua, style=plot.style_cross,     linewidth=2, title="Short TP Stop Loss")     // Submit entry ordersif (buy)    strategy.entry("Buy", strategy.long)if (sell)    strategy.entry("Sell", strategy.short)    //Evaluating trailing stop, stop after take profit or stop loss to use, var longStopPrice = 0.0if strategy.position_avg_price < longTP     if longTrailPrice < longLossPrice        longStopPrice := longLossPrice    else if longTrailPrice > longLossPrice        longStopPrice := longTrailPrice        if stageLongTP == true    if longTrailPrice < longStopTP        longStopPrice := longStopTP    else if longTrailPrice > longStopTP        longStopPrice := longTrailPricevar shortStopPrice = 0.0if strategy.position_avg_price > shortTP    if shortTrailPrice > shortLossPrice        shortStopPrice := shortLossPrice    else if shortTrailPrice < shortLossPrice        shortStopPrice := shortTrailPrice        if stageShortTP == true    if shortTrailPrice > shortStopTP        shortStopPrice := shortStopTP    else if shortTrailPrice < shortStopTP        shortStopPrice := shortTrailPrice// STEP 3:// Submit exit orders for take profit (stop loss moves to entry price) and stop priceif (strategy.position_size > 0)    strategy.exit(id="Buy TP", qty = initial_position_size * TP_Ratio, limit = longTP)    strategy.exit(id="Buy Stop", stop=longStopPrice)if (strategy.position_size < 0)    strategy.exit(id="Sell TP", qty = initial_position_size * TP_Ratio, limit = shortTP)    // shortLossPrice := shortStopTP    strategy.exit(id="Sell Stop", stop=shortStopPrice)