Concept 25 / 52·Momentum·Unbounded oscillators
‹ Keltner ChannelsMarket Structure ›

MACD in Pine Script

moving average convergence divergence · MACD histogram · MACD 12 26 9 · signal line cross

The gap between a 12 and a 26-period EMA, with a 9-period EMA of that gap as the signal line and the difference between the two drawn as a histogram.

Reads best on: Trending markets on daily and 4-hour charts: stocks, indices and major crypto pairs. In ranges it whipsaws, so filter by the side of zero or by a higher timeframe.
On this page: the Pine v6 script, checked, drawn on real NVDA bars. Backtest it free, costs charged, every trade on the chart.
Backtest results: MACD strategy: SPY, QQQ and more since 2016, costs charged, every trade listed.
01

Definition

MACD, moving average convergence divergence, is an unbounded momentum oscillator built from two exponential moving averages. The MACD line is the fast EMA minus the slow EMA, so it is positive while the fast average is above the slow one and grows as they pull apart. A shorter EMA of the MACD line is the signal line, and the histogram is the MACD line minus the signal line. Because the line is measured in price units and nothing caps it, MACD belongs with CCI and rate of change rather than with RSI and the stochastic.

MACD measures the speed at which the two averages are separating, which is close to the acceleration of the trend. A rising MACD line above zero says the fast average is pulling away upward from the slow one; a falling line above zero says the trend is still up but is slowing. The signal line turns that slope into crosses, and the histogram shows how far the MACD line has run from its own average. The histogram therefore turns before the lines cross, which is why traders watch its bars shrink towards zero as the earliest warning.

Gerald Appel developed MACD in the late 1970s with 12, 26 and 9 as the lengths, chosen for daily stock charts, and those numbers remain the default everywhere. Thomas Aspray added the histogram in 1986. Faster sets such as 5, 35, 5 or 8, 17, 9 appear in shorter-term work, and some traders run 19, 39, 9 on weekly charts. The lengths are EMA lengths, so a 26-period EMA weights price over far more than 26 bars, and the indicator inherits the lag of the averages it is built from.

On the chart the two lines cross a few times a month on daily bars, and most crosses happen near the zero line in ranges, where they whipsaw. The strong crosses are the ones that come after the histogram has built to an extreme and then contracted for several bars. Crosses of the zero line lag the signal crosses and mark the point where the 12 EMA crosses the 26 EMA on the price chart. The library's indicator marks Long on the MACD line crossing above the signal and Short on the cross below. It colours the histogram by side and by whether each bar is growing or shrinking.

02

Reading the chart

Read the histogram for acceleration, the signal cross for timing, and the zero line for the trend, in that order.

  1. Add a 12, 26, 9 MACD in a pane. Identify the three parts, the MACD line, the signal line and the histogram, and check which side of zero the MACD line is on before reading any cross.
  2. Read the histogram first. Bars growing away from zero mean the trend is accelerating; bars shrinking towards zero mean it is slowing, and a shrinking histogram usually precedes a line cross by a few bars.
  3. Watch the signal cross. The MACD line crossing above the signal is the classic long, the cross below the short; the library's script marks these as Long and Short on confirmed bars.
  4. Weight the cross by its position. A cross far below zero after a long decline is a bottom-fishing read. A cross just above zero in a range is usually noise, and a cross above zero after a pullback in an uptrend is a continuation.
  5. Note the zero-line cross separately. It confirms that the fast EMA has crossed the slow one on the price chart, which is a slower, trend-defining event rather than a timing signal.
  6. Compare the peaks of the histogram and the MACD line with the peaks in price. A higher price high with a lower MACD peak is a bearish divergence and says the second push had less acceleration behind it.
03

The maths

MACD is the difference between two EMAs, the signal line an EMA of that difference, and the histogram the gap between the two.

EMAn(x)t=α xt+(1−α) EMAn(x)t−1\mathrm{EMA}_n(x)_t = \alpha \, x_t + (1 - \alpha) \, \mathrm{EMA}_n(x)_{t-1}
α=2n+1\alpha = \frac{2}{n + 1}
MACDt=EMA12(C)t−EMA26(C)t\mathrm{MACD}_t = \mathrm{EMA}_{12}(C)_t - \mathrm{EMA}_{26}(C)_t
Signalt=EMA9(MACD)t\mathrm{Signal}_t = \mathrm{EMA}_{9}(\mathrm{MACD})_t
Histt=MACDt−Signalt\mathrm{Hist}_t = \mathrm{MACD}_t - \mathrm{Signal}_t
xtx_tthe series being averaged, at bar t
EMAn(x)t\mathrm{EMA}_n(x)_tthe exponential moving average of x with length n at bar t
α\alphathe EMA smoothing factor for length n
nnan EMA length: 12 and 26 for the two price averages, 9 for the signal
CCthe close series
MACDt\mathrm{MACD}_tthe MACD line at bar t, in price units
Signalt\mathrm{Signal}_tthe signal line at bar t
Histt\mathrm{Hist}_tthe histogram at bar t

The lengths are EMA lengths, so each average weights every earlier bar with decaying weight; a 26-period EMA is not the average of 26 bars.

Because the MACD line is in price units, its scale differs between a low-priced stock and an index in the thousands; compare shapes across markets, not values. Dividing by the slow EMA gives a percentage version.

The histogram is the MACD line minus the signal line, not the MACD line itself; some charting packages plot the MACD line as columns, which is a different picture.

The signal cross and the zero cross are different events: the signal cross happens when the MACD line turns through its own average, the zero cross when the two price EMAs cross.

04

Inputs that matter

InputTypicalWhat changing it does
Fast length12Shorter fast lengths make the MACD line respond sooner and cross the signal more often; longer ones smooth it and move the crosses later.
Slow length26A longer slow length widens the gap the line can reach in a trend and slows the zero crosses; a shorter one keeps the line closer to zero.
Signal length9Shorter signal lengths give earlier crosses with more whipsaws; longer ones wait for a sustained turn before crossing.
Stop and target (strategy)2 ATR stop, 3 ATR targetWider stops survive more of the noise around a cross and lower the count of trades that end at the stop; a target of 0 leaves the exit to the opposite cross.
05

In practice

  • As a trend-following cross: the rule goes long on the MACD line crossing above the signal and short on the cross below. The library's indicator marks these as Long and Short, and its strategy trades them with an ATR stop and target on every entry.
  • As an acceleration read: watch the histogram grow and shrink. A trade in the direction of a growing histogram has momentum behind it; shrinking bars are where exit rules tighten stops before the cross arrives.
  • As a trend filter for other tools: the sign of the MACD line tells you which of the two EMAs is on top. Requiring MACD above zero before a long entry keeps other signals on the right side of the trend.
  • As a filtered cross: the filter keeps only the signal crosses that happen on the far side of zero, going long on crosses below zero after a fall and short on crosses above zero after a rise. That removes most of the range whipsaws.
  • As a divergence tool: a higher price high with a lower MACD or histogram peak marks a push with less acceleration, and is a common warning before a trend's last leg fails.
  • As a multi-timeframe frame: a weekly MACD above zero and rising sets the direction, and daily signal crosses in that direction become the entries. A shrinking weekly histogram switches the rule off.
06

Where it goes wrong

  • Trading every signal cross. Near the zero line in a range the lines cross constantly; require the histogram to have built to an extreme first, or filter by the side of zero.
  • Comparing MACD values across markets. The line is in price units, so a MACD of 2 on one instrument and 2 on another mean nothing alike; compare the shape or use a percentage version.
  • Reading the zero cross as the timing signal. It is the 12 and 26 EMA cross on the price chart, and it confirms a trend long after the signal cross flagged it.
  • Forgetting the lag. Two EMAs and a third on top respond to a turn several bars late; in fast reversals the cross prints after much of the move.
07

Compared with

Moving Average Crossover. A 12 and 26 EMA crossover on the price chart fires exactly when MACD crosses zero. MACD adds two things the price chart cannot show: the distance between the averages as a line, and its own signal line, which gives an earlier cross while the averages are still converging.

RSI. RSI is bounded and saturates in a trend, reading overbought while MACD keeps rising. MACD is unbounded and reads acceleration in price units. Use MACD to hold a trend and RSI to time the extremes inside a range; their divergences from price ask different questions and are worth reading together.

Rate of Change. Rate of change compares today's close with the close n bars ago and is the plain speed of price. MACD compares two smoothed averages and adds a signal line. ROC is faster and rougher; MACD is smoother, later and gives a built-in cross signal.

Moving Average Slope. A slope indicator measures how fast one average is rising or falling; MACD measures how fast two averages are separating, which is closer to acceleration. Both go positive in an uptrend, but the slope stays positive while a trend coasts and MACD turns down as soon as it slows.

08

Build it in Quant

Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.

Backtest MACD as a strategy
Costs and slippage included; every version stays selectable.
09

Questions

  • What do 12, 26 and 9 mean?

    12 and 26 are the lengths of the two EMAs whose difference is the MACD line, and 9 is the length of the EMA of the MACD line that forms the signal. Appel chose them for daily stock charts. Shorter sets such as 5, 35, 5 or 8, 17, 9 make the line faster; the ratio between fast and slow matters more than the exact numbers.

  • Is the histogram the MACD line?

    No. The histogram is the MACD line minus the signal line, so it shows how far the line has run from its own average. It crosses zero exactly when the two lines cross, and it turns before that cross, which is why traders watch it as the earliest read. Some platforms draw the MACD line as columns instead; check the labels.

  • Why does MACD give so many false crosses?

    Because in a range the two EMAs stay close, the MACD line hovers near zero and the signal line sits on top of it, so every wobble is a cross. The fix is to filter: keep only crosses that come after the histogram has built up and contracted, only crosses on the far side of zero, or only crosses in the direction of a higher-timeframe trend.

  • What does the library's MACD strategy do?

    It enters long when the MACD line crosses above the signal and short on the cross below, using 12, 26 and 9, and closes any opposite position on the new cross. Every entry gets a stop 2 ATR away and a target 3 ATR away, both fixed at the entry bar, with a 14-period ATR. Longs and shorts can be switched off separately, and orders fill on the next bar.

  • Can MACD be used for divergence?

    Yes, and it is one of its best uses. Compare the peaks of the MACD line or the histogram with the peaks in price. A higher price high with a lower MACD peak says the second push had less acceleration; a lower price low with a higher MACD trough is the bullish version. Wait for a signal cross to confirm rather than trading the divergence alone.

  • Does MACD work on intraday charts?

    Yes, with the same lengths read in bars rather than days. A 12, 26, 9 MACD on 5-minute bars describes about two hours of movement and crosses many times a session. Intraday traders usually pair it with a higher-timeframe MACD or a session VWAP for direction and use the intraday crosses only for timing.