length = input.int(14, 'Length')
multiplier = input.float(4, 'Multiplier')
var dir = 1
var stopDistance = ta.atr(length) * multiplier
// Remove var to fix the first issue
// stopDistance = ta.atr(length) * multiplier
buyStopCurrent = close-stopDistance
sellStopCurrent = close + stopDistance
var buyStop = buyStopCurrent
var sellStop = sellStopCurrent
buyStop := dir > 0? math.max(buyStop, buyStopCurrent) : buyStopCurrent
sellStop := dir < 0? math.min(sellStop, sellStopCurrent) : sellStopCurrent
// Use nz to overcome na issues with math.max/ math.min
// buyStop := dir > 0? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent) : buyStopCurrent
// sellStop := dir < 0? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent) : sellStopCurrent
dir := dir == 1 and close < buyStop? -1 : dir == -1 and close > sellStop ? 1 : dir
// Plot statements used for debugging. display is set to display.data_window as the debugging plots do not need to appear on the charts
plot(stopDistance, 'Stop Distance', color.purple, display = display.data_window)
plot(buyStopCurrent, 'buyStopCurrent', color.red, display = display.data_window)
plot(sellStopCurrent, 'sellStopCurrent', color.green, display = display.data_window)
plot(buyStop, 'buyStop', color.red, display = display.data_window)
plot(sellStop, 'sellStop', color.green, display = display.data_window)
plot(dir, 'Direction', color.white, display = display.data_window)
plot(dir > 0? buyStop : sellStop, 'Supertrend', dir > 0? color.red : color.green)