Edgoro
Momentum indicator

MACD indicator: how it works, settings and Pine Script v6 code

The MACD line, signal line and histogram in plain words, how traders read crosses and divergence, sensible settings, and a free MACD script for TradingView.

What it measures

MACD measures the gap between a fast and a slow exponential moving average. When the fast average pulls away above the slow one, upward momentum is building; when the gap narrows, momentum is fading, even if price is still rising.

It is really three lines in one indicator: the MACD line (the gap itself), a signal line (a smoothed copy of the MACD line) and a histogram (the distance between the two). Gerald Appel developed it in the late 1970s; the histogram was added later.

The formula in words

  1. Compute a 12-period and a 26-period exponential moving average of the close.
  2. MACD line = 12-period EMA − 26-period EMA. It is positive when the fast average is above the slow one.
  3. Signal line = 9-period EMA of the MACD line.
  4. Histogram = MACD line − signal line.

Because the values are price differences, MACD is in the instrument's price units. A MACD of 2.5 on an index and 0.0008 on a currency pair can describe similar momentum. That also means you can't compare MACD levels across symbols, or set fixed thresholds that work everywhere.

How traders read it

  • Signal-line crosses. MACD crossing above its signal line is read as momentum turning up; crossing below, turning down. These are frequent and lag price, so many traders only take them in the direction of a higher-timeframe trend.
  • Zero-line crosses. MACD crossing zero is the same event as the 12 EMA crossing the 26 EMA. It is slower and is used as a trend filter more than as an entry.
  • The histogram. Shrinking bars mean the MACD line is converging on the signal line: momentum is slowing before any cross happens. Some traders watch for the first shorter bar after a run of growing ones.
  • Divergence. Price makes a new high while MACD makes a lower high. As with RSI, it describes weakening momentum and needs a separate trigger.

Common settings

SettingTypical valueNotes
Fast EMA12Shorter makes MACD more sensitive.
Slow EMA26Must be longer than the fast EMA.
Signal9Shorter gives earlier, noisier crosses.
Faster variants5 / 35 / 5, 8 / 17 / 9Seen in intraday trading; test before you adopt them.

The defaults were designed for daily charts. They work on any timeframe, but the meaning of "12 bars" changes with it.

Pine Script v6 code

The complete, self-contained script is below. Copy it into a new indicator in TradingView's Pine Editor, or download the .pine file.

Pine Script v6
//@version=6
indicator("MACD with histogram shading", shorttitle = "MACD")

src     = input.source(close, "Source")
fastLen = input.int(12, "Fast EMA", minval = 1)
slowLen = input.int(26, "Slow EMA", minval = 2)
sigLen  = input.int(9, "Signal smoothing", minval = 1)

[macdLine, signalLine, hist] = ta.macd(src, fastLen, slowLen, sigLen)

// Strong colour while the histogram grows, faded while it shrinks.
histColor = hist >= 0 ? (hist > hist[1] ? color.new(color.teal, 0) : color.new(color.teal, 55)) : (hist < hist[1] ? color.new(color.red, 0) : color.new(color.red, 55))

plot(hist, "Histogram", color = histColor, style = plot.style_columns)
plot(macdLine, "MACD", color = color.new(color.blue, 0), linewidth = 2)
plot(signalLine, "Signal", color = color.new(color.orange, 0))
hline(0, "Zero", color = color.new(color.gray, 50))

bullCross = ta.crossover(macdLine, signalLine)
bearCross = ta.crossunder(macdLine, signalLine)
zeroUp    = ta.crossover(macdLine, 0)
zeroDown  = ta.crossunder(macdLine, 0)

plotshape(bullCross, "Bullish cross", shape.circle, location.bottom, color.new(color.teal, 0), size = size.tiny)
plotshape(bearCross, "Bearish cross", shape.circle, location.top, color.new(color.red, 0), size = size.tiny)

alertcondition(bullCross, "MACD bullish cross", "MACD crossed above its signal line on {{ticker}} ({{interval}})")
alertcondition(bearCross, "MACD bearish cross", "MACD crossed below its signal line on {{ticker}} ({{interval}})")
alertcondition(zeroUp, "MACD above zero", "MACD crossed above zero on {{ticker}} ({{interval}})")
alertcondition(zeroDown, "MACD below zero", "MACD crossed below zero on {{ticker}} ({{interval}})")

The histogram is drawn as columns with four shades: solid when it is growing, faded when it is shrinking, which makes slowing momentum visible before a cross. Dots mark signal-line crosses, and four alert conditions cover signal-line and zero-line crosses in both directions.

All three lengths are inputs. If you change them, keep the fast length below the slow one.

Add it to your chart

  1. Open any chart on TradingView and open the Pine Editor.
  2. Create a new indicator, delete the template code and paste the script.
  3. Click Save, then Add to chart. Change lengths and levels from the indicator's settings.

Stuck on an error? See how to add a Pine Script indicator to TradingView.

Pitfalls

  • Taking every cross. Signal-line crosses are frequent in sideways markets. A trend filter (price above a long moving average, or the higher-timeframe MACD above zero) cuts many of them.
  • Comparing levels across symbols. MACD is in price units, so "MACD above 1" means nothing in general. Compare MACD with its own history on the same symbol.
  • Forgetting the lag. MACD is built from moving averages of moving averages. By the time a cross confirms, a good part of the move can be over.
  • Live-bar crosses. As with any indicator, a cross on the unfinished bar can disappear. Use once-per-bar-close alerts.

The script is an educational example: test it on your own markets before relying on it. Indicators describe the past; they don't predict the future. Trading involves substantial risk of loss and is not suitable for every investor. Edgoro is a software tool, not a broker or financial adviser: nothing it produces is investment advice, and past or backtested performance does not guarantee future results.

Make it yours with Edgoro

Describe the change in plain English and Edgoro writes the Pine Script v6 for you, ready to paste. For example:

“Plot MACD 12/26/9 and alert on a bullish signal-line cross only when the daily close is above the daily 50 EMA, without repainting.”

Build your MACD indicator