ATR Start & Stop Bot
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mmoiwgg

//@version=4
study(title="ATR Start & Stop Bot", overlay = true)

//Inputs
res = input(title="Timeframe (check tooltip)", type=input.resolution, defval= "240", tooltip="Set the timeframe to a 4 hour if you are not using a 4 hour chart.")
nATRPeriod = input(10, title="ATR Period", tooltip="Try using Period 5 and Multiplier 3.5 on the 4 hour chart if default settings are not the best.")
nATRMultip = input(3, title="ATR Multiplier", step=0.10, tooltip="Make sure you are using this on a 4 hour chart.")

resScript = security(syminfo.tickerid, res, nATRMultip * atr(nATRPeriod))

xATRTrailingStop = 0.0
xATRTrailingStop := iff(close > nz(xATRTrailingStop[1], 0) and close[1] > nz(xATRTrailingStop[1], 0), max(nz(xATRTrailingStop[1]), close - resScript), 
     iff(close < nz(xATRTrailingStop[1], 0) and close[1] < nz(xATRTrailingStop[1], 0), min(nz(xATRTrailingStop[1]), close + resScript), 
     iff(close > nz(xATRTrailingStop[1], 0), close - resScript, close + resScript)))

pos = 0.0
pos :=    iff(close[1] < nz(xATRTrailingStop[1], 0) and close > nz(xATRTrailingStop[1], 0), 1, 
     iff(close[1] > nz(xATRTrailingStop[1], 0) and close < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0))) 

color = pos == -1 ? color.red: pos == 1 ? color.green : color.blue 

plot(xATRTrailingStop, color=color, linewidth=3, title="ATR Trailing Stop")
long  = pos == 1
short = pos == -1

last_long = 0.0
last_short = 0.0
last_long := long ? time : nz(last_long[1])
last_short := short ? time : nz(last_short[1])

long_signal = crossover(last_long, last_short)
short_signal = crossover(last_short, last_long)

StartBot = long_signal
StopBot = short_signal


// Plots Candle Colors
colors = last_long > last_short ? color.green : color.red
plotcandle(open, high, low, close, color=colors)


//Alerts
alertcondition(StartBot, title='Start Bot', message='Start Bot')
alertcondition(StopBot, title='Stop Bot',message='Stop Bot')