ER-Adaptive ATR [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("ER-Adaptive ATR [Loxx]", 
     shorttitle="ERAATR [Loxx]", 
     overlay = false, 
     timeframe="", 
     timeframe_gaps = true)

greencolor = #2DD204

src = input.source(hl2, "Source")
period = input.int(14, "ATR Period")

mper = (period > 1) ? period : 1
mfast = math.max(mper / 2.0, 1)
mslow = mper * 5
mperDiff = mslow - mfast
        
noise = 0., aatr = 0.

diff = math.abs(src - nz(src[1]))
signal = math.abs(src - nz(src[mper]))
noise := nz(noise[1]) + diff - nz(diff[mper])
avgper = (noise != 0) ? (signal / noise) * mperDiff + mfast : mper
aatr := nz(aatr[1]) + (2.0 / (1.0 + avgper)) * ((high - low) - nz(aatr[1]))  

ratr = ta.atr(period)
plot(aatr, "ER-Adaptive ATR", color = greencolor, linewidth = 2)
plot(ratr, "Regular ATR", color = color.white, linewidth = 1)
