Pine Script Trailing Stop
Uses strategy.exit's trail_points and trail_offset to lock in profit as price moves in your favor, both measured in ticks.
Pine Script
//@version=6
strategy("Target Filled - Trailing Stop Example", overlay=true, calc_on_every_tick=false)
// --- Inputs ---------------------------------------------------
armTicks = input.int(40, "Arm Distance (ticks in profit)", minval=1,
tooltip="Trail arms 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 armed.")
// --- Sample signal — replace with your own entry logic ---------
fastMA = ta.ema(close, 9)
slowMA = ta.ema(close, 21)
if ta.crossover(fastMA, slowMA)
strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
strategy.entry("Short", strategy.short)
// --- Trailing exit ---------------------------------------------------
// trail_points = ticks in profit required before the trail arms
// trail_offset = ticks the stop follows behind price once armed
strategy.exit("Long Trail", "Long", trail_points=armTicks, trail_offset=trailTicks)
strategy.exit("Short Trail", "Short", trail_points=armTicks, trail_offset=trailTicks) Settings
| Input | Default | Purpose |
|---|---|---|
| armTicks | 40 | Profit in ticks required before the trail arms. |
| trailTicks | 20 | Distance in ticks the stop follows behind the best price once armed. |
How to use
- Paste into the Pine Editor, or lift just the two
strategy.exitlines into a strategy you already have. - Keep the exit calls at global scope — evaluated every bar, not inside the entry's
ifblock — so the order stays attached while a position is open. - Swap the EMA-crossover placeholder for your own entry conditions.
- For a hard floor before the trail arms, add a
loss=parameter to the samestrategy.exitcall.
Frequently Asked Questions
What is trail_offset in Pine Script?
trail_offset is the distance, in ticks, that a trailing stop follows behind price once the trail has armed. trail_points is the profit, also in ticks, price must reach before that happens. With trail_points=40 and trail_offset=20, nothing happens until the trade is 40 ticks in profit — from there, 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. The order sits in TradingView's broker emulator and updates on its own as price moves. Keep the call at global scope, evaluated every bar — not nested inside the entry's if block — so it stays attached for the full life of the position.