Adaptive ATR Keltner Channels [Loxx]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx

//@version=5

indicator("Adaptive ATR Keltner Channels [Loxx]", shorttitle = "AATRKC [Loxx]", 
     overlay = true, 
     timeframe="", 
     timeframe_gaps = true)

greencolor = #2DD204
redcolor = #D2042D 

src = input.source(close, "Source", group = "Basic Settings")
len = input.int(20, "Length", group = "Basic Settings")

minMult = input.int(1, "Min Multiplier", group = "Basic Settings")
midMult = input.int(2, "Mid Multiplier", group = "Basic Settings")
maxMult = input.int(3, "Max Multiplier", group = "Basic Settings")

showmin = input.bool(true, "Show min channels?", group = "UI Options")
showmid  = input.bool(true, "Show mid channels?", group = "UI Options")
showmax = input.bool(true, "Show max channels?", group = "UI Options")
fillcolor = input.bool(true, "Show fill color?", group = "UI Options")

mlen = (len > 1) ? len : 1
fast = math.max(mlen / 2.0, 1)
slow = mlen * 5

signal = 0., noise = 0., atr = 0., val = 0.

diff = src - nz(src[1]) 
diff := diff < 0 ? diff * -1.0 : diff

if (bar_index > mlen) 
    signal := src - nz(src[1]) 
    signal := signal < 0 ? signal * -1.0 : signal
    noise := nz(noise[1]) + diff - nz(diff[mlen])
else 
    noise := diff
    for k = 1 to mlen 
        noise += nz(diff[k])

efratio = noise != 0 ? signal/noise : 1
avgper = noise != 0 ? ((signal/noise) * (slow - fast)) + fast : mlen

atr := nz(atr[1]) + (2.0 / (1.0 + avgper)) * ((high - low) - nz(atr[1]))  
val := nz(val[1]) + (2.0 / (1.0 + avgper)) * (src - nz(val[1]))  

minUp = val + minMult * atr
minDn = val - minMult * atr

midUp = val + midMult * atr
midDn = val - midMult * atr

maxUp = val + maxMult * atr
maxDn = val - maxMult * atr

midplot = plot(val, "mid", color = close >= val ? greencolor : redcolor, linewidth = 3)

plot(showmin ? minUp : na, "minUp", color = color.new(greencolor, 50))
plot(showmin ? minDn : na, "minDn", color = color.new(redcolor, 50))

plot(showmid ? midUp : na, "midUp", color = color.new(greencolor, 50))
plot(showmid ? midDn : na, "midDn", color = color.new(redcolor, 50))

mupplot = plot(showmax ? maxUp : na, "maxUp", color = color.new(greencolor, 50))
mdnplot = plot(showmax ? maxDn : na, "maxDn", color = color.new(redcolor, 50))

fill(mupplot, midplot, fillcolor ? color.new(greencolor, 95) : na)
fill(mdnplot, midplot, fillcolor ? color.new(redcolor, 95) : na)













