Adaptive Moving Average with ATR bands
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © raminyazdanpanah - 2023

//@version=5
indicator(title = "Adaptive Moving Average with ATR bands", shorttitle="iMA", overlay=true)

// Inputs
length = input.int(title = "Length", defval=8, minval = 0, confirm = true)
fastLength = input.int(title = "Fast EMA Length", defval = 5, minval = 0, confirm = true)
slowLength = input.int(title = "Slow EMA Length", defval = 14, minval = 0, confirm = true)
atrPeriod = input.int(title = "ATR period", defval=14, minval = 0, confirm = true)
atrFactor = input.float(title = "ATR Factor", defval = 0.5, minval = 0, confirm = true)
src = input.source(title="Source", defval=close)
slAtr = input.int(title = "X ATR stop loss", defval = 2, minval = 0, confirm = true)

// Fast and slow constants for EMA's
fastAlpha = 2 / (fastLength + 1)
slowAlpha = 2 / (slowLength + 1)

// Direction
hh = ta.highest(length + 1)
ll = ta.lowest(length + 1)

// Efficiency Ratio
mltp = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0

// Scalable Constant
ssc = mltp * (fastAlpha - slowAlpha) + slowAlpha

// adaptive moving average
ama = 0.0
ama := nz(ama[1]) + math.pow(ssc, 2) * (src - nz(ama[1]))

// ATR bands
halfAtr = ta.atr(atrPeriod) * atrFactor
upperBnad = ama + halfAtr
lowerBand = ama - halfAtr

// Stop loss
sl = slAtr * ta.atr(atrPeriod)

// ploting
plot(ama, title="AMA", linewidth=2, color= color.yellow)
plot(upperBnad, title = "Upper Band", linewidth = 2, color = color.blue)
plot(lowerBand, title = "Lower Band", linewidth = 2, color = color.red)
plot(slAtr*ta.atr(atrPeriod), title = "X ATR stop loss", color = color.orange, display = display.status_line)