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
- 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Fast EMA period | 20 | int · min 0 | fastEMA |
| Slow EMA period | 50 | int · min 0 | slowEMA |
| Long Trailing Stop (%) | 7 | float · min 0.0 · step 0.1 | longTrailPrice stopValue |
| Short Trailing Stop (%) | 7 | float · min 0.0 · step 0.1 | shortTrailPrice stopValue |
| Long Stop Loss (%) | 2 | float · min 0.0 · step 0.1 | longLossPrice |
| Short Stop Loss (%) | 2 | float · min 0.0 · step 0.1 | shortLossPrice |
| Long Take Profit (%) | 2 | float · min 0.0 · step 0.1 | longTP |
| Short Take Profit (%) | 2 | float · min 0.0 · step 0.1 | shortTP |
| Unwind Postion Size % @ TPExample: 50 closing 50% of the position once TP is reached | 50 | float · step 1 | exit Buy TP exit Sell TP |
| Long Stop Loss after TP | 1 | float · min 0.0 · step 0.1 | longStopTP |
| Short Stop Loss after TP | 1 | float · min 0.0 · step 0.1 | shortStopTP |
What it calculates
- EMAclose, Fast EMA period (20)
fastEMA · line 15 - EMAclose, Slow EMA period (50)
slowEMA · line 16 - CrossoverfastEMA, slowEMA
buy · line 22 - CrossunderfastEMA, slowEMA
sell · 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Buy long | (buy) | On | 108 |
| Open Sell short | (sell) | On | 110 |
| Exit Buy TP limit | (strategy.position_size > 0) | On | 140 |
| Exit Buy Stop stop | (strategy.position_size > 0) | On | 141 |
| Exit Sell TP limit | (strategy.position_size < 0) | On | 143 |
| Exit Sell Stop stop | (strategy.position_size < 0) | On | 145 |
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 | +0.6% | +102.5% | 39 | 69% | 1.32 | 1.3% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +0.9% | +5.5% | 22 | 64% | 2.67 | 0.5% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +0.0% | +9.8% | 32 | 59% | 1.01 | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −0.0% | +8.4% | 31 | 42% | 0.67 | 0.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −0.0% | +16.7% | 47 | 55% | 0.71 | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +0.0% | +21.5% | 23 | 78% | 5.49 | 0.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +0.0% | +148.3% | 24 | 63% | 1.27 | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −0.0% | +17.1% | 48 | 48% | 0.71 | 0.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 7 | 71% | $1,205.52 |
| Sideways market | 26 | 73% | $8,404.95 |
| Falling market | 6 | 50% | −$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.
All 39 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| short | 4 May 2024 62,882.00 | 5 May 2024 63,892.00 | 1 | −$1,010.02 |
| long | 5 May 2024 63,892.00 | 6 May 2024 65,169.90 | 1 | $638.92 |
| long | 5 May 2024 63,892.00 | 7 May 2024 63,165.20 | 2 | −$363.43 |
| short | 8 May 2024 62,312.10 | 9 May 2024 61,065.80 | 1 | $623.12 |
| short | 8 May 2024 62,312.10 | 9 May 2024 61,688.90 | 1 | $311.56 |
| long | 18 May 2024 67,024.00 | 20 May 2024 68,364.50 | 2 | $670.24 |
| long | 18 May 2024 67,024.00 | 23 May 2024 67,694.20 | 5 | $335.12 |
| short | 24 Jun 2024 63,210.00 | 25 Jun 2024 60,293.30 | 1 | $1,458.35 |
| short | 24 Jun 2024 63,210.00 | 30 Jun 2024 62,490.10 | 6 | $359.94 |
| long | 23 Jul 2024 67,532.00 | 24 Jul 2024 65,936.00 | 1 | −$798.00 |
| long | 23 Jul 2024 67,532.00 | 27 Jul 2024 68,882.60 | 4 | $675.32 |
| short | 6 Aug 2024 54,018.80 | 7 Aug 2024 56,022.00 | 1 | −$1,001.59 |
| short | 6 Aug 2024 54,018.80 | 6 Sep 2024 52,938.40 | 31 | $540.19 |
| long | 23 Sep 2024 63,578.80 | 26 Sep 2024 64,850.30 | 3 | $635.79 |
| long | 23 Sep 2024 63,578.80 | 30 Sep 2024 64,214.50 | 7 | $317.89 |
| short | 18 Feb 2025 95,780.00 | 19 Feb 2025 95,671.70 | 1 | $54.13 |
| short | 18 Feb 2025 95,780.00 | 24 Feb 2025 93,864.40 | 6 | $957.80 |
| long | 25 Apr 2025 93,980.50 | 1 May 2025 95,860.10 | 6 | $939.80 |
| long | 25 Apr 2025 93,980.50 | 4 May 2025 94,920.30 | 9 | $469.90 |
| short | 30 Aug 2025 108,377.00 | 2 Sep 2025 110,545.00 | 3 | −$1,083.78 |
| short | 30 Aug 2025 108,377.00 | 16 Sep 2025 115,350.00 | 17 | −$3,486.16 |
| long | 16 Sep 2025 115,350.00 | 18 Sep 2025 117,657.00 | 2 | $1,153.49 |
| long | 16 Sep 2025 115,350.00 | 19 Sep 2025 116,503.00 | 3 | $576.75 |
| short | 26 Sep 2025 108,994.00 | 28 Sep 2025 111,174.00 | 2 | −$1,089.94 |
| short | 26 Sep 2025 108,994.00 | 2 Oct 2025 118,595.00 | 6 | −$4,800.25 |
| long | 2 Oct 2025 118,595.00 | 3 Oct 2025 119,781.00 | 1 | $592.97 |
| long | 2 Oct 2025 118,595.00 | 3 Oct 2025 120,967.00 | 1 | $1,185.95 |
| short | 18 Oct 2025 106,432.00 | 19 Oct 2025 108,560.00 | 1 | −$1,064.32 |
| short | 18 Oct 2025 106,432.00 | 4 Nov 2025 104,303.00 | 17 | $1,064.31 |
| long | 18 Jan 2026 95,147.80 | 19 Jan 2026 93,244.80 | 1 | −$951.48 |
| long | 18 Jan 2026 95,147.80 | 21 Jan 2026 88,427.70 | 3 | −$3,360.06 |
| short | 21 Jan 2026 88,427.70 | 22 Jan 2026 90,196.20 | 1 | −$884.28 |
| short | 21 Jan 2026 88,427.70 | 25 Jan 2026 86,659.10 | 4 | $884.27 |
| long | 16 Apr 2026 74,810.00 | 17 Apr 2026 76,306.20 | 1 | $748.10 |
| long | 16 Apr 2026 74,810.00 | 18 Apr 2026 75,558.10 | 2 | $374.05 |
| short | 1 Jun 2026 73,674.40 | 2 Jun 2026 71,408.90 | 1 | $1,132.75 |
| short | 1 Jun 2026 73,674.40 | 7 Jun 2026 63,270.10 | 6 | $5,202.15 |
| long | 21 Aug 2026 73,027.00 | 22 Aug 2026 78,338.00 | 1 | $2,655.50 |
| long | 21 Aug 2026 73,027.00 | 10 Sep 2026 76,539.00 | 20 | $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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Combining Trailing Stop and Stop loss (- of instrument price) this page | — | v5 strategy | +0.6% | 39 | 1.3% |
| EMA Slope AyE by fajardoarelys | ema | v4 strategy | No trades on this market | ||
| ROoT by realisticDove62527 | ema | v5 strategy | −4.7% | 225 | 9.4% |
| sachin5986 by mohitesachin78 | ema | v4 strategy | +32.1% | 35 | 17.6% |
| sonu1997 by Sonu1997 | ema | v4 strategy | +960.7% | 2 | 1,103.8% |
| Moving Average Crossover by Muh4mm4d | ema | v4 strategy | +19,990.1% | 30 | 1,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
VerifiedNothing 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
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 50 ms | With a workaround 1,000 bars in 69 ms | Not measured |
| PineTS | Not tested | Not tested | 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.
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)