Strategy · Pine Script v5 · On the chart

MACD Divergence - Reversal Hunter

by Basant1Saini· code credited to TradingTools

MACD Divergence - Reversal Hunter detects regular and hidden divergences between price action and the MACD line using pivot points.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code107
Settings14inputs
LicenceNone statedfile: MPL-2.0
Last update7 months ago4 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

107 lines of Pine Script v5 from 14_MACD_Divergence/14_MACD_Divergence.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

14_MACD_Divergence.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
// © TradingTools

//@version=5
strategy("MACD Divergence - Reversal Hunter", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// ─── Inputs ───
macdFast        = input.int(12, "MACD Fast", group="MACD")
macdSlow        = input.int(26, "MACD Slow", group="MACD")
macdSignal      = input.int(9, "MACD Signal", group="MACD")
pivotLookback   = input.int(5, "Pivot Lookback", group="Divergence")
pivotLookfwd    = input.int(2, "Pivot Look Forward", group="Divergence")
useRegular      = input.bool(true, "Trade Regular Divergence", group="Divergence")
useHidden       = input.bool(true, "Trade Hidden Divergence", group="Divergence")
rsiLength       = input.int(14, "RSI Confirmation Length", group="Filters")
rsiOB           = input.float(70, "RSI Overbought", group="Filters")
rsiOS           = input.float(30, "RSI Oversold", group="Filters")
useRSIFilter    = input.bool(true, "Use RSI Extreme Filter", group="Filters")
atrLength       = input.int(14, "ATR Length", group="Risk Management")
atrMult         = input.float(2.0, "ATR Multiplier for SL", step=0.1, group="Risk Management")
rrRatio         = input.float(2.0, "Risk:Reward Ratio", step=0.1, group="Risk Management")

// ─── MACD ───
[macdLine, signalLine, hist] = ta.macd(close, macdFast, macdSlow, macdSignal)

// ─── RSI ───
rsiVal = ta.rsi(close, rsiLength)

// ─── ATR ───
atrVal = ta.atr(atrLength)

// ─── Pivot Detection on Price and MACD ───
pricePivotLow  = ta.pivotlow(low, pivotLookback, pivotLookfwd)
pricePivotHigh = ta.pivothigh(high, pivotLookback, pivotLookfwd)
macdPivotLow   = ta.pivotlow(macdLine, pivotLookback, pivotLookfwd)
macdPivotHigh  = ta.pivothigh(macdLine, pivotLookback, pivotLookfwd)

// ─── Store Previous Pivots ───
var float prevPriceLow   = na
var float prevMACDLow    = na
var float prevPriceHigh  = na
var float prevMACDHigh   = na

var float currPriceLow   = na
var float currMACDLow    = na
var float currPriceHigh  = na
var float currMACDHigh   = na

if not na(pricePivotLow) and not na(macdPivotLow)
    prevPriceLow := currPriceLow
    prevMACDLow  := currMACDLow
    currPriceLow := pricePivotLow
    currMACDLow  := macdPivotLow

if not na(pricePivotHigh) and not na(macdPivotHigh)
    prevPriceHigh := currPriceHigh
    prevMACDHigh  := currMACDHigh
    currPriceHigh := pricePivotHigh
    currMACDHigh  := macdPivotHigh

// ─── Divergence Detection ───
// Regular Bullish: Price lower low + MACD higher low (reversal up)
regBullDiv = not na(prevPriceLow) and currPriceLow < prevPriceLow and currMACDLow > prevMACDLow
// Regular Bearish: Price higher high + MACD lower high (reversal down)
regBearDiv = not na(prevPriceHigh) and currPriceHigh > prevPriceHigh and currMACDHigh < prevMACDHigh
// Hidden Bullish: Price higher low + MACD lower low (continuation up)
hidBullDiv = not na(prevPriceLow) and currPriceLow > prevPriceLow and currMACDLow < prevMACDLow
// Hidden Bearish: Price lower high + MACD higher high (continuation down)
hidBearDiv = not na(prevPriceHigh) and currPriceHigh < prevPriceHigh and currMACDHigh > prevMACDHigh

// ─── RSI Filter ───
rsiLongOK  = useRSIFilter ? rsiVal < rsiOB : true
rsiShortOK = useRSIFilter ? rsiVal > rsiOS : true

// ─── Entry Conditions ───
bullDiv = (useRegular and regBullDiv) or (useHidden and hidBullDiv)
bearDiv = (useRegular and regBearDiv) or (useHidden and hidBearDiv)

// Trigger on new pivot detection + MACD histogram confirmation
longCondition  = bullDiv and not na(pricePivotLow) and hist > hist[1] and rsiLongOK
shortCondition = bearDiv and not na(pricePivotHigh) and hist < hist[1] and rsiShortOK

// ─── Execute Trades ───
if longCondition and strategy.position_size == 0
    sl = close - atrVal * atrMult
    tp = close + (close - sl) * rrRatio
    strategy.entry("Div Long", strategy.long)
    strategy.exit("Div Long Exit", "Div Long", stop=sl, limit=tp)

if shortCondition and strategy.position_size == 0
    sl = close + atrVal * atrMult
    tp = close - (sl - close) * rrRatio
    strategy.entry("Div Short", strategy.short)
    strategy.exit("Div Short Exit", "Div Short", stop=sl, limit=tp)

// ─── Plotting ───
plotshape(longCondition, title="Bull Divergence", location=location.belowbar, style=shape.diamond, color=color.lime, size=size.small, text="DIV")
plotshape(shortCondition, title="Bear Divergence", location=location.abovebar, style=shape.diamond, color=color.fuchsia, size=size.small, text="DIV")

// MACD reference (non-overlay, will show in separate pane if added)
// Users can add MACD indicator separately for visual confirmation

// ─── Alerts ───
alertcondition(longCondition, title="MACD Div Long", message="MACD Divergence: Bullish divergence detected — Long entry")
alertcondition(shortCondition, title="MACD Div Short", message="MACD Divergence: Bearish divergence detected — Short entry")
alertcondition(regBullDiv, title="Regular Bull Div", message="MACD: Regular bullish divergence forming")
alertcondition(regBearDiv, title="Regular Bear Div", message="MACD: Regular bearish divergence forming")

Overview

MACD Divergence - Reversal Hunter generates buy signals on bullish divergences and sell signals on bearish divergences, with optional RSI filter for overbought or oversold confirmation. Entries use a risk-reward ratio and ATR-based stop loss. The strategy overlays signals directly on the price chart for reversal or continuation trades.

Details

Published by

Basant1Saini on GitHub

Code credit

TradingTools, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Divergence, Oscillators & momentum, Mean reversion

Markets

Stocks

Timeframes

H4 and above, M15-H1

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
MACD Fastint12macdFast
MACD Slowint26macdSlow
MACD Signalint9macdSignal
Pivot Lookbackint5pivotLookback
Pivot Look Forwardint2pivotLookfwd
Trade Regular DivergencebooltrueuseRegular
Trade Hidden DivergencebooltrueuseHidden
RSI Confirmation Lengthint14rsiLength
RSI Overboughtfloat70rsiOB
RSI Oversoldfloat30rsiOS
Use RSI Extreme FilterbooltrueuseRSIFilter
ATR Lengthint14atrLength
Show all 14 settings
SettingTypeDefaultVariable
ATR Multiplier for SLfloat2.0atrMult
Risk:Reward Ratiofloat2.0rrRatio
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

The Stock and NQ Futures Convergence Strategy identifies trading opportunities by comparing the Relative Strength Index of the active chart stock against NQ futures. It enters a long position when NQ RSI rises above the upper threshold while the stock RSI stay

Strategy v5 Oscillators & momentumDivergence
Updated 2 years ago · GPL-3.0 GitHub repository of Stock and NQ Futures Convergence Strategy

VMC Strat Flex Corrected

by matlaenousse
1 stars

This strategy evaluates market conditions using a combination of WaveTrend, RSI, Stochastic RSI, and a custom Money Flow Index calculation inspired by VuManChu. It enters long positions when multiple oscillators hit oversold thresholds and generate an upward c

Strategy v6 Oscillators & momentumDivergence
Updated 10 months ago · None stated GitHub repository of VMC Strat Flex Corrected
330 stars

Alert BB + RSI [Alorse] is a multi-symbol mean-reversion strategy designed for cryptocurrency trading. It evaluates Bollinger Bands and the Relative Strength Index (RSI) across up to 20 user-defined ticker symbols simultaneously. The strategy enters long posit

Strategy v4 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Alert BB + RSI [Alorse]
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

This strategy draws on the price chart and combines Stochastic RSI, the Money Flow Index, and an exponential moving average to open long or short trades. Longs use the lower oscillator thresholds and shorts use the upper ones, with direction limited to longs,

Strategy v5 Oscillators & momentumMoving averages Repaints
Updated 2 years ago · GPL-3.0 GitHub repository of 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers