MomentumPine Script v6

Moving Average Convergence Divergence Pine Script — Complete TradingView Guide

The Moving Average Convergence Divergence (MACD) is one of the most widely-used momentum indicators in TradingView, built into Pine Script v6 via ta.macd(source, fastLength, slowLength, signalLength). Developed by Gerald Appel in 1979, MACD measures the relationship between a 12-period EMA and a 26-period EMA, with a 9-period signal line smoothing the result. The indicator outputs three values — the MACD line, the signal line, and the histogram — making it a complete trend and momentum system in a single call. MACD Pine Script works across all asset classes including stocks, crypto, forex, and futures, and is most reliable on timeframes from 1-hour to daily charts. This guide covers the complete Pine Script v6 implementation using ta.macd(), all configurable parameters, three named MACD trading strategies with specific entry and exit conditions, and a five-step walkthrough for generating MACD scripts instantly with Pineify.

What Is the Moving Average Convergence Divergence?

The Moving Average Convergence Divergence (MACD) is a momentum-trend oscillator that measures the difference between two exponential moving averages, used to identify trend direction, signal momentum shifts, and generate crossover buy/sell signals. Unlike bounded oscillators such as RSI (which is capped at 0–100), the MACD has no fixed upper or lower boundary — its value scales with price volatility, making it useful across both low-volatility equities and high-volatility crypto assets.

MACD was developed by Gerald Appel in 1979 and first published in his newsletter Systems and Forecasts. Appel originally designed it as a buy/sell signal system for the stock market. In 1986, Thomas Aspray added the histogram component — the vertical bars representing the distance between the MACD line and the signal line — which significantly improved the indicator's ability to warn of upcoming crossovers before they occurred. Today MACD is one of the default indicators on TradingView and is used by millions of traders globally.

Core formula: MACD Line = EMA(close, 12) − EMA(close, 26). Signal Line = EMA(MACD Line, 9). Histogram = MACD Line − Signal Line. In this formula, EMA(close, 12) is the fast exponential moving average that reacts quickly to recent price changes, while EMA(close, 26) is the slow exponential moving average that represents the longer-term trend. When the fast EMA rises above the slow EMA, the MACD line is positive, which signals bullish momentum. When the MACD line crosses above the signal line (its own 9-period EMA), it generates a bullish crossover signal. In Pine Script v6, the call ta.macd(close, 12, 26, 9) returns all three values in a single destructured assignment.

MACD applies to all major liquid asset classes: stocks, crypto, forex, and futures. It performs best in trending markets and generates excessive false signals in sideways, low-volatility consolidation. The most reliable timeframes for MACD signals are 1-hour, 4-hour, and Daily charts — on shorter timeframes (1m, 5m) the signal-to-noise ratio drops significantly and faster MACD settings such as MACD(5, 13, 6) are recommended for day trading.

Best Markets

Stocks · Crypto · Forex · Futures

Best Timeframes

1H, 4H, Daily

Overlay

No — plots in a separate pane below price

MACD Pine Script Code Example

The code below implements the full MACD indicator in Pine Script v6 using ta.macd(close, 12, 26, 9), plotting the MACD line (blue), signal line (orange), and a color-coded histogram in a separate pane. To add it to TradingView, open the Pine Script editor with Alt+P, paste the code, and click Add to chart — the indicator automatically renders below the price chart.

Pine Script v6
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//@version=6
indicator(title="Moving Average Convergence Divergence", overlay=false, max_labels_count=500)

// MACD — calculates MACD line, signal line, and histogram
[p_ind_1_macd, p_ind_1_signal, p_ind_1_histogram] = ta.macd(close, 12, 26, 9)

// Zero line reference
hline(0, "MACD - Zero Line", color=color.new(#787B86, 50))

// Histogram: green when positive (bullish), red when negative (bearish)
plot(p_ind_1_histogram, title="MACD - Histogram", style=plot.style_columns,
     color=(p_ind_1_histogram >= 0
            ? (p_ind_1_histogram[1] < p_ind_1_histogram ? color.rgb(38, 166, 154, 0) : color.rgb(38, 166, 154, 70))
            : (p_ind_1_histogram[1] < p_ind_1_histogram ? color.rgb(255, 82, 82, 70)  : color.rgb(255, 82, 82, 0))))

// MACD line (blue) and Signal line (orange)
plot(p_ind_1_macd,   title="MACD - MACD",   color=color.rgb(41, 98, 255, 0),  linewidth=1)
plot(p_ind_1_signal, title="MACD - Signal", color=color.rgb(255, 109, 0, 0), linewidth=1)

Chart Preview

Moving Average Convergence Divergence indicator Pine Script code example in TradingView

MACD Parameters

ParameterDefault ValueDescriptionRecommended Range
sourcecloseThe price series to apply the EMA calculations to. Most commonly close, but can be hl2 or any numeric series.Any numeric series
fastLength12Period of the fast EMA. Controls how quickly the MACD line reacts to recent price changes. Lower values produce a more sensitive MACD line.5–20
slowLength26Period of the slow EMA. Sets the baseline trend reference. Must always be greater than fastLength or the MACD logic inverts.13–55
signalLength9Period of the signal EMA (smoothing applied to the MACD line). Controls how many crossovers are generated. Lower values = more signals; higher values = fewer, slower signals.5–14

Tuning Guide by Trading Style

  • Scalping / day trading (5m–15m): MACD(5, 13, 6) — faster settings, higher signal frequency, more noise
  • Standard day trading (1H): MACD(12, 26, 9) — the default; widely backtested across all asset classes
  • Swing trading (4H–Daily): MACD(8, 21, 5) or MACD(12, 26, 9) — reduces lag for multi-day holds
  • Position trading (Weekly): MACD(12, 26, 9) on weekly charts — signals are rare but highly reliable for macro trend changes

MACD Trading Strategies

The MACD is most effective as a momentum confirmation tool and crossover signal generator. Below are three concrete strategies with specific entry and exit conditions for use in TradingView.

Strategy 1 — MACD Signal Line Crossover (Classic Momentum)

Market environment: trending markets · Best timeframe: 1H, 4H, Daily

The MACD signal line crossover is Gerald Appel's original strategy. When the MACD line crosses above the signal line, it signals bullish momentum. Use ta.crossover(macdLine, signalLine) to detect it in Pine Script.

  1. Calculate MACD: [macd, signal, hist] = ta.macd(close, 12, 26, 9)
  2. Long entry: ta.crossover(macd, signal) — MACD line crosses above signal line
  3. Confirm signal occurs below the zero line (stronger signal; avoids chasing extended moves)
  4. Add ADX > 20 filter to avoid crossovers in sideways markets
  5. Exit: ta.crossunder(macd, signal) — MACD line crosses below signal line

Strategy 2 — MACD Zero-Line Cross + EMA 200 Trend Filter

Market environment: trending bull/bear markets · Best timeframe: Daily

When the MACD line crosses above the zero line, the fast EMA has crossed above the slow EMA, confirming a trend change. Pairing this with EMA 200 as a macro filter restricts entries to the dominant trend direction.

  1. Calculate MACD and trend filter: ema200 = ta.ema(close, 200)
  2. Condition 1 (trend): close > ema200 — only take long entries in bull territory
  3. Condition 2 (entry): ta.crossover(macd, 0) — MACD crosses above zero line
  4. Confirm histogram is positive and increasing for at least 2 consecutive bars
  5. Exit: MACD crosses below zero line or close falls below EMA 200

Strategy 3 — MACD Histogram Divergence + RSI Confirmation

Market environment: trend reversals · Best timeframe: 4H, Daily

MACD divergence occurs when price makes a new high but the MACD histogram makes a lower high, warning of weakening momentum before the crossover happens. Confirming with RSI(14) reduces false divergence signals significantly.

  1. Calculate MACD and RSI: rsi14 = ta.rsi(close, 14)
  2. Bearish divergence: price makes a higher high while the MACD histogram makes a lower high (momentum not confirming price)
  3. RSI confirmation: rsi14 is above 60 and declining — confirms momentum is weakening
  4. Short entry trigger: MACD line crosses below signal line after the divergence is confirmed
  5. Exit: MACD histogram turns positive for 2 consecutive bars or RSI recovers above 50

Disclaimer: The strategies above are for educational purposes only and do not constitute investment advice. Past performance does not guarantee future results. Always apply proper risk management and position sizing.

How to Generate the MACD Indicator in Pineify

  1. 1

    Open Pineify

    Go to pineify.app and sign in — a free account is sufficient to generate MACD indicators.

  2. 2

    Click "New Indicator"

    Select "Indicator" as the script type from the creation menu on the dashboard.

  3. 3

    Describe the MACD configuration you want

    Type a prompt such as: "Create a MACD indicator with fast length 12, slow length 26, and signal length 9. Show the MACD line, signal line, and color-coded histogram." Pineify's AI Coding Agent generates the complete Pine Script v6 code in seconds.

  4. 4

    Copy to TradingView

    Click "Copy to TradingView" to copy the generated code, then open the TradingView Pine Script editor (Alt+P), paste the code, and click "Add to chart". The MACD renders in a separate pane below the price chart automatically.

  5. 5

    Adjust the MACD lengths

    In the TradingView indicator settings panel, change the fast length, slow length, and signal length (e.g., to 5/13/6 for day trading) to match your trading style — no code editing required.

Frequently Asked Questions

Build Your MACD Indicator in Seconds

Skip the manual coding. Pineify's AI Coding Agent generates complete, ready-to-use Pine Script indicators — including MACD crossover and divergence strategies — instantly for free.

Try Pineify Free