Pine Script Trailing Stop
Uses strategy.exit trail_points and trail_offset to lock in profit as price moves your way — both measured in ticks.
//@version=6
strategy("Trailing Stop", overlay=true, calc_on_every_tick=false)
// ── Inputs ──────────────────────────────────────────────
activationTicks = input.int(40, "Activation (ticks in profit)", minval=1,
tooltip="Trail activates once price moves this many ticks in your favor.")
trailTicks = input.int(20, "Trail Distance (ticks)", minval=1,
tooltip="Stop follows price at this distance once active.")
// ── Entry logic (replace with your own conditions) ───────
longCondition = ta.crossover(ta.ema(close, 9), ta.ema(close, 21))
shortCondition = ta.crossunder(ta.ema(close, 9), ta.ema(close, 21))
if longCondition
strategy.entry("Long", strategy.long)
if shortCondition
strategy.entry("Short", strategy.short)
// ── Trailing stop via strategy.exit ──────────────────────
// trail_points = ticks in profit before the trail activates
// trail_offset = ticks the stop trails behind price once active
strategy.exit("Long Trail", "Long", trail_points=activationTicks, trail_offset=trailTicks)
strategy.exit("Short Trail", "Short", trail_points=activationTicks, trail_offset=trailTicks)
Settings
activationTicks— profit in ticks required before the trail activates. Default 40.trailTicks— distance in ticks the stop follows behind the best price. Default 20.
How to use
- Paste into the Pine Editor, or copy the two
strategy.exitlines into your own strategy. - Keep the exit calls at global scope (evaluated every bar), not inside the entry
ifblock — the order must stay attached while the position is open. - Replace the EMA-crossover placeholder with your own entry conditions.
- For a hard floor before the trail activates, add a
loss=parameter to the same exit call.
Frequently Asked Questions
What is trail_offset in Pine Script?
trail_offset is the distance, in ticks, that the trailing stop follows price once the trail is active. trail_points is the profit, also in ticks, that price must reach before the trail activates. With trail_points=40 and trail_offset=20, nothing happens until the trade is 40 ticks in profit; from then on the stop trails 20 ticks behind the best price reached.
How do I add a trailing stop to a strategy?
Call strategy.exit with trail_points and trail_offset instead of a fixed stop parameter. The order sits in TradingView’s broker emulator and updates as price moves. Keep the exit call evaluated on every bar — not only inside the entry block — so it stays attached for the life of the position.
Related
Want a complete eval-ready strategy with exits already tuned?
This snippet is a building block. Our paid scripts are complete strategies — entries, trailing exits, kill switch, session filter, and EOD flatten pre-wired and tested on 3 years of MES/NQ data. Instant delivery from $50.
View Plans — From $50