Bitcoin Golden Bottom Oscillator (MZ BTC Oscillator)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MightyZinger

//@version=5

indicator(title='Bitcoin Golden Bottom Oscillator (MZ BTC Oscillator)', shorttitle='MZ BTC Oscillator', overlay=false)

src = request.security('INDEX:BTCUSD', '1D', close)

length = input.int(title='Adaptive MA Length', defval=365)
majLength = input.int(title='Major Length', defval=100)
minLength = input.int(title='Minor Length', defval=50)
rsiLen = input.int(14, minval=1,title="RSI Period")

//  Envelop Parameters
atr_mult = input.float(20, title='Distance (Envelope) Multiplier', step=.1, group='ENVELOPE DISTANCE ZONE')
env_atr = input.int(40, title='Envelope ATR Length', group='ENVELOPE DISTANCE ZONE')

ama(src,length,minLength,majLength)=>
    minAlpha = 2 / (minLength + 1)
    majAlpha = 2 / (majLength + 1)

    hh = ta.highest(length + 1)
    ll = ta.lowest(length + 1)

    mult = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0

    final = mult * (minAlpha - majAlpha) + majAlpha

    ma = 0.0
    ma := nz(ma[1]) + math.pow(final, 2) * (src - nz(ma[1]))
    ma

_low = request.security('INDEX:BTCUSD', '1D', low)
_ama = request.security('INDEX:BTCUSD', '1D', ama(src,length,minLength,majLength))

madif = (_low - _ama) / src * 100
// AMA Delta
deltaMA = ta.sma(math.abs(madif) , rsiLen)
// RSI
rsi = ta.rsi(math.abs(deltaMA), rsiLen)
osc = request.security('INDEX:BTCUSD', '1D', ta.hma(math.abs(rsi), rsiLen))

band0 = hline(80, "Overbought", color=#787B86, linestyle=hline.style_dashed)
band1 = hline(20, "Oversold", color=#787B86, linestyle=hline.style_dashed)
band2 = hline(50, "Middle", color=#787B86, linestyle=hline.style_dashed)
// Dynamic coloring function to detect trend
b_col = color.from_gradient(osc, 0, 100, color.rgb(8,255,8), color.rgb(225,6,0))
plot(osc, "Osc", b_col , 4)

// Enveloping AMA with ATR bands
env_MA = _ama
float dev = 0.0
dev :=  request.security('INDEX:BTCUSD', '1D', atr_mult * ta.atr(env_atr))
// Bands
b1 = env_MA + 0.236 * dev
t1 = env_MA + 0.764 * dev
t2 = env_MA + dev

bottom = madif < 20
local_b = _low < b1 and not bottom
out = request.security('INDEX:BTCUSD', '1D', high) > t2
local_out = request.security('INDEX:BTCUSD', '1D', high) > t1 and not out
bgcolor(bottom ? color.rgb(47, 249, 36, 60) : na)
bgcolor(local_b ? color.rgb(83,176,174, 70) : na)
bgcolor(out ? color.rgb(225,6,0, 60) : na)
bgcolor(local_out ? color.rgb(219,62,121, 80) : na)
