// 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("Mogalef Bands", overlay=true)

// === Inputs ===
lp = input.int(25, title="Linear Regression Period")
sp = input.int(30, title="StdDev Period")

// === Helper function: Linear Regression ===
linear_regression(src, len) =>
    var float slope = na
    var float intercept = na
    float sumX = 0
    float sumY = 0
    float sumXY = 0
    float sumX2 = 0

    for i = 0 to len - 1
        sumX += i
        sumY += src[i]
        sumXY += i * src[i]
        sumX2 += i * i

    divisor = (len * sumX2 - sumX * sumX)
    slope := divisor == 0 ? 0 : (len * sumXY - sumX * sumY) / divisor
    intercept := (sumY - slope * sumX) / len

    // Value at bar zero (most recent)
    intercept + slope * (len - 1)

// === Build arrays for LinReg and StdDev ===
var float[] linreg_arr = array.new_float()
var float[] stddev_arr = array.new_float()

linreg_val = linear_regression(close, lp)
array.unshift(linreg_arr, linreg_val)
if array.size(linreg_arr) > 500
    array.pop(linreg_arr)

stddev_val = ta.stdev(array.get(linreg_arr, 0), sp)
array.unshift(stddev_arr, stddev_val)
if array.size(stddev_arr) > 500
    array.pop(stddev_arr)

// === Calculate bands ===
hiband = linreg_val + stddev_val * 2
loband = linreg_val - stddev_val * 2
median = (hiband + loband) / 2

// === Apply the Mogalef override logic ===
hiband_prev = nz(hiband[1])
loband_prev = nz(loband[1])
linreg_prev = nz(linreg_val[1])

hiband := (linreg_val < hiband_prev and linreg_val > loband_prev) ? hiband_prev : hiband
loband := (linreg_val < hiband_prev and linreg_val > loband_prev) ? loband_prev : loband
median := (hiband + loband) / 2

// === Plot bands ===
plot(hiband, color=color.red, title="Upper Band", style=plot.style_line)
plot(loband, color=color.green, title="Lower Band", style=plot.style_line)
plot(median, color=color.blue, title="Median", style=plot.style_line)
