VIX Reference Indicator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Steversteves

//@version=5
indicator("VIX Reference", max_labels_count = 500)


// Settings
timeframe = input.timeframe("") 
AvgLength   = input.int(75, title="Average Length")
vix = request.security("CBOE:VIX", timeframe, close) 
RSILength = input.int(14, title="RSI Length")
ZLength = input.int(75, title="Reversal Z-Score Length")

// Calculcate Z Score 

vixhx = ta.sma(vix, AvgLength) 
vixsd = ta.stdev(vix, AvgLength) 

z = (vix - vixhx) / vixsd 


// Reversal Points

vixmax = ta.highest(z, ZLength) 
vixmin = ta.lowest(z, ZLength) 

// RSI 

rsi = ta.rsi(vix, RSILength) 
bool bearishrsi = rsi <= 30 
bool bullishrsi = rsi >= 70 

// Color 

bear = color.new(color.red, 0) 
bull = color.new(color.green, 0) 
neutral = color.new(color.blue, 0) 
color pallette = bearishrsi ? bear : bullishrsi ? bull : neutral 

plot(z, color=pallette, linewidth=4)


// Condition Alerts
var wait = 0

wait := wait + 1 

if (z >= vixmax) and (wait > 50)
    wait := 10
    label.new(x=bar_index, y=vixmax, text="Buy", size = size.tiny, color=color.green)
    alert("Buy The Dip "+syminfo.ticker, alert.freq_once_per_bar)
    

if (z <= vixmin) and (wait > 50)
    wait := 10
    label.new(x=bar_index, y=vixmin, text="Sell", size = size.tiny, color=color.red)
    alert("Sell The Rally "+syminfo.ticker, alert.freq_once_per_bar)

// Fills
upperband = hline(2.5, "Upper Band", color=color.gray)
lowerband = hline(-2.5, "Lower Band", color=color.gray)
centreband = hline(0, "Centre Band", color=color.yellow)

color fillcolor = color.new(color.gray, 95) 

fill(upperband, lowerband, color=fillcolor)