TheATR™: Volatility Extremes (VolEx)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © theATR

//@version=5
indicator("TheATR™: Volatility Extremes", "VolEx(TheATR™)")
//User has to agree to have the indi loading on the chart.
//{
var user_consensus = input.string(defval="", title="By typing 'Agree' you acknowledge the understanding about the fact 'TheATR™: Volatility Extremes' (or 'VolEx(TheATR™)') doesn't aim and/or intend to provide any financial advice, as of its nature of being an educational tool.\n © TheATR", confirm = true, group="consensus")
var valid = false
if user_consensus == "Agree"
    valid := true
else
    valid := false

var label lbl_agree_err = na
if not valid 
    runtime.error("'Agree' to the consensus policy first in order to display the Indicator.")
//}

//--Settings
//{

i_volex_t = input.string("%", "Extremes Detection Parameter", ["%", "St.Dev."], inline = 'sett00')
i_volex_lb = input.int(100, "Lookback", minval = 10, inline='sett01') 
i_volex_l = input.int(14, "ATR Base Lenght", minval = 2, inline='sett01')

i_volex_ptop = input.float(90.0, "↑ '%': % Thresholds: Top", minval = 60.0, maxval = 100.0, inline = 'sett02')
i_volex_pbot = input.float(10.0, "Bottom", minval = 0.0, maxval = 40.0, inline = 'sett02')

i_volex_stdev = input.float(2.0, "↑ 'St.Dev.': St.Dev. Factor", minval = 0.25, inline = 'step03')

i_volex_stndcol = input.color(color.blue, "Volatility Colors:\nStandard ", inline = 'settcols0')
i_volex_highcol = input.color(color.yellow, "Extremely High ", inline = 'settcols1')
i_volex_lowcol = input.color(color.rgb(161, 118, 0), "Extremely Low ", inline = 'settcols2')

//}

//--Calcs
//{

var volex_atr = 0.0
volex_atr := ta.atr(i_volex_l)

var volex_ptop = 0.0, var volex_pbot = 0.0
volex_ptop := ta.percentile_linear_interpolation(volex_atr, i_volex_lb, i_volex_ptop)
volex_pbot := ta.percentile_linear_interpolation(volex_atr, i_volex_lb, i_volex_pbot)

var volex_stdevtop = 0.0, var volex_stdevbot = 0.0
volex_stdevtop := ta.sma(volex_atr, i_volex_lb) + i_volex_stdev * ta.stdev(volex_atr, i_volex_lb)
volex_stdevbot := ta.sma(volex_atr, i_volex_lb) - i_volex_stdev * ta.stdev(volex_atr, i_volex_lb)

var volex_topf = 0.0, var volex_botf = 0.0
volex_topf := i_volex_t == "%" ? volex_ptop:volex_stdevtop 
volex_botf := i_volex_t == "%" ? volex_ptop:volex_stdevbot

var volex_high = false, var volex_low = false
volex_high := volex_atr > volex_topf
volex_low := volex_atr < volex_botf



//}

//--Plots
//{

var color volex_col = na
volex_col := volex_high?i_volex_highcol:volex_low?i_volex_lowcol:i_volex_stndcol

plot(valid?volex_atr:na, "ATR", volex_col, 1)
barcolor(valid and volex_high?i_volex_highcol:na)
barcolor(valid and volex_low?i_volex_lowcol:na)

//}

