ATR Trailing Stop in Pine Script

This lesson demonstrates a simple template for creating an ATR-based volatility-adaptive trailing stop in Pine Script.

Check out my other free lessons!

Source Code

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading | www.TheArtOfTrading.com
// @version=5
strategy("TheArtOfTrading.com|", overlay=true, margin_long=100, margin_short=100)

// Get user input 
int     BAR_LOOKBACK    = input.int(10, "Bar Lookback")
int     ATR_LENGTH      = input.int(14, "ATR Length")
float   ATR_MULTIPLIER  = input.float(1.0, "ATR Multiplier")

// Get indicator values 
float atrValue = ta.atr(ATR_LENGTH)

// Calculate stop loss values
var float trailingStopLoss = na 
float longStop  = ta.lowest(low, BAR_LOOKBACK) - (atrValue * ATR_MULTIPLIER)
float shortStop = ta.highest(high, BAR_LOOKBACK) + (atrValue * ATR_MULTIPLIER)

// Check if we can take trades 
bool canTakeTrades = not na(atrValue)
bgcolor(canTakeTrades ? na : color.red)

// Enter long trades (replace this entry condition)
longCondition = canTakeTrades and ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition and strategy.position_size == 0)
    strategy.entry("Long", strategy.long)

// Enter short trades (replace this entry condition)
shortCondition = canTakeTrades and ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if (shortCondition and strategy.position_size == 0)
    strategy.entry("Short", strategy.short)

// Update trailing stop
if (strategy.position_size > 0)
    if (na(trailingStopLoss) or longStop > trailingStopLoss)
        trailingStopLoss := longStop
else if (strategy.position_size < 0)
    if (na(trailingStopLoss) or shortStop < trailingStopLoss)
        trailingStopLoss := shortStop
else
    trailingStopLoss := na

// Exit trades with trailing stop
strategy.exit("Long Exit",  "Long",  stop=trailingStopLoss)
strategy.exit("Short Exit", "Short", stop=trailingStopLoss)

// Draw stop loss 
plot(trailingStopLoss, "Stop Loss", color.red, 1, plot.style_linebr)