//@version=6
indicator(title="Moving Average Convergence Divergence", shorttitle="MACD", timeframe="", timeframe_gaps=true)
// Inputs
fast_length = input.int(title="Fast Length", defval=12)
slow_length = input.int(title="Slow Length", defval=26)
src = input.source(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval=1, maxval=50, defval=9, display=display.data_window)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA","EMA"], display=display.data_window)
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA","EMA"], display=display.data_window)
// MACD core
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
// ----- Direction (slope) detection -----
was_rising = hist[1] > hist[2]
was_falling = hist[1] < hist[2]
now_rising = hist > hist[1]
now_falling = hist < hist[1]
// ----- Zone helpers -----
in_pos = hist > 0
in_neg = hist < 0
// ===== ALERТS =====
// 1) Зміна кольору (нахилу) — ГЛОБАЛЬНО
alertcondition(was_rising and now_falling, title="Rising → Falling", message="MACD histogram turned from rising to falling")
alertcondition(was_falling and now_rising, title="Falling → Rising", message="MACD histogram turned from falling to rising")
// 2) Зміна кольору тільки ВИЩЕ нуля
alertcondition(was_rising and now_falling and in_pos, title="Rising → Falling (above 0)", message="MACD histogram turned down while above zero")
alertcondition(was_falling and now_rising and in_pos, title="Falling → Rising (above 0)", message="MACD histogram turned up while above zero")
// 3) Зміна кольору тільки НИЖЧЕ нуля
alertcondition(was_rising and now_falling and in_neg, title="Rising → Falling (below 0)", message="MACD histogram turned down while below zero")
alertcondition(was_falling and now_rising and in_neg, title="Falling → Rising (below 0)", message="MACD histogram turned up while below zero")
// (Опційно) перетини нуля гістограмою
alertcondition(ta.crossunder(hist, 0), title="Histogram cross↓ zero", message="MACD histogram crossed below 0")
alertcondition(ta.crossover(hist, 0), title="Histogram cross↑ zero", message="MACD histogram crossed above 0")
// (Опційно) перетини MACD/Signal
alertcondition(ta.crossover(macd, signal), title="MACD cross↑ Signal", message="MACD crossed above Signal")
alertcondition(ta.crossunder(macd, signal), title="MACD cross↓ Signal", message="MACD crossed below Signal")
// Plots
hline(0, "Zero Line", color=color.new(#787B86, 50))
plot(hist, title="Histogram", style=plot.style_columns,
color=(hist >= 0 ? (hist[1] < hist ? #26A69A : #B2DFDB) : (hist[1] < hist ? #FFCDD2 : #FF5252)))
plot(macd, title="MACD", color=#2962FF)
plot(signal, title="Signal", color=#FF6D00)