Efficiency-Ratio-Adaptive EMA [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("Efficiency-Ratio-Adaptive EMA [Loxx]", 
     shorttitle = "ERAEMA [Loxx]", 
     overlay = true, 
     timeframe="", 
     timeframe_gaps = true)

greencolor = #2DD204
redcolor = #D2042D 

src = input.source(close, "Source", group = "Basic Settings")
per = input.int(14, "Period", group = "Basic Settings")

colorbars = input.bool(false, "Color bars?", group = "UI Options")

m_fastEnd = math.max(per / 2.0, 1)
m_slowEnd = per * 5

signal = 0.
noise = 0.
difference = src - nz(src[1])

if (bar_index > per) 
    signal := math.abs(src - nz(src[per]))
    noise := nz(noise[1]) + difference - nz(difference[per])
else 
    noise := difference
    for k = 1 to per - 1  
        noise += nz(difference[k])

efratio = signal / noise
averagePeriod = noise > 0 ? (efratio * (m_slowEnd - m_fastEnd)) + m_fastEnd : per
val = 0., valc = 0.
val := nz(val[1]) + (2.0 / (1.0 + averagePeriod)) * (src - nz(val[1]))
valc := val > nz(val[1]) ? 1 : val < nz(val[1]) ? 2 : nz(valc[1])

colorout = valc == 1 ? greencolor : valc == 2 ? redcolor : color.gray

plot(val, color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)













