Strategy · Pine Script v4 · Own pane

MACD

by avatar-lavventura· code credited to lavventura

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

View on GitHub

GitHub stars2on the repository
Pine versionv4older, still runs
Lines of code48
Settings12inputs
LicenceNone statedfile: MPL-2.0
Last update7 months ago5 Mar 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 strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

48 lines of Pine Script v4 from pine/work/macd.pine, published under MPL-2.0 (file header). 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/
// © lavventura

//@version=4
strategy(title="MACD", shorttitle="MACD")
// Getting inputs
fast_length = input(title="Fast Length", type=input.integer, defval=12)
slow_length = input(title="Slow Length", type=input.integer, defval=26)
src = input(title="Source", type=input.source, defval=close)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="Simple MA (Oscillator)", type=input.bool, defval=false)
sma_signal = input(title="Simple MA (Signal Line)", type=input.bool, defval=false)
// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350
col_macd = #0094ff
col_signal = #ff6a00
// Calculating
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=0 )
plot(macd, title="MACD", color=col_macd, transp=0)
plot(signal, title="Signal", color=col_signal, transp=0)
// -----------------------------------------------------------------------------------------------------
hist_long = hist > 0
hist_short = hist < 0

fromYear = input(2020, "Backtest Start Year")
fromMonth = input(1, "Backtest Start Month")
fromDay = input(2, "Backtest Start Day")
testPeriodStart = timestamp(fromYear,fromMonth,fromDay,0,0)

thruYear = input(2021, "Backtest Stop Year")
thruMonth = input(12, "Backtest Stop Month")
thruDay = input(30, "Backtest Stop Day")
testPeriodStop = timestamp(thruYear,thruMonth,thruDay,0,0)

start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)  // backtest start window
finish    = timestamp(thruYear, thruMonth, thruDay, 23, 59)  // backtest finish window
window()  => time >= start and time <= finish ? true : false

strategy.entry("Long", strategy.long, when=window() and hist_long)
strategy.close("Long", when=window() and hist_short)

Overview

MACD enters a long position when the MACD histogram is above zero and closes the long position when the histogram drops below zero within a user-defined backtesting date range. Inputs allow customization of fast, slow, and signal lengths, along with toggling between exponential and simple moving averages. The strategy operates without a stop loss.

Details

Published by

avatar-lavventura on GitHub

Code credit

lavventura, as written in the script's header

Type

Strategy, Pine Script v4

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
Fast Lengthint12fast_length
Slow Lengthint26slow_length
Sourcesourceclosesrc
Signal Smoothingint9signal_length
Simple MA (Oscillator)boolfalsesma_source
Simple MA (Signal Line)boolfalsesma_signal
Backtest Start Yearint2020fromYear
Backtest Start Monthint1fromMonth
Backtest Start Dayint2fromDay
Backtest Stop Yearint2021thruYear
Backtest Stop Monthint12thruMonth
Backtest Stop Dayint30thruDay
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

330 stars

MACD + Divergences [Alorse] is a momentum strategy that calculates the MACD oscillator and identifies regular and hidden divergences using pivot high and low points. It filters trade signals with dual Exponential Moving Averages (EMA 150 and 600) to ensure tra

Strategy v4 Oscillators & momentumDivergence Repaints
Updated 2 months ago · None stated GitHub repository of MACD + Divergences [Alorse]

MACD Crossover (tutorial)

by pineforge-4pass
193 stars

This strategy calculates the Moving Average Convergence Divergence indicator and plots the MACD line, signal line, and histogram in a separate pane. It enters long positions when the MACD line crosses above the signal line and enters short positions when it cr

Strategy v6 Oscillators & momentumMoving averages
Updated 2 days ago · Apache-2.0 GitHub repository of MACD Crossover (tutorial)

8D Run

by hasnocool
106 stars

8D Run is a Pine Script momentum strategy inspired by Linda Bradford Raschke. It tracks consecutive price closes relative to a 5-period Simple Moving Average (SMA). When price remains above the SMA for 8 or more bars and then dips below it, the strategy enters

Strategy v5 Oscillators & momentumMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 8D Run

BTC Futures MACD

by iamrichardD
57 stars

This strategy plots a MACD oscillator in a separate pane and trades Bitcoin futures from zero-line and signal-line crosses. Optional early momentum signals, a volume filter, and a trend moving-average filter can confirm entries. It sizes positions as fixed con

Strategy v6 Oscillators & momentumMoving averages Repaints
Updated 1 year ago · Apache-2.0 GitHub repository of BTC Futures MACD
25 stars

This Pine Script strategy calculates Bayesian probabilities of price breaking up or down relative to Bollinger Bands and a Simple Moving Average. It plots these breakout and breakdown probability lines as oscillators in a separate pane. Long entries trigger wh

Strategy v4 Oscillators & momentumVolatility & bands
Updated 6 years ago · None stated GitHub repository of Bayesian BBSMA Oscillator Strategy

Greeffer BB Strategy

by SammyEnigma
18 stars

This strategy combines Bollinger Bands, Bollinger Band Width, and the Relative Strength Index (RSI) for mean-reversion trades. It enters long when price crosses below the lower band with oversold RSI, or when band width contracts under low volatility. Short en

Strategy v4 Mean reversionOscillators & momentum
Updated 6 years ago · None stated GitHub repository of Greeffer BB Strategy

More Oscillators & momentum scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers