Nasdaq VXN Volatility Warning Indicator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version = 5
// Author = TradeAutomation


indicator("Nasdaq VXN Volatility Warning Indicator", shorttitle="Nasdaq VXN Volatility Warning")


// Pulls in Nasdaq Volatility VXN data
res = input.timeframe(title="VXN Resolution", defval="60")
vxn = request.security("CBOE:VXN", res, high)

// Calculates the Variance and Defines the Volatility Warning
mean = ta.sma(vxn, input.int(2400, "Mean Length For Variance Calc"))
SquaredDifference = math.pow(vxn-mean, 2)
VolWarningLength = input.int(20, "Sustain Warning For X Bars", step=5)
SquaredDifferenceThreshold = input.int(150, "Variance Threshold", tooltip="The indicator will go up once the variance exceeds this threshold")
VolatilityWarning = ta.highest(SquaredDifference, VolWarningLength)>SquaredDifferenceThreshold
Warning = VolatilityWarning ? 1 : 0

// Plot
PlotVarianceInput = input.bool(false, "Plot the Variance?")
IndicatorColor = Warning > 0.5 ? color.red : Warning < 0.5 ? color.purple : na
plot(Warning, color=IndicatorColor, linewidth=2)
VariancePlot = PlotVarianceInput == true ? SquaredDifference : na
plot(VariancePlot, color=color.purple)
hline(input(1, "Custom H-Line"))
