Volatility
ATR Trailing Stop
A stop that trails a multiple of average true range behind price and flips side when it is breached, so the stop distance widens in fast conditions and tightens in quiet ones.
indicator
//@version=6
indicator("ATR Trailing Stop", "ATR Stop", overlay = true)
atrLen = input.int(14, "ATR length", minval = 1, group = "Settings")
mult = input.float(2.5, "Multiplier", minval = 0.1, step = 0.1, group = "Settings")
bull = input.color(#26A69A, "Long", group = "Style")
bear = input.color(#EF5350, "Short", group = "Style")
atr = ta.atr(atrLen)
longCandidate = close - atr * mult
shortCandidate = close + atr * mult
var float stop = na
var bool isLong = true
if na(stop)
stop := longCandidate
else if isLong
stop := math.max(stop, longCandidate)
if close < stop
isLong := false
stop := shortCandidate
else
stop := math.min(stop, shortCandidate)
if close > stop
isLong := true
stop := longCandidate
plot(stop, "Trailing stop", color = isLong ? bull : bear, style = plot.style_linebr, linewidth = 2)
flippedLong = isLong and not isLong[1]
flippedShort = not isLong and isLong[1]
plotshape(flippedLong, "Flip long", location = location.belowbar, style = shape.triangleup, color = bull, size = size.tiny)
plotshape(flippedShort, "Flip short", location = location.abovebar, style = shape.triangledown, color = bear, size = size.tiny)
alertcondition(flippedLong, "Stop flipped long", "The ATR trailing stop flipped to the long side")
alertcondition(flippedShort, "Stop flipped short", "The ATR trailing stop flipped to the short side")
This runs in TradingView, not here
Pine Script only executes inside TradingView. Paste the source into the Pine Editor and add it to a chart to see it plotted.
What it will not do
- This is a stop, not an entry. It says where a trade is wrong, not where one is worth taking.
- It flips repeatedly in a range. The multiplier is the only defence, and raising it costs you on the trend it is meant to catch.
Written from this description
Draw a trailing stop line a multiple of ATR away from price. Ratchet it in the direction of the trade, never against it, flip to the other side when price closes through it, and mark the flip.
Educational only, not financial advice. The maths is simple arithmetic on the numbers you enter; it knows nothing about your broker, fees, slippage or the market. Something wrong with it? Say so in Site Feedback.