Indicator · Pine Script v6 · Own pane

MACD

by SiegerTerpstra· code credited to sajjetti

This indicator calculates and plots the Moving Average Convergence Divergence (MACD) line, signal line, and histogram in a separate pane.

View on GitHub

GitHub stars5on the repository
Pine versionv6current
Lines of code174
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update9 months ago14 Jan 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

174 lines of Pine Script v6 from 4 - MACD (v6).pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

4 - MACD (v6).pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sajjetti

//@version=6

//-------------------------------------

// Release:                     2020-08-05
// Update:                      2025-12-29
// Author:                      sajjetti
// Email:                       contact@sajjetti.ai
// Website:                     sajjetti.ai
// Profile:                     https://www.tradingview.com/u/stmd/
// Pineversion:                 6
// Filename:                    4 - MACD (v6).pine

//-------------------------------------
// PURPOSE
// Moving Average Convergence Divergence (MACD) - a trend-following momentum
// indicator showing the relationship between two EMAs. Developed by Gerald Appel.

//-------------------------------------
// FEATURES
// - Multi-timeframe support via Indicator Timeframe input
// - MACD line (fast EMA - slow EMA)
// - Signal line (EMA of MACD)
// - Histogram (MACD - Signal)
// - Separate smoothing for MACD and Signal
// - Offset parameter for historical analysis
// - Dynamic colors for all components

//-------------------------------------
// NOTES
// - Default settings: 12/26/9 (fast/slow/signal)
// - MACD above Signal = bullish momentum
// - MACD below Signal = bearish momentum
// - Histogram shows momentum strength
// - Zero line crossovers indicate trend changes
// - Divergence between price and MACD signals reversals

//-------------------------------------
// INDICATOR PARAMETERS

vVersion                        = "V2.0"
vPineVersion                    = "ps6"
vTitle                          = "Moving Average Convergence Divergence"
vShort                          = "MACD"
vOverlay                        = false
vPrecision                      = 0

indicator( title = vTitle+" ["+vVersion+"|"+vPineVersion+"]", shorttitle = vShort+" ["+vVersion+"|"+vPineVersion+"]", overlay = vOverlay, precision = vPrecision )

//-------------------------------------
// INPUTS

var groupMacd                   = "MACD (Standard: close, 12, 26, 9, 1, 1)"

vTimeframe                      = input.timeframe( defval = "", title = "Indicator Timeframe" )
vSource                         = input.source( defval = close, title = "Source", group = groupMacd )
vFastLength                     = input.int( defval = 12, minval = 1, maxval = 1024, title = "Fast Length", group = groupMacd )
vSlowLength                     = input.int( defval = 26, minval = 1, maxval = 1024, title = "Slow Length", group = groupMacd )
vSignalLength                   = input.int( defval = 9, minval = 1, maxval = 1024, title = "Signal Length", group = groupMacd )
vSmoothMacD                     = input.int( defval = 1, minval = 1, maxval = 1024, title = "Smooth MacD", group = groupMacd )
vSmoothSignal                   = input.int( defval = 1, minval = 1, maxval = 1024, title = "Smooth Signal", group = groupMacd )
vOffSet                         = input.int( defval = 0, minval = 0, maxval = 1024, title = "Offset", group = groupMacd )

//-------------------------------------
// COLORS

cBullish                        = #26A69A
cBearish                        = #EF5350
cBullishLight                   = #B2DFDB
cBearishLight                   = #FFCDD2
cSignal                         = #999999
cMedian                         = #666666

//-------------------------------------
// FUNCTIONS

// @function    Simple Moving Average
// @param       n (int) Offset for lookback starting point
// @param       s (series float) Source data
// @param       le (int) Length of the averaging period
// @returns     (float) Average value over the specified period
fMa( n, s, le ) =>
    r = float( 0 )
    for i = n + 0 to ( n + ( le - 1 ) )
        r := ( r + s[ i ] )
    a = r / le
    a

// @function    Exponential Moving Average with MA seeding
// @param       n (int) Offset for source indexing
// @param       s (series float) Source data
// @param       le (int) Length for EMA calculation
// @returns     (float) EMA value with persistent state
fEma( n, s, le ) =>
    ma = fMa( n, s, le )
    var float r = na
    r := na( r[ 1 ] ) ? ma : ( r[ 1 ] + ( 2 / ( le + 1 ) ) * ( s[ n ] - r[ 1 ] ) )
    r

// @function    Calculate MACD line (fast EMA - slow EMA)
// @param       n (int) Offset for source indexing
// @param       s (series float) Source data
// @param       lf (int) Fast EMA length
// @param       ls (int) Slow EMA length
// @returns     (float) MACD value
fMacd( n, s, lf, ls ) =>
    emaf = fEma( n, s, lf )
    emas = fEma( n, s, ls )
    macd = ( emaf - emas )
    macd

// @function    Calculate Signal line (EMA of MACD)
// @param       macd (series float) MACD line values
// @param       li (int) Signal EMA length
// @returns     (float) Signal line value
fSignal( macd, li ) =>
    signal = fEma( 0, macd, li )
    signal

// @function    Calculate Histogram (MACD - Signal)
// @param       macd (series float) MACD line value
// @param       signal (series float) Signal line value
// @returns     (float) Histogram value
fHistogram( macd, signal ) =>
    histogram = ( macd - signal )
    histogram

// @function    Calculate all MACD components for MTF support
// @returns     (tuple) MACD, Signal, and Histogram values
fCalcMacd() =>
    macdBase   = fMacd( vOffSet, vSource, vFastLength, vSlowLength )
    macd       = fMa( 0, macdBase, vSmoothMacD )
    signalBase = fSignal( macd, vSignalLength )
    signal     = fMa( 0, signalBase, vSmoothSignal )
    histogram  = fHistogram( macd, signal )
    [ macd, signal, histogram ]

// @function    Determines MACD line color based on direction
// @param       n (int) Offset for comparison
// @param       s (series float) Source data to evaluate
// @returns     (color) Green if rising, red if falling
fColorMacd( n, s ) =>
    r = ( s[ n + 1 ] < s[ n ] ) ? cBullish : cBearish
    r

// @function    Determines Histogram color based on position and direction
// @param       n (int) Offset for comparison
// @param       s (series float) Source data to evaluate
// @returns     (color) Green shades if positive, red shades if negative
fColorHistogram( n, s ) =>
    r = ( s[ n ] >= 0 ) ? ( s[ n + 1 ] < s[ n ] ) ? cBullish : cBullishLight : ( s[ n + 1 ] > s[ n ] ) ? cBearish : cBearishLight
    r

//-------------------------------------
// CALCULATIONS

[ vMacd, vSignal, vHistogram ] = if vTimeframe == ""
    fCalcMacd()
else
    request.security( syminfo.tickerid, vTimeframe, fCalcMacd() )

//-------------------------------------
// PLOT

vLineMedian                     = hline( 0, color = cMedian, linestyle = hline.style_dashed, linewidth = 1, title = "Median", editable = true )

vPlotMacd                       = plot( vMacd, style = plot.style_line, color = fColorMacd( 0, vMacd ), title = "MacD" )
vPlotSignal                     = plot( vSignal, style = plot.style_line, color = cSignal, title = "Signal" )
vPlotHistogram                  = plot( vHistogram, style = plot.style_columns, color = fColorHistogram( 0, vHistogram ), title = "Histogram" )

//-------------------------------------

Overview

MACD tracks trend direction and momentum shifts by calculating the difference between fast and slow exponential moving averages alongside a signal line. Configurable inputs allow adjustments to source data, fast, slow, and signal lengths, multi-timeframe resolution, horizontal plot offset, and individual smoothing periods for both the MACD and signal lines.

Details

Published by

SiegerTerpstra on GitHub

Code credit

sajjetti, as written in the script's header

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Oscillators & momentum, Trend

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

tradingviewindicatorindicators

Settings

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

SettingTypeDefaultVariable
Indicator TimeframetimeframevTimeframe
SourcesourceclosevSource
Fast Lengthint12vFastLength
Slow Lengthint26vSlowLength
Signal Lengthint9vSignalLength
Smooth MacDint1vSmoothMacD
Smooth Signalint1vSmoothSignal
Offsetint0vOffSet
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

Schaff Trend Cycle

by everget
948 stars

This indicator plots the Schaff Trend Cycle in a separate pane. It subtracts a slow exponential moving average from a fast one, applies a stochastic cycle twice, and smooths each result to form a 0–100 oscillator. Line color follows the slope, or the upper and

Indicator v4 Oscillators & momentumTrend
Updated 10 days ago · GPL-3.0 GitHub repository of Schaff Trend Cycle

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

[RS]Standardized Trend Map

by ricardosantos79
261 stars

Standardized Trend Map calculates series momentum relative to active price range across 40 distinct lookback periods ranging from 2 to 80 bars on an exponential moving average source. Each standardized calculation rounds to an integer values of -1, 0, or 1 to

Indicator v4 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of [RS]Standardized Trend Map

ADX Histogram

by harryguiacorn
219 stars

This indicator calculates and displays the Average Directional Index (ADX) as a column histogram in a separate pane. It evaluates market trend strength by calculating directional movement metrics based on specified smoothing and DI length inputs. When the ADX

Indicator v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ADX Histogram
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

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