Volatility Ratio Adaptive RSX [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("Volatility Raito Adaptive RSX [Loxx]",
     shorttitle="VRARSX [Loxx]", 
     overlay=false, 
     max_bars_back = 3000)

greencolor = #2DD204
redcolor = #D2042D 

lightgreencolor = #96E881 
lightredcolor =  #DF4F6C

_calculate(src, per)=>
    dev = ta.stdev(src, per)
    devavg = ta.sma(dev, per)
    out = dev/devavg 
    out

_rsx(src, len, spd)=>
    src_out = 100 * src
    mom0 = ta.change(src_out)
    moa0 = math.abs(mom0)
    Kg = 3 / (len + 2.0)
    Hg = 1 - Kg
    
    spdp1  = spd + 1.0

    //mom
    f28 = 0.0, f30 = 0.0
    f28 := Kg * mom0 + Hg * nz(f28[1])
    f30 := Hg * nz(f30[1]) + Kg * f28
    mom1 = f28 * spdp1 - f30 * spd
 
    f38 = 0.0, f40 = 0.0
    f38 := Hg * nz(f38[1]) + Kg * mom1
    f40 := Kg * f38 + Hg * nz(f40[1])
    mom2 = f38 * spdp1 - f40 * spd
 
    f48 = 0.0, f50 = 0.0
    f48 := Hg * nz(f48[1]) + Kg * mom2
    f50 := Kg * f48 + Hg * nz(f50[1])
    mom_out = f48 * spdp1 - f50 * spd
 
    //moa
    f58 = 0.0, f60 = 0.0
    f58 := Hg * nz(f58[1]) + Kg * moa0
    f60 := Kg * f58 + Hg * nz(f60[1])
    moa1 = f58 * spdp1 - f60 * spd
 
    f68 = 0.0, f70 = 0.0
    f68 := Hg * nz(f68[1]) + Kg * moa1
    f70 := Kg * f68 + Hg * nz(f70[1])
    moa2 = f68 * spdp1 - f70 * spd
 
    f78 = 0.0, f80 = 0.0
    f78 := Hg * nz(f78[1]) + Kg * moa2
    f80 := Kg * f78 + Hg * nz(f80[1])
    moa_out = f78 * spdp1 - f80 * spd
 
    rsiout = math.max(math.min((mom_out / moa_out + 1.0) * 50.0, 100.00), 0.00)
    rsiout
    
src  = input.source(close, "Source", group = "Basic Settings")
per = input.int(14, "Period", group = "Basic Settings")
spd  = input.float(0.5, "spd", step = 0.1, maxval = 1, minval = 0, group = "Basic Settings")

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

val = _rsx(src, int(per/volRatio), spd)
signal = val[1]
middle = 50

colorout = 
     val > signal and val > middle ? greencolor : 
     val < signal and val > middle ? lightgreencolor : 
     val < signal and val < middle ? redcolor : 
     val > signal and val < middle ? lightredcolor : 
     color.gray

plot(val, color = colorout, linewidth = 2)
plot(middle, color = bar_index % 2 ? color.gray : na)

barcolor(colorbars ? colorout : na)









