VolatilityChecker
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © boitoki

//@version=5

// @description Volatility is judged to be high when the range of one period is greater than the ATR of another period.
library("VolatilityChecker", overlay=false)


f_volatility (int _periods, int _smooth) =>
    v_top = close > open ? close : open
    v_bot = close > open ? open : close
    v_rng = ta.highest(math.avg(high, v_top), _periods) - ta.lowest(math.avg(low, v_bot), _periods)
    ta.ema(v_rng, _smooth)

f_atr (int _atr_periods, float _atr_times) =>
    ta.atr(_atr_periods) * _atr_times


// @function Return true if the volatility is high.
// @param _periods Range Period
// @param _smooth Smoothes the range width.
// @param _atr_periods ATR Period
// @param _atr_times Amplify the calculated ATR.
// @returns {Boolean}
export is_high (simple int _periods = 7, simple int _smooth = 3, simple int _atr_periods = 20, simple float _atr_times = 2.0) =>
    v_vola = f_volatility(_periods, _smooth)
    v_atr = ta.atr(_atr_periods) * _atr_times
    v_vola > v_atr

export is_low (simple int _periods = 7, simple int _smooth = 3, simple int _atr_periods = 20, simple float _atr_times = 2.0) =>
    not is_high(_periods, _smooth, _atr_periods, _atr_times)

// @return return the range width value and atr value
export value (simple int _periods = 7, simple int _smooth = 3, simple int _atr_periods = 20, simple float _atr_times = 2.0) =>
    [f_volatility(_periods, _smooth), ta.atr(_atr_periods) * _atr_times]

// Inputs
i_periods = input.int(7, 'Periods')
i_smooth = input.int(3, 'Smooth')
i_atr_periods = input.int(20, 'ATR periods')
i_atr_times = input.float(2.0, 'ATR times', step=.2)

// Calculating
v_main = f_volatility(i_periods, i_smooth)
v_is_high_volatility = is_high(i_periods, i_smooth, i_atr_periods, i_atr_times)
v_is_low_volatility = is_low(i_periods, i_smooth, i_atr_periods, i_atr_times)

barcolor(v_is_high_volatility ? color.maroon : v_is_low_volatility ? color.purple : na)

// Plotting
plot(v_main, style=plot.style_columns, color=v_is_high_volatility ? color.purple : color.gray)
plot(f_atr(i_atr_periods, i_atr_times), color=color.orange)

