Fixed Volatility Oscillator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Written by: @creksar_stock - please credit if you use 
//@version=5

indicator("Volatility Expansions", "Volatility Expansions", overlay = false, format = format.percent)

//volatility lookback loop
LBV = input.string("50 Candles", "Candle Lookback # For Determining Volatility", options = ["10 Candles", "25 Candles", "50 Candles", "75 Candles", "100 Candles"], tooltip = "While it is possible to change lookback, It is not reccomended as it causes major inaccuracy and volatility spikes.")

switchCandleLoopback(getval) => //// you can edit the candle lookback period here and here^
    switch getval
        "10 Candles"   => 10
        "25 Candles"   => 25
        "50 Candles"   => 50
        "75 Candles"   => 75
        "100 Candles"  => 100

float lbmult = 0.0 // don't mess with this
maxNumberOfCandles = switchCandleLoopback(LBV)

for i = 1 to maxNumberOfCandles
    lbmult += volume[i]
lbmult := lbmult/maxNumberOfCandles

//volatility calculations
lbavg = math.avg(lbmult, maxNumberOfCandles)
diff = lbmult - lbavg

dev1 = ta.dev(lbmult, 2)
dev2 = ta.dev(lbavg, 2)
sqrdev1 = dev1*dev1
sqrdev2 = dev2*dev2

sqrsum = sqrdev1 + sqrdev2
_vol = sqrsum/maxNumberOfCandles

volatility = math.avg(_vol, sqrsum)

//main plot processing
maxL = ta.highest(volatility, maxNumberOfCandles)
minL = ta.lowest(volatility, maxNumberOfCandles)
R = maxL - minL
Volplot = 101 * volatility / R
hline(100, "Max Volatility", color.new(color.gray, 5), hline.style_solid, 1, false)
hline(0, "Minimum Volatility", color.new(color.gray, 5), hline.style_solid, 1, false)
plot(Volplot, color = color.white)

