MACD Area
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ©algotraderdev

// @version=5
indicator('MACD Area', explicit_plot_zorder = true)

float SRC = input.source(close, 'Source')
int FAST_LEN = input.int(12, 'Fast Length', minval = 1)
int SLOW_LEN = input.int(26, 'Slow Length', minval = 1)
int SIGNAL_LEN = input.int(9, 'Signal Length', minval = 1)
bool MACD_DISPLAY = input.bool(true, 'MACD Line', group = 'Lines', inline = 'MACD')
color MACD_COLOR = input.color(#2962ff, '', group = 'Lines', inline = 'MACD')
bool SIGNAL_DISPLAY = input.bool(true, 'Signal Line', group = 'Lines', inline = 'Signal')
color SIGNAL_COLOR = input.color(#ff6d00, '', group = 'Lines', inline = 'Signal')
bool HIST_DISPLAY = input.bool(true, 'Display', group = 'Histogram')
color ABOVE_GROW_COLOR = input.color(#26a69a, 'Above Zero Grow', group = 'Histogram', inline = 'Above')
color ABOVE_FALL_COLOR = input.color(#b2dfdb, 'Fall', group = 'Histogram', inline = 'Above')
color BELOW_GROW_COLOR = input.color(#ffcdd2, 'Below Zero Grow', group = 'Histogram', inline = 'Below')
color BELOW_FALL_COLOR = input.color(#ff5252, 'Fall', group = 'Histogram', inline = 'Below')
bool AREA_DISPLAY = input.bool(true, 'Display Histogram', group = 'Area')
bool AREA_LABEL_DISPLAY = input.bool(true, 'Display Label', group = 'Area')
color ABOVE_AREA_COLOR = input.color(#00bcd455, 'Above Zero', group = 'Area')
color BELOW_AREA_COLOR = input.color(#e91e6355, 'Below Zero', group = 'Area')
color ABOVE_AREA_LABEL_COLOR = color.new(ABOVE_AREA_COLOR, 0.8)
color BELOW_AREA_LABEL_COLOR = color.new(BELOW_AREA_COLOR, 0.8)


// Calculations.

[macd, signal, hist] = ta.macd(SRC, FAST_LEN, SLOW_LEN, SIGNAL_LEN)

float area = 0
if ta.change(math.sign(hist))
    area := hist
else
    area := area[1] + hist

// Plot the lines and histograms.

color areaColor = area >= 0 ? ABOVE_AREA_COLOR : BELOW_AREA_COLOR
color histColor = if hist >= 0
    hist[1] < hist ? ABOVE_GROW_COLOR : ABOVE_FALL_COLOR
else
    hist[1] < hist ? BELOW_GROW_COLOR : BELOW_FALL_COLOR

hline(0, 'Zero Line', color = #777777)
plot(AREA_DISPLAY ? area : na, 'Area Histogram', color = areaColor, style = plot.style_columns)
plot(HIST_DISPLAY ? hist : na, 'Histogram', color = histColor, style=plot.style_columns)
plot(MACD_DISPLAY ? macd : na, 'MACD', color = MACD_COLOR)
plot(SIGNAL_DISPLAY ? signal : na, 'Signal', color = SIGNAL_COLOR)

// Create a label to display cumulative area.

string areaStr = str.format('{0,number,#.#}', area)

newLabel() =>
    label.new(
      x = bar_index,
      y = area,
      text = areaStr,
      textcolor = area >= 0 ? ABOVE_AREA_LABEL_COLOR : BELOW_AREA_LABEL_COLOR,
      color = #00000000,
      style = area >= 0 ? label.style_label_down : label.style_label_up)

var label areaLabel = newLabel()
if ta.change(math.sign(area)) and not na(area[1])
    areaLabel := newLabel()
else
    areaLabel.set_xy(bar_index, area)
    areaLabel.set_text(areaStr)