Indicator · Pine Script v6 · Own pane

MACD = Moving Average Convergence Divergence

by piecioshka

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

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code94
Settings12inputs
LicenceMIT
Last update10 days ago18 Oct 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

94 lines of Pine Script v6 from indicators/oscillators/macd/macd.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

macd.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Piotr Kowalski "piecioshka"
// Docs (EN): https://github.com/piecioshka/tradingview-pine-scripts/blob/main/indicators/oscillators/macd/macd.md
// Docs (PL): https://github.com/piecioshka/tradingview-pine-scripts/blob/main/indicators/oscillators/macd/macd.pl.md

//@version=6
indicator('MACD = Moving Average Convergence Divergence', overlay=false, max_lines_count=100, max_labels_count=100)

// --- Color palette (single place for the theme) ---
cMacd   = color.rgb(56, 104, 174)   // MACD line
cSignal = color.rgb(215, 107, 52)   // signal line
cUp     = color.green               // rise / buy signal
cDn     = color.red                 // fall / sell signal
cMid    = color.gray                // zero line and neutral elements

// --- Inputs ---
gFast = 'Fast EMA (shorter)'
fastLen  = input.int(12, 'Length', minval=1, group=gFast, tooltip='Window of the faster average.')
fastType = input.string('EMA', 'Type', options=['SMA', 'EMA', 'WMA', 'VWMA', 'RMA'], group=gFast)

gSlow = 'Slow EMA (longer)'
slowLen  = input.int(26, 'Length', minval=1, group=gSlow, tooltip='Window of the slower average.')
slowType = input.string('EMA', 'Type', options=['SMA', 'EMA', 'WMA', 'VWMA', 'RMA'], group=gSlow)

gSig = 'Signal line'
sigLen  = input.int(9, 'Length', minval=1, group=gSig, tooltip='Smoothing of the MACD line = signal line.')
sigType = input.string('EMA', 'Type', options=['SMA', 'EMA', 'WMA', 'VWMA', 'RMA'], group=gSig)

gView = 'Display'
showHist    = input.bool(true,  'Histogram',                     group=gView, tooltip='Columns of the MACD − signal difference.')
showSignals = input.bool(true,  'Signals (markers on price)',    group=gView, tooltip='Markers on the price panel when MACD crosses the signal line: green below the candle on a cross up, red above the candle on a cross down. Shape and size in the Appearance group.')
showLabels  = input.bool(false, 'BUY CLOSE / BUY OPEN markers',  group=gView, tooltip='Markers on the MACD panel at crossings. Off by default.')
showTable   = input.bool(true,  'Status table',                  group=gView, tooltip='Small corner panel with values and trend.')

gA = 'Appearance'
shapeName = input.string('Triangle', 'Marker shape', options=['Triangle', 'Arrow', 'Label arrow', 'Circle', 'Diamond'], group=gA, tooltip='Triangle - solid triangle.\nArrow - small thin arrow.\nLabel arrow - arrow-shaped label bubble.\nCircle / Diamond - neutral dot markers.')
sizeName  = input.string('Small', 'Marker size', options=['Tiny', 'Small', 'Normal', 'Large'], group=gA)

// Markers as labels - the shape is picked from an input, which plotshape() cannot do (its style must be a constant).
upStyle    = shapeName == 'Arrow' ? label.style_arrowup : shapeName == 'Label arrow' ? label.style_label_up : shapeName == 'Circle' ? label.style_circle : shapeName == 'Diamond' ? label.style_diamond : label.style_triangleup
downStyle  = shapeName == 'Arrow' ? label.style_arrowdown : shapeName == 'Label arrow' ? label.style_label_down : shapeName == 'Circle' ? label.style_circle : shapeName == 'Diamond' ? label.style_diamond : label.style_triangledown
markerSize = sizeName == 'Tiny' ? size.tiny : sizeName == 'Normal' ? size.normal : sizeName == 'Large' ? size.large : size.small

// --- Calculations ---
maOf(src, len, kind) =>
    switch kind
        'SMA'  => ta.sma(src, len)
        'EMA'  => ta.ema(src, len)
        'WMA'  => ta.wma(src, len)
        'VWMA' => ta.vwma(src, len)
        'RMA'  => ta.rma(src, len)
        => ta.ema(src, len)

macd      = maOf(close, fastLen, fastType) - maOf(close, slowLen, slowType)
signal    = maOf(macd, sigLen, sigType)
histogram = macd - signal
crossUp   = ta.crossover(macd, signal)    // MACD crosses the signal line up -> bullish impulse
crossDn   = ta.crossunder(macd, signal)   // MACD crosses the signal line down -> bearish impulse

// --- Drawing (histogram below the lines) ---
histColor = histogram >= 0 ? (histogram > histogram[1] ? color.new(cUp, 50) : color.new(cUp, 80)) : (histogram < histogram[1] ? color.new(cDn, 50) : color.new(cDn, 80))
plot(showHist ? histogram : na, 'Histogram', color=histColor, linewidth=2, style=plot.style_columns)
plot(macd,   'MACD',   color=cMacd,   linewidth=2)
plot(signal, 'Signal', color=cSignal, linewidth=2, linestyle=plot.linestyle_dotted)
hline(0, 'Zero', color=cMid, linestyle=hline.style_dotted)

// --- Signals (compact markers + optional panel markers) ---
// Markers on the price panel: bullish cross = green below the candle, bearish = red above
if showSignals and crossUp
    label.new(bar_index, na, '', yloc=yloc.belowbar, style=upStyle, color=cUp, size=markerSize, force_overlay=true)
if showSignals and crossDn
    label.new(bar_index, na, '', yloc=yloc.abovebar, style=downStyle, color=cDn, size=markerSize, force_overlay=true)
// Markers on the MACD panel (off by default)
if showLabels and crossUp
    label.new(bar_index, macd, '', style=upStyle, color=cUp, size=markerSize)
if showLabels and crossDn
    label.new(bar_index, signal, '', style=downStyle, color=cDn, size=markerSize)

// --- Alerts ---
alertcondition(crossUp, 'MACD: cross up',   'MACD crossed the signal line up (bullish impulse)')
alertcondition(crossDn, 'MACD: cross down', 'MACD crossed the signal line down (bearish impulse)')

// --- Status table (top-right corner) ---
trend      = macd > signal ? 'Bullish' : macd < signal ? 'Bearish' : 'Neutral'
trendColor = macd > signal ? cUp : macd < signal ? cDn : cMid

var table infoTable = table.new(position.top_right, 2, 3, border_width=1, border_color=color.new(cMid, 70))
if showTable and barstate.islast
    table.cell(infoTable, 0, 0, 'MACD',   text_color=cMid,       text_size=size.small)
    table.cell(infoTable, 1, 0, str.tostring(macd, '#.###'),   text_color=color.white, text_size=size.small)
    table.cell(infoTable, 0, 1, 'Signal', text_color=cMid,       text_size=size.small)
    table.cell(infoTable, 1, 1, str.tostring(signal, '#.###'), text_color=color.white, text_size=size.small)
    table.cell(infoTable, 0, 2, 'Trend',  text_color=cMid,       text_size=size.small)
    table.cell(infoTable, 1, 2, trend,    text_color=trendColor, text_size=size.small)

Overview

MACD = Moving Average Convergence Divergence allows users to select from five moving average types (SMA, EMA, WMA, VWMA, or RMA) for the fast, slow, and signal calculations. The indicator can plot crossover markers directly on the price chart with customizable shapes and sizes, display labels on the MACD pane, and output a status table panel in the chart corner.

Details

Published by

piecioshka 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

pinescriptpinescript-indicatorspinescript-strategiestradingtradingview

Settings

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

SettingTypeDefaultVariable
Lengthint12fastLen
TypestringEMAfastType
Lengthint26slowLen
TypestringEMAslowType
Lengthint9sigLen
TypestringEMAsigType
HistogrambooltrueshowHist
Signals (markers on price)booltrueshowSignals
BUY CLOSE / BUY OPEN markersboolfalseshowLabels
Status tablebooltrueshowTable
Marker shapestringTriangleshapeName
Marker sizestringSmallsizeName
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