// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ // © Venture Lab – https://venturelab-bots.pages.dev/pine/ // // ATR trailing stop. // What it does: draws a stop line at "ATR multiplier" x ATR away from the close. In an up phase the line // only moves up; when a bar closes below it, the phase flips to down and the line starts above price // (and only moves down) until a bar closes above it again. Flips are marked and can trigger alerts. // What it does NOT do: it places no orders, it does not guarantee fills at the line (gaps and slippage), // it is not a trading system and it is not financial advice. On the open bar the line and the phase can // still change until the bar closes. //@version=6 indicator("ATR Trailing Stop [Venture Lab]", shorttitle = "ATR Trail", overlay = true) // ---- Inputs int atrLen = input.int(14, "ATR length", minval = 1) float mult = input.float(3.0, "ATR multiplier", minval = 0.1, step = 0.1) // ---- Calculation float atr = ta.atr(atrLen) float dist = mult * atr var float trail = na var int dir = 1 // 1 = up phase (stop below price), -1 = down phase (stop above price) if na(atr) trail := na else if na(trail) trail := close - dist dir := 1 else if dir == 1 if close < trail dir := -1 trail := close + dist else trail := math.max(trail, close - dist) else if close > trail dir := 1 trail := close - dist else trail := math.min(trail, close + dist) int prevDir = nz(dir[1], dir) bool flipUp = dir == 1 and prevDir == -1 bool flipDown = dir == -1 and prevDir == 1 // ---- Plots plot(dir == 1 ? trail : na, "Stop (up phase)", color = color.teal, linewidth = 2, style = plot.style_linebr) plot(dir == -1 ? trail : na, "Stop (down phase)", color = color.red, linewidth = 2, style = plot.style_linebr) plotshape(flipUp, "Flip to up", shape.circle, location.belowbar, color.teal, size = size.tiny) plotshape(flipDown, "Flip to down", shape.circle, location.abovebar, color.red, size = size.tiny) // ---- Alerts alertcondition(flipUp, "ATR stop flip up", "Close crossed above the ATR trailing stop on {{ticker}} ({{interval}})") alertcondition(flipDown, "ATR stop flip down", "Close crossed below the ATR trailing stop on {{ticker}} ({{interval}})")