HomePine Script Snippets › Trailing Stop

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

How to use

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