// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("BB-HL", overlay=true)

// === INPUTS ===
per   = input.int(200, title="Period")
nDev  = input.float(2.0, title="Deviation Multiplier")

// === CALCULATIONS ===
medianPrice = hl2
ma = ta.sma(medianPrice, per)

// Compute squared deviation using max of High and Low deviation from MA
highDev = math.pow(high - ma, 2)
lowDev  = math.pow(low - ma, 2)
devMax  = math.max(highDev, lowDev)

// Rolling average of max squared deviation
devAvg = 0.0
devSum = 0.0

// Use a manual loop to simulate rolling sum of devMax
var float[] devBuffer = array.new_float()

// Update the buffer each bar
if bar_index > 0
    array.push(devBuffer, devMax)
    if array.size(devBuffer) > per
        array.shift(devBuffer)

// Compute rolling average from buffer
if array.size(devBuffer) >= per
    for i = 0 to array.size(devBuffer) - 1
        devSum := devSum + array.get(devBuffer, i)
    devAvg := devSum / per

// Standard deviation and bands
stdev = math.sqrt(devAvg)
upper = ma + nDev * stdev
lower = ma - nDev * stdev

// === PLOTS ===
plot(ma, title="MA", color=color.orange)
plot(upper, title="Upper Band", color=color.silver)
plot(lower, title="Lower Band", color=color.silver)
