MACD + EMA System with Alerts
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © andryrads

//@version=5
indicator(title='MACD + EMA System with Alerts')

source = close

// Input Parameter
emaPeriod = input(200)
fastLength = input(12)
slowLength = input(26)
signalLength = input(9)

// EMA Logic
ema = ta.ema(source, emaPeriod)
isTrendUp = close > ema
isTrendDown = close < ema

// MACD Logic
fastMA = ta.ema(source, fastLength)
slowMA = ta.ema(source, slowLength)
macd = fastMA - slowMA
signal = ta.sma(macd, signalLength)
hist = macd - signal
outMACD = request.security(syminfo.tickerid, timeframe.period, macd)
outSignal = request.security(syminfo.tickerid, timeframe.period, signal)
outHist = request.security(syminfo.tickerid, timeframe.period, hist)

// MACD Area Logic
isMACDupside = signal > 0
isMACDdownside = signal < 0

// Histogram 4 Color Logic
histA_IsUp = outHist > outHist[1] and outHist > 0
histA_IsDown = outHist < outHist[1] and outHist > 0
histB_IsDown = outHist < outHist[1] and outHist <= 0
histB_IsUp = outHist > outHist[1] and outHist <= 0

// MACD Cross Color Logic
macd_IsAbove = outMACD >= outSignal
macd_IsBelow = outMACD < outSignal

// Indicator Color Definition
macd_color = #2963ff
signal_color = #ff9901
hist_color = histA_IsUp ? #4caf50 : histA_IsDown ? #1b5e20 : histB_IsDown ? #f33645 : histB_IsUp ? #801923 : color.gray
cross_color = macd_IsAbove ? color.rgb(0, 230, 118) : color.rgb(235, 92, 92)

// Y position of crossing signal
YPosition = outSignal

// Chart Plotting Section
plot(outMACD, title='Main Line', color=color.new(macd_color, 0), style=plot.style_line, linewidth=1)
plot(outSignal, title='Signal Line', color=color.new(signal_color, 0), style=plot.style_line, linewidth=1)
plot(outHist, title='Histogram', color=hist_color, style=plot.style_columns, linewidth=1)
plot(isTrendUp and isMACDdownside and ta.crossover(outMACD, outSignal) ? YPosition : na, title='MACD Crossover', style=plot.style_circles, linewidth=2, color=cross_color)
plot(isTrendDown and isMACDupside and ta.crossunder(outMACD, outSignal) ? YPosition : na, title='MACD Crossunder', style=plot.style_circles, linewidth=2, color=cross_color)
hline(0, 'Middle Line', linestyle=hline.style_solid, linewidth=1, color=color.white)

// Signal & Alerting section
entryLong = isTrendUp and isMACDdownside and ta.crossover(outMACD, outSignal)
entryShort = isTrendDown and isMACDupside and ta.crossunder(outMACD, outSignal)
alertcondition(entryLong, 'Buy Signal', '{{ticker}} : Buy Entry!')
alertcondition(entryShort, 'Sell Signal', '{{ticker}} : Sell Entry!')

