OPEN-SOURCE SCRIPT

MACD Divergence Engine

272
════════════════════════════════════════════════════

OVERVIEW

MACD Divergence Engine is a rebuild of the classic MACD divergence
detector, redesigned around one question the original never asks:
is this divergence actually worth anything?

A raw divergence is a low-information event. Every oscillator prints
dozens of them, most in conditions where the pattern has no business
working. This engine finds the same structures, then grades each one
from 0 to 100 across ten independent factors and only draws the ones
that clear your threshold. Every signal is labelled with its grade
(A+ / A / B / C / D) and its numeric score, so you can see exactly
how much the model liked it rather than treating all signals alike.

Built on Pine v6. Runs in its own pane with a single zero centre line
as the reference axis.

════════════════════════════════════════════════════

WHAT IT DOES DIFFERENTLY

1 — VOLATILITY NORMALIZATION

Raw MACD is measured in price units. A reading of 0.8 means something
completely different on an index future, on EURUSD, and on a $3
small-cap. That is why fixed MACD thresholds never transfer between
instruments.

Here the oscillator is divided by ATR, by its own standard deviation,
or by percent-of-price (your choice). Every internal threshold is then
expressed in volatility units, so the zero line, the exhaustion bands
and all ten score components mean the same thing on every symbol and
every timeframe without re-tuning. Raw mode is available if you want
the classic scale back.

2 — MULTI-PIVOT SCAN

Conventional divergence scripts compare the current swing to exactly
one prior swing. Real divergences frequently form against the second
or third pivot back, and those get missed entirely.

This build maintains a rolling ledger of recent pivots, evaluates every
legal pairing inside your bar-gap window, scores each one, and emits
the single strongest. Scan depth is adjustable from 1 to 8.

3 — THE CONFLUENCE MODEL

Each divergence candidate is scored across ten orthogonal factors:

· MAGNITUDE — how far apart the price swing and the momentum swing
genuinely are, in ATR and oscillator sigma. Combined as a geometric
mean so a near-flat price leg cannot be rescued by a large
oscillator leg. A 0.1-ATR "divergence" scores near zero.

· EXTREMITY — how stretched the oscillator was at the pivot.
Reversals want an extreme reading; continuations want a shallow
pullback that never reached exhaustion, so this factor inverts
between the two classes.

· SPACING — pivots too close together are the same swing counted
twice; too far apart and market structure has changed between them.

· REGIME FIT — see the next section. Highest-value single filter.

· EXTENSION — distance from the structural moving average, signed
toward the intended trade, in ATR.

· VOLUME — regular divergence wants falling volume on the second
push, which is what exhaustion looks like. Hidden divergence wants
rising volume. Neutral on symbols without volume data.

· HIGHER-TIMEFRAME BIAS — momentum direction on a higher timeframe,
auto-selected from your chart timeframe or set manually.

· MOMENTUM SHIFT — is the histogram already turning at the
confirmation bar, and is the MACD line on the right side of signal.

· ZERO-LINE INTEGRITY — see below.

· BAR STRUCTURE — RSI positioning at the pivot plus the rejection
wick as a proportion of that bar's range.

All ten weights are exposed as inputs. Set any of them to 0 to remove
that factor entirely. The model is auditable, not a black box you have
to take on faith — you can see and change exactly what it rewards.

4 — REGIME AWARENESS

Regular and hidden divergences are opposite trades and fail in opposite
conditions. Regular divergence is mean-reversion and gets destroyed in
strong trends. Hidden divergence is continuation and gets destroyed in
chop. Firing both blindly guarantees you take the wrong one half the
time.

Trend strength is measured by blending Kaufman's Efficiency Ratio (how
straight the path is) with ADX (directional conviction) — two different
questions, deliberately averaged. Direction comes from DMI confirmed by
a structural moving average; when those two disagree the regime is
classified as TRANSITION, which is itself useful information.

The model then scores each divergence class against that measured
regime. Notably, a regular divergence WITH the prevailing trend — a
pullback low that held while momentum improved — is treated as the
highest-quality version of the pattern, while the same structure
against a strong trend is scaled down as the falling-knife trade it is.

5 — GENERALISED ZERO-LINE DISCIPLINE

The classic rule says a bullish divergence should form entirely below
zero. This build extends that: in Strict mode the whole oscillator
segment between both pivots must stay on the correct side of the zero
line, not just the two endpoints. The rule is also correctly inverted
for hidden divergences, which legitimately live on the opposite side of
zero from regular ones. Soft mode checks only the pivot values, and Off
removes the constraint.

════════════════════════════════════════════════════

THE ZERO CENTRE LINE

The pane carries one zero line, drawn as a first-class object rather
than a background hairline, because every threshold in the model is
anchored to it. Above zero is momentum expansion, below is contraction.
It can optionally take its colour from the current regime, giving you
the market state at a glance without reading any numbers. Line width is
adjustable.

════════════════════════════════════════════════════

READING THE OUTPUT

· Solid line between two pivots — regular divergence
· Dashed line — hidden divergence
· Label — direction, grade, and score out of 100
· Dotted line on the price chart — the same divergence mirrored onto
price, so you can see both legs of the structure at once
· Shaded band — adaptive exhaustion envelope at ±N sigma
· Histogram — four-state colouring for expansion and fade above and
below zero

Grades: A+ is 85 and above, A is 75+, B is 65+, C is 55+, D below that.

════════════════════════════════════════════════════

SETTINGS GUIDE

Start with defaults. Minimum Score is 60, which is roughly a B grade.

· Want fewer, higher-conviction signals — raise Minimum Score to 75
or 85. Expect a large drop in signal count. This is the main dial.
· Trading continuation setups — enable Hidden divergences.
· Too few signals on a choppy instrument — set Zero-Line Discipline
to Soft, or reduce Pivot Left/Right.
· Divergences forming against older swings are being missed — raise
Prior Pivots Scanned.
· Instrument has no meaningful volume (many FX feeds) — set the
Volume Confirmation weight to 0 rather than leaving it neutral.
· Want the classic MACD scale back — set Normalization to Raw.

Oscillator MA type is selectable: EMA, SMA, WMA, HMA, DEMA, TEMA,
ZLEMA and KAMA. KAMA adapts its smoothing to the efficiency ratio,
which reduces whipsaw in chop. ZLEMA and TEMA cut lag at the cost of
overshoot.

════════════════════════════════════════════════════

ALERTS

Five alert conditions are provided: regular bullish, regular bearish,
hidden bullish, hidden bearish, and an A+ grade filter that fires only
on scores of 85 or above.

A structured JSON alert is also emitted on every signal, carrying the
symbol, timeframe, signal type, grade, numeric score, regime state,
higher-timeframe bias, price and ATR — suitable for routing to a
webhook.

════════════════════════════════════════════════════

REPAINTING

Signals do not repaint. Pivot confirmation requires the configured
number of bars to the right of the pivot, so a divergence is only
detected after those bars have printed and its position never moves
afterwards. The trade-off is inherent to all pivot-based detection:
the signal is by definition late by that many bars. That is disclosed
rather than hidden.

"Evaluate on bar close only" is enabled by default and prevents the
live-bar score components from flickering intrabar.

════════════════════════════════════════════════════

CREDITS

Based on "MACD Divergences" by daviddtech, whose script established
the pivot-comparison structure and the zero-line rule this build starts
from. The divergence detection has been rewritten around a multi-pivot
ledger, and the normalization layer, confluence scoring model, regime
engine and drawing system are new work.

Open source. Use it, read it, change it.

════════════════════════════════════════════════════

DISCLAIMER

This is an analysis tool, not financial advice and not a trading
system. It identifies and grades a chart pattern; it does not tell you
what to buy or sell, and it does not include position sizing, risk
management or exits. A high score means the model's criteria were met,
not that the trade will work. Divergence is a pattern that fails
regularly, and it fails most often exactly where it is most tempting —
against a strong trend.

No indicator predicts the future. Past behaviour of any pattern does
not guarantee future results. Test anything on your own instruments and
timeframes before risking capital, and size positions on the assumption
that any individual signal can be wrong.

════════════════════════════════════════════════════

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.