ATR Trailing Stop Loss [V5]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BentonBuilding
//@version=5

indicator("ATR Trailing Stop Loss", 'ATR TS', overlay = true, timeframe = '')
atr_p_inp = input.int(5, 'ATR length', 1, 1000000, 1)
atr_m_inp = input.float(3.5, 'ATR mult.', 0.01, 1000000, 0.05)
gold_ent = input.bool (true, 'Gold Entry Directional Confluence', tooltip = 'Requirs Gold Sell Signals To Be On A Red Bar And Gold Buy Signal To Be On A Green Bar')
atr = ta.atr(atr_p_inp)
ts = atr_m_inp * atr


float atr_ts = na
if (close > nz(atr_ts[1], 0)) and (close[1] > nz(atr_ts[1], 0))
    atr_ts := (math.max(nz(atr_ts[1]), close - ts))
else 
    if (close < nz(atr_ts[1], 0)) and (close[1] < nz(atr_ts[1], 0))
        atr_ts := (math.min(nz(atr_ts[1]), close + ts))
    else
        if (close > nz(atr_ts[1], 0))
            atr_ts := (close - ts)
        else
            atr_ts := (close + ts)


float pos = na
if (close[1] < nz(atr_ts[1], 0)) and (close > nz(atr_ts[1], 0))
    pos := (1)
else
    if (close[1] > nz(atr_ts[1], 0)) and (close < nz(atr_ts[1], 0))
        pos := (-1)
    else
        pos := (nz(pos[1], 0))


color _color = na
if (pos == -1)
    _color := (color.red)
else 
    if (pos == 1)
        _color := (color.green)
    else
        _color := (color.blue)

plot (atr_ts, color=_color, title="ATR Trailing Stop")
plotshape (pos, 'UP/DOWN', location = location.bottom, color = _color)

long_trig = (close < atr_ts)[1] and (close > atr_ts)
shrt_trig = (close > atr_ts)[1] and (close < atr_ts)
long_gold = (close > atr_ts)    and (low   < atr_ts) and not ((close > atr_ts) and (low   < atr_ts))[1] and (gold_ent == true ? (close > open) : true)
shrt_gold = (close < atr_ts)    and (high  > atr_ts) and not ((close < atr_ts) and (high  > atr_ts))[1] and (gold_ent == true ? (close < open) : true)
plotshape (long_trig, 'Long',       shape.triangleup,   location.belowbar, color.green,  size = size.small)
plotshape (shrt_trig, 'Short',      shape.triangledown, location.abovebar, color.red,    size = size.small)
plotshape (long_gold, 'Gold Long',  shape.triangleup,   location.belowbar, color.yellow, size = size.small)
plotshape (shrt_gold, 'Gold Short', shape.triangledown, location.abovebar, color.yellow, size = size.small)

alertcondition (long_trig, 'Long', 'Green Triangles Below Price')
alertcondition (shrt_trig, 'Short', 'Red Triangles Above Price')
alertcondition ( (pos == 1),  'Long Condition',  'Moving In The Bullish Direction')
alertcondition ( (pos == -1), 'Short Condition', 'Moving In The Bearish Direction')
alertcondition (long_gold, 'Gold Long', 'Gold Triangles Below Price')
alertcondition (shrt_gold, 'Gold Short', 'Gold Triangles Above Price')







