// 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("MA Channels FiboEnv Mid", overlay=true)

// === INPUT PARAMETERS ===
barsCount     = input.int(1000, title="Bars Count")
maPeriod      = input.int(55, title="MA Period")
maType        = input.string("SMA", title="MA Type", options=["SMA", "EMA", "SMMA", "LWMA"])
priceSource   = input.string("Median", title="Price Source", options=["Close", "Open", "High", "Low", "Median", "Typical", "Weighted"])
maShift       = input.int(0, title="MA Shift")

// === PRICE SOURCE ===
src = switch priceSource
    "Close" => close
    "Open" => open
    "High" => high
    "Low" => low
    "Median" => hl2
    "Typical" => (high + low + close) / 3
    "Weighted" => (high + low + close + close) / 4

// === MA FUNCTION ===
getMA(source, length) =>
    switch maType
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA" => ta.rma(source, length)
        "LWMA" => ta.wma(source, length)

// === CALCULATE RANGE OVER LAST barsCount BARS ===
var float maxDev = na
var float minDev = na

if bar_index >= barsCount + maPeriod
    maxDev := 0.0
    minDev := 0.0
    for i = 0 to barsCount
        ma_i = getMA(src[i], maPeriod)
        top = high[i] - ma_i
        bottom = low[i] - ma_i
        maxDev := math.max(maxDev, top)
        minDev := math.min(minDev, bottom)

// === FIBO OFFSETS ===
inc4 = math.abs(maxDev) > math.abs(minDev) ? maxDev : minDev
inc1 = (maxDev - minDev) * 0.118
inc2 = (maxDev - minDev) * 0.264
inc3 = (maxDev - minDev) * 0.5

// === BASE MA ===
baseMA = getMA(src[maShift], maPeriod)

// === CHANNEL LEVELS ===
fibUp100 = baseMA + inc3
fibDn23  = baseMA + inc2
fibDn38  = baseMA + inc1
fib50    = baseMA
fibUp38  = baseMA - inc1
fibUp23  = baseMA - inc2
fibDn100 = baseMA - inc3

// === PLOT ===
plot(fibUp100, title="FibMA Up 100%", color=color.purple)
plot(fibDn23,  title="FibMA Down 23.5%", color=color.purple)
plot(fibDn38,  title="FibMA Down 38.2 / Up 61.8%", color=color.purple)
plot(fib50,    title="FibMA 50%", color=color.purple)
plot(fibUp38,  title="FibMA Up 38.2 / Down 61.8%", color=color.purple)
plot(fibUp23,  title="FibMA Up 23.5%", color=color.purple)
plot(fibDn100, title="FibMA Down 100%", color=color.purple)
