Moving Average Convergence Divergence
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kevindcarr

//@version=5
indicator(title='Moving Average Convergence Divergence', shorttitle='MACD')

var table conditions = table.new(position=position.top_right, columns=1, rows=3)

log = input.string(title="Scale", options=['Logarithmic', 'Regular'], defval='Logarithmic')
signal = input(title='Signal', defval=9)
long = input(title='Long', defval=26)
short = input(title='Short', defval=12)
source = input(title='Source', defval=close)

shortEma = ta.ema(source, short)
longEma = ta.ema(source, long)
macd = (log == 'Logarithmic' ? math.log(shortEma) - math.log(longEma) : shortEma - longEma)
sig = ta.ema(macd, signal)
hist = macd - sig

macdPlot = plot(series=macd, title='MACD', color=color.new(color.blue, 50))
sigPlot = plot(series=sig, title='Signal', color=color.new(color.silver, 50))
fill(macdPlot, sigPlot, transp=90)

highlightHistogram(hist) =>
    chg = ta.change(hist)
    if hist >= 0
        chg / hist > 0 ? color.green : color.new(color.green, 50)
    else
        chg / hist > 0 ? color.red : color.new(color.red, 50)

plot(hist, title='Histogram', style=plot.style_columns, color=highlightHistogram(hist))

bullSigX = ta.crossover(hist, 0)
bearSigX = ta.crossunder(hist, 0)
bull0X = ta.crossover(macd, 0)
bear0X = ta.crossunder(macd, 0)

if bullSigX
    table.cell(conditions, 0, 0, str.tostring('Signal Cross'), bgcolor=color.green)
if bearSigX
    table.cell(conditions, 0, 0, str.tostring('Signal Cross'), bgcolor=color.red)
if ta.change(source) > 0 and ta.change(macd) < 0
    table.cell(conditions, 0, 2, str.tostring('Divergence'), bgcolor=color.red)
else if ta.change(source) < 0 and ta.change(macd) > 0
    table.cell(conditions, 0, 2, str.tostring('Divergence'), bgcolor=color.green)
else
    table.clear(conditions, 0, 2)

