Kaufman's Efficiency Ratio Indicator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DojiEmoji

//@version=5
indicator("Kaufman's ER", overlay=false)

kaufman_ER(src, len) =>
// {
    float total_abs_chng = 0  // [B]
    for i = 1 to len by 1
        total_abs_chng += math.abs(src[i - 1] - src[i])
        total_abs_chng

    float net_chng = src - src[len]  // [A]

    float er = net_chng / total_abs_chng * 100  // = ([A]/[B]) * 100
    er
// }

bool is_dir = input(true, title="Directional")
period = input(10, title="Lookback period")

ER = is_dir ? kaufman_ER(close, period) : math.abs(kaufman_ER(close, period))


// Modes
var string MODE_STATIC = 'Static threshold'
var string MODE_DYNAMIC = 'Dynamic threshold'
var string mode = input.string(title='If checked above: Presets', defval=MODE_STATIC, options=[MODE_STATIC, MODE_DYNAMIC])

// Static mode
int static_low = input.int(25, minval=0, maxval=100, title="Threshold for low", group="Static mode")
int static_high = input.int(50, minval=0, maxval=100, title="Threshold for high", group="Static mode")
var color color_low  = input.color(color.new(color.green, 0),title="Color (low)", group="Static mode")
var color color_mid  = input.color(color.new(color.yellow , 0),title="Color (mid)", group="Static mode")
var color color_high = input.color(color.new(color.red, 0),title="Color (high)", group="Static mode")
//
// Dynamic mode
float ER_bar = ta.sma(math.abs(ER), period)
float ER_sigma = ta.stdev(math.abs(ER), period)
float ER_sigma_mult = input.float(0.5, 'Dynamic mode: stdev multiplier', step=0.1, group="Dynamic mode")
float dynamic_low = ER_bar - ER_sigma * ER_sigma_mult
float dynamic_high = ER_bar + ER_sigma * ER_sigma_mult
//


bool is_low  = na
bool is_mid  = na
bool is_high = na

if mode == MODE_STATIC
	is_low  := math.abs(ER) <= static_low
	is_mid  := math.abs(ER) >= static_low and math.abs(ER) < static_high
	is_high := math.abs(ER) >= static_high
else if mode == MODE_DYNAMIC
    is_low  := math.abs(ER) <= dynamic_low
    is_mid  := math.abs(ER) >= dynamic_low and math.abs(ER) < dynamic_high
    is_high := math.abs(ER) >= dynamic_high

hline(static_high, linestyle=hline.style_dashed, title="High", color=color.new(color.gray, 50), editable=true)
hline(static_low, linestyle=hline.style_dashed, title="low", color=color.new(color.gray, 50), editable=true)

var int coeff = is_dir ? -1 : 1
hline(coeff*static_high, linestyle=hline.style_dashed, title="High", color=color.new(color.gray, 50), editable=true)
hline(coeff*static_low, linestyle=hline.style_dashed, title="low", color=color.new(color.gray, 50), editable=true)

p0 = plot(0, color=color.new(color.gray, 0), title="Zeroline")
p1 = plot(ER, "Efficiency ratio", color=is_high ? color_high : is_mid ? color_mid : color_low, style=plot.style_columns)
