Impulse levels
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © IldarAkhmetgaleev

//@version=5
indicator("Impulse levels", overlay=true)

n_bars = input.int(5, "Number of bars to average", minval=3, maxval=50)
atr_impulse_thr = input.int(120, "ATR impulse thresshold % (0 to disable)", minval=0, maxval=500)
vol_impulse_thr = input.int(200, "Volume impulse thresshold % (0 to disable)", minval=0, maxval=1000)
level_color = input.color(color.orange, "Level color")

find_impulse() =>
    atr = ta.atr(n_bars)
    min_atr = ta.lowest(atr, n_bars)
    wide_min_atr = ta.lowest(atr, n_bars * 2)
    by_atr = wide_min_atr == atr[n_bars] and min_atr[n_bars + 1] > atr[n_bars] and atr > min_atr[n_bars] * (float(atr_impulse_thr) / 100.0)
    
    avg_vol = ta.sma(volume, n_bars)
    max_vol = ta.highest(volume, n_bars) 
    by_vol = max_vol > avg_vol[n_bars] * (float(vol_impulse_thr) / 100.0)
    
    (atr_impulse_thr == 0 or by_atr) and (vol_impulse_thr == 0 or by_vol)


impulse_price(n) =>
    ta.valuewhen(find_impulse(), close[n_bars], n)

brake_line(value) =>
	value == value[1] ? value : na


clrI = color.new(level_color, 0)
imp = find_impulse() ? close[n_bars] : na
plotshape(imp, "Impulse root", shape.circle, location=location.absolute, color=clrI, offset=-n_bars+1)

clr0 = color.new(level_color, 15)
lvl0 = brake_line(impulse_price(0))
plot(lvl0, "Impulse level 0", color=clr0, style=plot.style_linebr, offset=-n_bars+1)

clr1 = color.new(level_color, 40)
lvl1 = brake_line(impulse_price(1))
plot(lvl1, "Impulse level 1", color=clr1, style=plot.style_linebr,  offset=-n_bars+1)

clr2 = color.new(level_color, 60)
lvl2 = brake_line(impulse_price(2))
plot(lvl2, "Impulse level 2", color=clr2, style=plot.style_linebr,  offset=-n_bars+1)

clr3= color.new(level_color, 80)
lvl3 = brake_line(impulse_price(3))
plot(lvl3, "Impulse level 3", color=clr3, style=plot.style_linebr,  offset=-n_bars+1)

clr4= color.new(level_color, 90)
lvl4 = brake_line(impulse_price(4))
plot(lvl4, "Impulse level 4", color=clr4, style=plot.style_linebr,  offset=-n_bars+1)