Indicator · Pine Script v6 · Own pane

Moving Average Convergence Divergence (MACD)

by mihakralj

The MACD indicator calculates the difference between two exponential moving averages with fast and slow periods to identify momentum shifts in the market.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code74
Settings4inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

74 lines of Pine Script v6 from lib/momentum/macd/macd.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

macd.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Moving Average Convergence Divergence (MACD)", "MACD", overlay=false)

//@function Calculates MACD with fast and slow EMAs and signal line
//@param src Source series to calculate MACD from
//@param fast_length Period for fast EMA
//@param slow_length Period for slow EMA
//@param signal_length Period for signal line EMA
//@returns Tuple [macd, signal, histogram] values
//@optimized for performance and dirty data with embedded EMA calculations
macd(series float src, simple int fast_length, simple int slow_length, simple int signal_length) =>
    if fast_length <= 0 or slow_length <= 0 or signal_length <= 0
        runtime.error("All periods must be greater than 0")
    if fast_length >= slow_length
        runtime.error("Fast length must be less than slow length")
    float alpha_fast = 2.0 / (fast_length + 1)
    float alpha_slow = 2.0 / (slow_length + 1)
    float alpha_signal = 2.0 / (signal_length + 1)
    float beta_fast = 1.0 - alpha_fast
    float beta_slow = 1.0 - alpha_slow
    float beta_signal = 1.0 - alpha_signal
    var bool warmup = true
    var float e_fast = 1.0
    var float e_slow = 1.0
    var float e_signal = 1.0
    var float ema_fast = 0.0
    var float ema_slow = 0.0
    var float ema_signal = 0.0
    var float result_fast = src
    var float result_slow = src
    var float result_signal = 0.0
    ema_fast := alpha_fast * (src - ema_fast) + ema_fast
    ema_slow := alpha_slow * (src - ema_slow) + ema_slow
    if warmup
        e_fast *= beta_fast
        e_slow *= beta_slow
        e_signal *= beta_signal
        float c_fast = 1.0 / (1.0 - e_fast)
        float c_slow = 1.0 / (1.0 - e_slow)
        float c_signal = 1.0 / (1.0 - e_signal)
        result_fast := c_fast * ema_fast
        result_slow := c_slow * ema_slow
        float macd_line = result_fast - result_slow
        ema_signal := alpha_signal * (macd_line - ema_signal) + ema_signal
        result_signal := c_signal * ema_signal
        warmup := e_fast > 1e-10 or e_slow > 1e-10 or e_signal > 1e-10
    else
        result_fast := ema_fast
        result_slow := ema_slow
        float macd_line = result_fast - result_slow
        ema_signal := alpha_signal * (macd_line - ema_signal) + ema_signal
        result_signal := ema_signal
    float macd_line = result_fast - result_slow
    float histogram = macd_line - result_signal
    [macd_line, result_signal, histogram]

// ---------- Main loop ----------

// Inputs
i_fast = input.int(12, "Fast Length", minval=1)
i_slow = input.int(26, "Slow Length", minval=2)
i_signal = input.int(9, "Signal Length", minval=1)
i_source = input.source(close, "Source")

// Calculation
[macd_line, signal_line, histogram] = macd(i_source, i_fast, i_slow, i_signal)

// Plot
hline(0, "Zero Line", color=color.gray)
plot(histogram, "Histogram", style=plot.style_columns, color=histogram >= 0 ? (histogram[1] < histogram ? color.green : color.green) : (histogram[1] < histogram ? color.red : color.red))
plot(macd_line, "MACD", color=color.blue, linewidth=2)
plot(signal_line, "Signal", color=color.red, linewidth=2)

Overview

Moving Average Convergence Divergence (MACD) plots the MACD line, signal line, and histogram bars in a separate pane below the price chart. The histogram bars turn green when positive and red when negative, signaling potential trend changes when crossing the zero line. Main settings allow customization of fast length, slow length, signal length, and data source. This momentum oscillator helps traders spot crossovers and divergences but may lag in rapidly changing markets.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Oscillators & momentum, Moving averages

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Fast Lengthint12i_fast
Slow Lengthint26i_slow
Signal Lengthint9i_signal
Sourcesourceclosei_source
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

948 stars

The Derivative Oscillator calculates a double-exponentially smoothed Relative Strength Index (RSI) and subtracts its Simple Moving Average (SMA) to form the main oscillator line. A secondary signal line is plotted using an SMA of the main oscillator values. Th

Indicator v4 Oscillators & momentumMoving averages
Updated 10 days ago · GPL-3.0 GitHub repository of Derivative Oscillator

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

MACD

by Alorse
330 stars

This indicator calculates and plots the standard Moving Average Convergence Divergence oscillator in a separate pane. It computes the difference between a fast and slow moving average, derives a signal line through smoothing, and plots a histogram representing

Indicator v4 Oscillators & momentumMoving averages
Updated 2 months ago · None stated GitHub repository of MACD

MACD-V

by harryguiacorn
219 stars

MACD-V is a volatility-normalized momentum indicator based on research by Alex Spiroglou. It calculates the standard MACD histogram and normalizes it by dividing by the Average True Range (ATR). Plotted in a separate pane as a colored histogram, it includes us

Indicator v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of MACD-V
218 stars

Multi-Timeframe Analysis Suite calculates trend direction and momentum conditions across five user-selected timeframes using moving averages, RSI, and Stochastic oscillators. It evaluates moving average slope and oscillator levels to compute trend alignment, m

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe Analysis Suite

KamaFama

by Mastaaa1987
141 stars

KamaFama is an indicator that translates a Freqtrade trading strategy into Pine Script for visualization. It combines Kaufman Adaptive Moving Average (KAMA), MAMA/FAMA calculations derived via Hilbert Transform, Williams %R, and correlation trend filters to ev

Indicator v6 Moving averagesOscillators & momentum
Updated 6 weeks ago · MIT GitHub repository of KamaFama

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers