Pine Script Strategy & Execution

Pine Script Trailing Stop with strategy.exit trail_offset, stop, and limit

In Pine Script, a trailing stop is implemented using strategy.exit() by pairing trail_points (the distance from the entry price required to activate the trailing mechanism) with trail_offset (the distance price can pull back from its peak before triggering an exit). Both stop (fixed stop loss price level) and limit (take profit target price) can be combined in the same strategy.exit call alongside trailing parameters to provide complete risk management.

Build Trailing Stops with AI Agent

Understanding strategy.exit parameters: trail_offset, trail_points, stop, and limit

When writing a strategy in Pine Script, managing risk requires balancing fixed initial defense against capturing trend extension. The built-in strategy.exit() function can evaluate four parameters simultaneously: a fixed stop-loss price, a profit target limit price, an activation threshold (trail_points), and a trailing pullback tolerance (trail_offset). When the position opens, the fixed stop protects against immediate adverse movement. If price surges past trail_points, the trailing stop activates and begins ratcheting forward with every new peak. If price hits the limit target first, it exits at full profit. If price retreats by trail_offset, it exits via trailing stop.

ParameterValue TypeUnit of measurementRole in strategy.exit
stopseries floatAbsolute price level (e.g. 152.50)Fixed catastrophic stop loss protecting initial capital
limitseries floatAbsolute price level (e.g. 165.00)Fixed take profit price target
trail_pointsseries floatTicks / points (price / syminfo.mintick)Favorable distance required before trailing stop arms
trail_offsetseries floatTicks / points (price / syminfo.mintick)Trailing distance maintained behind the extreme price

Complete Pine Script v6 trailing stop strategy code example

This Pine Script v6 strategy demonstrates how to combine an initial ATR-based stop loss, a fixed profit target, and an active trailing stop with trail_offset inside a single strategy.exit() order.

Pine Script v6: Strategy with trail_offset, stop, and limitpinescript
//@version=6
strategy("Trailing Stop Master [v6]", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 10)

// Inputs
fastLength = input.int(10, "Fast EMA")
slowLength = input.int(30, "Slow EMA")
atrLength = input.int(14, "ATR Length")
atrMult = input.float(2.0, "ATR Stop Multiplier")
tpPercent = input.float(4.0, "Take Profit %")
trailArmAtr = input.float(1.5, "Trail Activation (ATR Mult)")
trailOffsetAtr = input.float(1.0, "Trail Offset (ATR Mult)")

// Technical indicators
fastEma = ta.ema(close, fastLength)
slowEma = ta.ema(close, slowLength)
atrVal = ta.atr(atrLength)

plot(fastEma, "Fast EMA", color = color.blue)
plot(slowEma, "Slow EMA", color = color.orange)

// Entry condition
longCondition = ta.crossover(fastEma, slowEma)

if longCondition
    strategy.entry("Long", strategy.long)

if strategy.position_size > 0
    // Calculate price levels
    entryPrice = strategy.position_avg_price
    initialStopPrice = entryPrice - (atrVal * atrMult)
    targetPrice = entryPrice * (1 + tpPercent / 100)
    
    // Convert ATR distances to ticks for trail parameters
    armTicks = (atrVal * trailArmAtr) / syminfo.mintick
    offsetTicks = (atrVal * trailOffsetAtr) / syminfo.mintick
    
    // Combined exit: initial stop + profit target + trailing stop
    strategy.exit("Exit Long", from_entry = "Long", stop = initialStopPrice, limit = targetPrice, trail_points = armTicks, trail_offset = offsetTicks)

ATR dynamic trailing stop multiplier mechanics

Static trailing stops (e.g. trailing by a fixed $2.00) perform poorly across assets with varying volatility. An ATR-based trailing stop adapts dynamically to market expansion and consolidation. When volatility spikes, the ATR widens, allowing the trade breathing room during turbulent trends. When volatility contracts, the ATR narrows, tightening the trailing stop to lock in profits before momentum wanes.

  • Calculate in ticks: Pine Script trail_points and trail_offset expect units of price movement (ticks). Always divide your price distance by syminfo.mintick.
  • Immediate trailing: To begin trailing immediately upon entry without waiting for an activation buffer, set trail_points = 0.
  • Short positions: For short exits, strategy.exit automatically trails above the lowest price reached once price moves downward past trail_points.
  • Intrabar precision: In backtesting, enable "Recalculate on order fills" or Bar Magnifier to inspect realistic intrabar fills for trailing stops.

Common errors when coding Pine Script trailing stops

Traders frequently encounter unexpected exits or compiler warnings when configuring strategy.exit trailing parameters. Watch out for these three core failure modes:

  • Passing raw prices into trail_points: Passing entryPrice + 10 instead of ticks will set the activation threshold thousands of ticks away, meaning the trailing stop never activates.
  • Mismatched IDs: The from_entry parameter in strategy.exit must exactly match the ID string passed to strategy.entry.
  • Overwriting orders on every tick: If recalculating trailing parameters per bar, avoid triggering conflicting exit orders with duplicate IDs.
  • Assuming limit takes priority over stop: During rapid price spikes, whichever condition TradingViews broker emulator evaluates first will fill the order.
Where Pineify fits

Pine Script AI Coding Agent

Generate robust Pine Script v6 strategies with multi-bracket exits, dynamic ATR trailing stops, and verified tick conversions from plain English descriptions.

Also useful: Strategy Optimizer. Optimize your trailing stop multipliers, trail offset ticks, and take profit targets to maximize Sharpe ratio and minimize drawdown.

Build Trailing Stops with AI Agent

Frequently asked questions

Educational and programming guide for Pine Script strategy development. Trailing stop performance varies by market regime, spread, and slippage. Backtest results do not guarantee live trading returns.

Sources and verification