Rough Average
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © QuantiLuxe

//@version=5
indicator("Rough Average", "{Ʌ} -‌ Rough Avg.", false)

len = input.int(14, "Length", group = "Rough AVG")
upper = input.int(80, "Upper Level", group = "Rough AVG")
lower = input.int(20, "Lower Level", group = "Rough AVG")
colbar = input.string("None", "Bar Coloring", ["None", "Trend", "Extremities", "Reversions"], group = "UI Options")
revshow = input.bool(true, "Show Reversal Signals", group = "UI Options")

f_checkp() =>
    p = close
    count = 0

    while p > 1
        p /= 10
        count += 1

    math.pow(10, count)

f_profile(len) =>
    l = len
    integral = 0.0

    f_x = math.abs(ta.rsi(close, len)) 

    for x = low / f_checkp() to high / f_checkp() 
        integral := integral + f_x

    l * integral

spacing_profile = f_profile(len)

ra = ta.rsi(ta.ema(spacing_profile, len), len)

col_up = #3179f5
col_dn = #ab47bc

d = plot(ra, "RA", ra > 50 ? color.from_gradient(ra, 40, upper, #00000000, col_up) : color.from_gradient(ra, lower, 60, col_dn, #00000000))
hline(50, "Mid Line", #ffffff80, hline.style_dotted)
u = plot(upper, "Upper Line", #ffffff80, display = display.pane)
l = plot(lower, "Lower Line", #ffffff80, display = display.pane)

fill(d, u, 95, upper, col_dn, #aa47bc00)
fill(d, l, lower, 5, #3179f500, col_up)

plotshape(revshow ? ra > upper and ra < ra[1] and not (ra[1] < ra[2]) ? 110 : na : na, "OB", shape.triangledown, location.absolute, col_up, size = size.tiny)
plotshape(revshow ? ra < lower and ra > ra[1] and not (ra[1] > ra[2]) ? -10 : na : na, "OS", shape.triangleup, location.absolute, col_dn, size = size.tiny)

color col = switch colbar
    "None" => na
    "Trend" => ra > 50 ? col_up : col_dn
    "Extremities" => ra > upper ? col_up : ra < lower ? col_dn : #b3b3b3c2
    "Reversions" => ra > upper and ra < ra[1] and not (ra[1] < ra[2]) ? col_up : ra < lower and ra > ra[1] and not (ra[1] > ra[2]) ? col_dn : #b3b3b3c2

barcolor(col)