Intraday Volatility Bars
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © weak_hand

//@version=5
indicator("Intraday Volatility Bars")

// ----------------------------------------------}
// INPUT AND VARIABLES
// ----------------------------------------------{

int bars_per_day = math.ceil(1440 / timeframe.multiplier)
var bars_count   = int(0)

int length = input.int(14, "Length", 1, tooltip = "How many days back should be taken into account.")
var cumulative_volatility_bars = matrix.new<float>(bars_per_day, length)
var cumulative_volatility      = float(0)

float true_range = ta.tr(false)

// ----------------------------------------------}
// CALCULATIONS
// ----------------------------------------------{

if session.isfirstbar
    bars_count := 0
    cumulative_volatility := high - low
    cumulative_volatility_bars.add_col(0)
    cumulative_volatility_bars.remove_col(length)
else
    cumulative_volatility := cumulative_volatility + true_range
    bars_count += 1

cumulative_volatility_bars.set(bars_count, 0, cumulative_volatility)
float[] volatility_rows = cumulative_volatility_bars.row(bars_count)

// ----------------------------------------------}
// OUTPUTS
// ----------------------------------------------{

plot(volatility_rows.avg(), "Average", color.gray, style = plot.style_columns)
plot(cumulative_volatility, "IVB", linewidth = 2, style = plot.style_circles)
