Indicator · Pine Script v6 · Own pane

MACD

by rubbermetal· code credited to claygrace74

MACD is a standard moving average convergence divergence oscillator in a separate pane.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code88
Settings9inputs
LicenceMPL-2.0
Last update4 months ago10 Jun 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

88 lines of Pine Script v6 from MACD.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

MACD.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © claygrace74

//@version=6
indicator("MACD", overlay=false)

// ==================== MACD Settings ====================
var macd_group = "MACD Settings"
macdsrc       = input.source(close, "Source", group=macd_group)
macdfastlen   = input.int(12, "Fast Length", minval=1, group=macd_group)
macdslowlen   = input.int(26, "Slow Length", minval=1, group=macd_group)
macdsignallen = input.int(9, "Signal Smoothing", minval=1, maxval=50, group=macd_group)
sigType       = input.string("EMA", "Signal Line Type", options=["EMA", "SMA"], group=macd_group)

// ==================== Display Settings ====================
var disp_group = "Display Settings"
i_showCross      = input.bool(true, "Show MACD/Signal Cross", group=disp_group)
i_showZeroCross  = input.bool(true, "Show Zero-Line Cross", group=disp_group)
i_showDivergence = input.bool(false, "Show Divergence Signals", group=disp_group)
i_divLookback    = input.int(5, "Divergence Lookback", minval=3, group=disp_group)

// ==================================================================================
// Core Calculations
// ==================================================================================
fastavg    = ta.ema(macdsrc, macdfastlen)
slowavg    = ta.ema(macdsrc, macdslowlen)
macd       = fastavg - slowavg
macdsignal = sigType == "SMA" ? ta.sma(macd, macdsignallen) : ta.ema(macd, macdsignallen)
macdhist   = macd - macdsignal

// Cross detection
bullCross = ta.crossover(macd, macdsignal)   // MACD crosses above signal — bullish
bearCross = ta.crossunder(macd, macdsignal)  // MACD crosses below signal — bearish
zeroCrossUp   = ta.crossover(macd, 0)
zeroCrossDown = ta.crossunder(macd, 0)

// Histogram momentum — 4 states
histGrowBull   = macdhist >= 0 and macdhist > macdhist[1]  // Above zero, growing
histShrinkBull = macdhist >= 0 and macdhist <= macdhist[1] // Above zero, shrinking
histGrowBear   = macdhist < 0 and macdhist < macdhist[1]   // Below zero, growing (more negative)
histShrinkBear = macdhist < 0 and macdhist >= macdhist[1]  // Below zero, shrinking

histColor = histGrowBull ? color.rgb(0, 230, 64) : histShrinkBull ? color.rgb(0, 150, 40) : histGrowBear ? color.rgb(230, 30, 30) : color.rgb(150, 40, 40)

// Divergence detection
priceHigher  = high > ta.highest(high, i_divLookback)[1]
macdNotHigh  = macd < ta.highest(macd, i_divLookback)[1]
bearDiv      = priceHigher and macdNotHigh and macd > 0

priceLower   = low < ta.lowest(low, i_divLookback)[1]
macdNotLow   = macd > ta.lowest(macd, i_divLookback)[1]
bullDiv      = priceLower and macdNotLow and macd < 0

// ==================================================================================
// Plots
// ==================================================================================
hline(0, "Zero Line", color=color.new(#787B86, 50))

// Histogram — 4-color momentum
plot(macdhist, color=histColor, linewidth=1, style=plot.style_columns, title="Histogram")

// MACD and Signal lines
plot(macd,       color=color.rgb(44, 29, 255),    linewidth=2, title="MACD")
plot(macdsignal, color=color.rgb(255, 152, 36, 0), linewidth=1, title="Signal")

// MACD/Signal cross shapes
crossVal = bullCross or bearCross ? macdsignal : na
crossClr = bullCross ? color.green : color.red
plotshape(i_showCross and bullCross, style=shape.circle, location=location.absolute, color=color.green, size=size.tiny, title="Bull Cross")
plotshape(i_showCross and bearCross, style=shape.circle, location=location.absolute, color=color.red,   size=size.tiny, title="Bear Cross")

// Zero-line cross
plotshape(i_showZeroCross and zeroCrossUp,   style=shape.triangleup,   location=location.bottom, color=color.lime,   text="0+", textcolor=color.lime,   size=size.tiny, title="Zero Cross Up")
plotshape(i_showZeroCross and zeroCrossDown, style=shape.triangledown, location=location.top,    color=color.orange, text="0-", textcolor=color.orange, size=size.tiny, title="Zero Cross Down")

// Divergence
bgcolor(i_showDivergence and bearDiv ? color.new(color.orange, 85) : na, title="Bearish Divergence")
bgcolor(i_showDivergence and bullDiv ? color.new(color.teal, 85)   : na, title="Bullish Divergence")

// ==================================================================================
// Alert Conditions
// ==================================================================================
alertcondition(bullCross,     "MACD Bullish Cross",     "MACD crossed above signal line")
alertcondition(bearCross,     "MACD Bearish Cross",     "MACD crossed below signal line")
alertcondition(zeroCrossUp,   "MACD Above Zero",        "MACD crossed above zero line")
alertcondition(zeroCrossDown, "MACD Below Zero",        "MACD crossed below zero line")
alertcondition(bullDiv,       "Bullish Divergence",     "Price making new low but MACD is not")
alertcondition(bearDiv,       "Bearish Divergence",     "Price making new high but MACD is not")

Overview

MACD shows the MACD line, a signal line that can use EMA or SMA smoothing, and a histogram colored in four shades for rising and falling momentum above or below zero. Optional markers show MACD and signal crosses, zero line crosses, and a simple divergence check against recent highs and lows. Source and all lengths are adjustable.

Details

Published by

rubbermetal on GitHub

Code credit

claygrace74, as written in the script's header

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Oscillators & momentum, Divergence

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.

Settings

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

SettingTypeDefaultVariable
Sourcesourceclosemacdsrc
Fast Lengthint12macdfastlen
Slow Lengthint26macdslowlen
Signal Smoothingint9macdsignallen
Signal Line TypestringEMAsigType
Show MACD/Signal Crossbooltruei_showCross
Show Zero-Line Crossbooltruei_showZeroCross
Show Divergence Signalsboolfalsei_showDivergence
Divergence Lookbackint5i_divLookback
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

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator
330 stars

This indicator calculates the MACD oscillator from a configurable source with fast and slow lengths, then plots the histogram, MACD line, and signal line in a separate pane. It detects regular bullish divergences (price lower lows with oscillator higher lows),

Indicator v5 Oscillators & momentumDivergence
Updated 2 months ago · None stated GitHub repository of MACD + Divergences [Alorse]
218 stars

This indicator calculates the Relative Strength Index (RSI) across four user-selected timeframes and plots the results in a separate pane. It identifies regular bullish and bearish divergences between price pivot points and the primary timeframe RSI value. Add

Indicator v6 Oscillators & momentumDivergence
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe RSI with Divergence

Bubbles Indicator

by capissimo
114 stars

The Bubbles Indicator measures volatility squeezes and expansion bursts using Bollinger Bands combined with a sinusoid oscillator and RSI divergence. It processes price data through scaled Bollinger Bands to highlight volatility changes while confirming trend

Indicator v4 Volatility & bandsOscillators & momentum Repaints
Updated 1 year ago · None stated GitHub repository of Bubbles Indicator

RSI [SystemAlpha]

by iamc1oud
56 stars

This indicator plots a standard Relative Strength Index (RSI) in a separate pane alongside customizable overbought and oversold threshold levels with shaded fills. It identifies pivot highs and lows on the oscillator to detect regular and hidden bullish and be

Indicator v4 Oscillators & momentumDivergence Repaints
Updated 2 months ago · None stated GitHub repository of RSI [SystemAlpha]
55 stars

This indicator calculates a 14-period RSI from close and plots it in a separate pane with dotted overbought and dashed oversold lines at 70 and 30. It marks bullish divergence when a five-bar pivot low in price is lower than the price twenty bars earlier while

Indicator v6 Oscillators & momentumDivergence
Updated 6 months ago · Apache-2.0 GitHub repository of RSI Divergence Detector

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