OPEN-SOURCE SCRIPT
מעודכן Divergence Stack Scanner [AGPro Series]

Divergence Stack Scanner [AGPro Series]
🔹 Overview
Divergence Stack Scanner [AGPro Series] scans five independent momentum and volume oscillators simultaneously — RSI, MACD Histogram, CCI, MFI, and OBV — and grades every confirmed pivot by how many of them show regular divergence at the same time. The result is a 0 to 5 STACK score that isolates rare, high-conviction reversal zones which single-divergence tools simply cannot surface.
Most divergence indicators track one oscillator at a time. Strong reversals, however, tend to leave fingerprints across momentum and volume at once. This tool quantifies that confluence in a single, objective number you can act on.
🔸 Unique Edge
What separates this script from the crowded divergence space:
1. Five-oscillator confluence in one engine — not one divergence, five divergences graded together.
2. Strict versus Window classification — a 5/5 STRICT stack (all five on the exact same pivot) is marked with a star flash, while a 5/5 WINDOW stack (all five within a small bar tolerance) is tagged separately. The distinction matters because strict stacks are statistically rarer and sharper.
3. Pressure Zones — a rectangular, SR-style zone is drawn forward from each qualifying pivot, so the reversal level stays visible long after the signal fires.
4. Rolling win-rate panel — the last N decided signals are evaluated N bars forward, and the win percentage is displayed live on the panel.
5. Per-oscillator live state — you see at a glance which oscillators are already in divergence and how long ago they triggered.
🔹 Methodology
Pivots are detected using the standard TradingView pivot method with a configurable lookback (default 5 bars each side, confirmed, non-repainting).
When a pivot is confirmed, the script compares the current pivot price and oscillator value to the previous same-direction pivot:
- Regular bullish divergence: price prints a lower low while the oscillator prints a higher low.
- Regular bearish divergence: price prints a higher high while the oscillator prints a lower high.
This comparison runs independently for RSI, MACD Histogram, CCI, MFI, and OBV. Each oscillator stores the bar index of its most recent divergence. The stack engine then counts how many oscillators have fired within a tolerance window of the current pivot:
- Strict stack (window = 0): all counted oscillators fired on the exact same pivot bar.
- Window stack (window = 1 to N bars): oscillators fired within N bars of each other.
Pressure zones are drawn only when the stack meets a configurable minimum (default 4/5). Zone height is ATR-scaled so it stays proportional across instruments and timeframes. A proximity filter prevents label clutter: once a label is drawn in a given direction, a new label in the same direction within a short window is only drawn if its stack level is strictly higher.
🔸 Signals & Alerts
On-chart signals:
- ★ N/5 STACK label (filled color) — strict same-bar stack at level N.
- N/5 NEAR label (lighter color) — window stack (near-miss of strict).
- Pressure zone rectangle — drawn forward from the pivot for qualifying stacks.
Alerts available:
- 5/5 Strict Stack (bull and bear, separate) — the rarest and sharpest signal.
- Minimum Stack threshold — fires whenever the stack reaches your configured minimum level.
All alerts use alert.freq_once_per_bar_close and include ticker plus timeframe in the message.
🔹 Key Inputs
Core Engine:
- Pivot Lookback — bars each side to confirm a pivot (default 5).
- RSI, MACD, CCI, MFI lengths — standard defaults, all configurable.
Stack Configuration:
- Minimum Stack Level — display threshold (default 3/5).
- Window Tolerance — bar tolerance for near-stacks (default 3).
- Win-Rate Lookback — number of recent signals used for rolling win rate (default 20).
- Win Evaluation Bars — forward bars to decide win or loss (default 10).
Pressure Zones:
- Minimum Stack for Zone (default 4/5) — keeps the chart premium and uncluttered.
- Zone Extend and Height (ATR%) — tune the visual footprint to your taste.
- Max Active Zones — oldest zones are automatically trimmed.
Panel and Theme:
- Location (6 anchors), Dark or Light theme, font size presets.
- Fully brand-consistent AGPro color palette built in.
🔸 How to Use
- Treat 5/5 STRICT stacks as the headline signal. They are rare by construction and typically appear at genuine inflection points.
- Use 4/5 stacks as early-warning context around support, resistance, or higher-timeframe levels.
- Read the per-oscillator live state on the panel. When RSI, MACD, CCI, MFI are all in the same direction and OBV is the last holdout, a full stack is often imminent.
- Pressure zones work well as re-entry or invalidation levels after the initial signal fires.
- The rolling win rate is a sanity check for the current asset and timeframe — if it degrades meaningfully, raise the minimum stack level or widen the pivot lookback.
🔹 Limitations and Transparency
- This is a confluence tool, not a standalone trading system. Divergence by nature can persist in strong trends before any reversal.
- The engine is pivot-based and therefore delayed by the pivot lookback. Labels appear on the bar the pivot is confirmed, not on the pivot itself.
- Win rate is computed on the last N decided signals on the current chart. It is not a backtest, it is an evolving statistic and it does not include slippage, spread, or position sizing.
- Window stacks are lower-confidence than strict stacks by design. The visual distinction is intentional.
- Session-based "Today's Max" uses calendar-day rollover.
🔸 Risk Disclosure
This indicator is a technical analysis tool for research and education. It is not financial advice, not a signal service, and not a trading strategy. Past patterns do not guarantee future behavior. You are solely responsible for your trading decisions, risk management, and position sizing. Always combine any indicator with independent analysis, higher-timeframe context, and strict risk controls.
🔹 Technical Notes
- Pine Script v6, overlay indicator.
- Fully non-repainting. All divergences are evaluated only on confirmed pivots.
- Drawing objects (labels, boxes) are capped to avoid resource overruns.
- MPL 2.0 licensed — open source.
🔹 Overview
Divergence Stack Scanner [AGPro Series] scans five independent momentum and volume oscillators simultaneously — RSI, MACD Histogram, CCI, MFI, and OBV — and grades every confirmed pivot by how many of them show regular divergence at the same time. The result is a 0 to 5 STACK score that isolates rare, high-conviction reversal zones which single-divergence tools simply cannot surface.
Most divergence indicators track one oscillator at a time. Strong reversals, however, tend to leave fingerprints across momentum and volume at once. This tool quantifies that confluence in a single, objective number you can act on.
🔸 Unique Edge
What separates this script from the crowded divergence space:
1. Five-oscillator confluence in one engine — not one divergence, five divergences graded together.
2. Strict versus Window classification — a 5/5 STRICT stack (all five on the exact same pivot) is marked with a star flash, while a 5/5 WINDOW stack (all five within a small bar tolerance) is tagged separately. The distinction matters because strict stacks are statistically rarer and sharper.
3. Pressure Zones — a rectangular, SR-style zone is drawn forward from each qualifying pivot, so the reversal level stays visible long after the signal fires.
4. Rolling win-rate panel — the last N decided signals are evaluated N bars forward, and the win percentage is displayed live on the panel.
5. Per-oscillator live state — you see at a glance which oscillators are already in divergence and how long ago they triggered.
🔹 Methodology
Pivots are detected using the standard TradingView pivot method with a configurable lookback (default 5 bars each side, confirmed, non-repainting).
When a pivot is confirmed, the script compares the current pivot price and oscillator value to the previous same-direction pivot:
- Regular bullish divergence: price prints a lower low while the oscillator prints a higher low.
- Regular bearish divergence: price prints a higher high while the oscillator prints a lower high.
This comparison runs independently for RSI, MACD Histogram, CCI, MFI, and OBV. Each oscillator stores the bar index of its most recent divergence. The stack engine then counts how many oscillators have fired within a tolerance window of the current pivot:
- Strict stack (window = 0): all counted oscillators fired on the exact same pivot bar.
- Window stack (window = 1 to N bars): oscillators fired within N bars of each other.
Pressure zones are drawn only when the stack meets a configurable minimum (default 4/5). Zone height is ATR-scaled so it stays proportional across instruments and timeframes. A proximity filter prevents label clutter: once a label is drawn in a given direction, a new label in the same direction within a short window is only drawn if its stack level is strictly higher.
🔸 Signals & Alerts
On-chart signals:
- ★ N/5 STACK label (filled color) — strict same-bar stack at level N.
- N/5 NEAR label (lighter color) — window stack (near-miss of strict).
- Pressure zone rectangle — drawn forward from the pivot for qualifying stacks.
Alerts available:
- 5/5 Strict Stack (bull and bear, separate) — the rarest and sharpest signal.
- Minimum Stack threshold — fires whenever the stack reaches your configured minimum level.
All alerts use alert.freq_once_per_bar_close and include ticker plus timeframe in the message.
🔹 Key Inputs
Core Engine:
- Pivot Lookback — bars each side to confirm a pivot (default 5).
- RSI, MACD, CCI, MFI lengths — standard defaults, all configurable.
Stack Configuration:
- Minimum Stack Level — display threshold (default 3/5).
- Window Tolerance — bar tolerance for near-stacks (default 3).
- Win-Rate Lookback — number of recent signals used for rolling win rate (default 20).
- Win Evaluation Bars — forward bars to decide win or loss (default 10).
Pressure Zones:
- Minimum Stack for Zone (default 4/5) — keeps the chart premium and uncluttered.
- Zone Extend and Height (ATR%) — tune the visual footprint to your taste.
- Max Active Zones — oldest zones are automatically trimmed.
Panel and Theme:
- Location (6 anchors), Dark or Light theme, font size presets.
- Fully brand-consistent AGPro color palette built in.
🔸 How to Use
- Treat 5/5 STRICT stacks as the headline signal. They are rare by construction and typically appear at genuine inflection points.
- Use 4/5 stacks as early-warning context around support, resistance, or higher-timeframe levels.
- Read the per-oscillator live state on the panel. When RSI, MACD, CCI, MFI are all in the same direction and OBV is the last holdout, a full stack is often imminent.
- Pressure zones work well as re-entry or invalidation levels after the initial signal fires.
- The rolling win rate is a sanity check for the current asset and timeframe — if it degrades meaningfully, raise the minimum stack level or widen the pivot lookback.
🔹 Limitations and Transparency
- This is a confluence tool, not a standalone trading system. Divergence by nature can persist in strong trends before any reversal.
- The engine is pivot-based and therefore delayed by the pivot lookback. Labels appear on the bar the pivot is confirmed, not on the pivot itself.
- Win rate is computed on the last N decided signals on the current chart. It is not a backtest, it is an evolving statistic and it does not include slippage, spread, or position sizing.
- Window stacks are lower-confidence than strict stacks by design. The visual distinction is intentional.
- Session-based "Today's Max" uses calendar-day rollover.
🔸 Risk Disclosure
This indicator is a technical analysis tool for research and education. It is not financial advice, not a signal service, and not a trading strategy. Past patterns do not guarantee future behavior. You are solely responsible for your trading decisions, risk management, and position sizing. Always combine any indicator with independent analysis, higher-timeframe context, and strict risk controls.
🔹 Technical Notes
- Pine Script v6, overlay indicator.
- Fully non-repainting. All divergences are evaluated only on confirmed pivots.
- Drawing objects (labels, boxes) are capped to avoid resource overruns.
- MPL 2.0 licensed — open source.
הערות שחרור
UPDATE NOTES - V2.0This update focuses on improving divergence selectivity, chart cleanliness, and decision readability while preserving the original Divergence Stack Scanner identity.
The core purpose of the script remains unchanged.
This release improves how regular multi-oscillator divergence stacks are scored, filtered, labeled, and interpreted on the chart.
This script continues to function as an analytical and visualization tool.
It does not attempt to predict price direction or provide guaranteed outcomes.
------------------------
What Changed
------------------------
* Added a 0-100 Divergence Readiness score.
The score evaluates swing quality, oscillator agreement, trend context, confirmation close, and distance from invalidation.
* Added clearer stack tiers.
Events are now classified as WATCH, READY, or PRIME so strong divergence stacks stand apart from lower-quality noise.
* Added same-swing dedupe and cooldown logic.
The update reduces repeated same-side labels around one swing while still keeping enough labels visible for a premium public chart.
* Added invalidation and follow-through tracking.
Each active stack now carries a rule-based invalidation level and a projected follow-through target for cleaner review.
* Added cleaner connector and expiry logic.
Connectors link only the compared price pivots, while active divergence context can expire after a configurable number of bars.
* Balanced the default screenshot preset.
Event labels are shorter, lifecycle labels are optional, default cooldown is stronger, and Stack Reaction Bands use a selective but still visible threshold.
------------------------
Visual Improvements
------------------------
* Added cleaner swing connectors between compared pivots.
* Added compact event labels with state, score tier, stack count, and hover-level invalidation context.
* Added optional Stack Reaction Bands with centered text inside the band and a balanced default threshold.
* Labels are ATR-offset farther from candles and controlled by cooldown plus max-visible object settings.
------------------------
Interface & Usability
------------------------
* Rebuilt the panel around the V2 roadmap rows: Active Divergence, Stack Count, Swing Quality, Confirmation, and Action.
* Preserved the AGPro standard merged blue header row with only the panel title.
* Added sensitivity, confirmation mode, expiry, panel theme, panel location, panel font-size, and label font-size controls.
* Panel visibility remains enabled by default.
------------------------
Behavior Notes
------------------------
This update does not turn the script into a hidden divergence continuation tool.
Divergence Stack Scanner remains focused on regular bullish and bearish divergence confluence across RSI, MACD Histogram, CCI, MFI, and OBV.
The new score and action state are rule-based review tools. They should be read as context, not as instructions.
------------------------
Limitations Reminder
------------------------
The script remains a rule-based analytical tool.
Market conditions such as volatility, liquidity, strong trend persistence, and timeframe differences may affect how divergence stacks appear.
Pivot-based divergence confirms after the pivot lookback, so labels appear after confirmation rather than on the exact pivot in real time.
------------------------
Risk Reminder
------------------------
This script is for educational and analytical purposes only.
It does not provide financial advice or guaranteed trading outcomes.
Users remain responsible for their own decisions.
הערות שחרור
UPDATE NOTES - v2.1This update adds an optional SMT (correlated-pair) divergence module and refines
zone-badge readability.
The core purpose of the script remains unchanged. The 5-oscillator regular
divergence stack, its 0-100 readiness score, tiers, confirmation logic,
invalidation and follow-through tracking all behave exactly as before. The new
SMT layer is fully optional, disabled by default, and tracked separately from
the 0-5 stack score. This script continues to function as an analytical and
visualization tool. It does not attempt to predict price direction or provide
guaranteed outcomes.
------------------------
What Changed
------------------------
* Added an optional SMT (correlated-pair) divergence module.
A new "Enable SMT Divergence" toggle compares the chart symbol against a
correlated symbol you choose (for example XAGUSD on an XAUUSD chart, or US30 on
a NAS100 chart). It flags SMT-style divergence when one symbol makes a new high
or low and the correlated symbol does not.
* SMT is kept completely separate from the oscillator stack.
The SMT module has its own detection, its own labels, its own panel row, and its
own alerts. It does NOT add to or change the 0-5 stack score. This was an
intentional design choice so the original stack reading stays clean.
* Added a Positive / Inverse correlation setting.
Positive suits normally same-direction pairs (XAUUSD and XAGUSD, NAS100 and
US30). Inverse suits normally opposite pairs.
* Added two dedicated SMT alerts (bullish and bearish), plus an SMT alert toggle.
* Converted Stack Reaction Band labels to centered zone badges.
Each reaction band now carries a centered badge (tier and score) inside the zone
instead of plain box text, improving first-glance readability over the band.
------------------------
Visual Improvements
------------------------
* Reaction-band readouts are now centered badges inside their zone, easier to
read against candles than the previous in-box text.
* SMT events use a distinct accent color and sit farther from the candles than
the stack labels, so the two layers never overlap.
* The panel adds a single "SMT (corr)" row only when the SMT module is enabled,
keeping the default layout unchanged for users who do not use SMT.
------------------------
Interface & Usability
------------------------
* New "SMT Divergence (Correlated Pair)" settings group: enable toggle,
correlated symbol, correlation type, and an SMT label toggle.
* The SMT panel row shows the current SMT side and notes when it aligns with the
active stack direction, as context rather than a combined score.
* All existing panel rows, inputs, and defaults are preserved.
------------------------
Behavior Notes
------------------------
This update does not change the core analytical logic of the script. The
oscillator stack, readiness score, and state logic are unchanged.
The SMT module is rule-based context only. SMT divergence is shown and alerted
separately and should be read as additional correlated-pair context, not as an
instruction and not as part of the stack score.
The SMT module uses a correlated symbol request with lookahead disabled, so it
remains non-repainting like the rest of the engine.
------------------------
Limitations Reminder
------------------------
The script remains a rule-based analytical tool. Market conditions such as
volatility, liquidity, strong trend persistence, and timeframe differences may
affect how divergence stacks and SMT events appear.
Pivot-based divergence confirms after the pivot lookback, so labels appear after
confirmation rather than on the exact pivot in real time. SMT events follow the
same pivot timing.
------------------------
Risk Reminder
------------------------
This script is for educational and analytical purposes only. It does not provide
financial advice or guaranteed trading outcomes. Users remain responsible for
their own decisions.
סקריפט קוד פתוח
ברוח האמיתית של TradingView, יוצר הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יוכלו לעיין בו ולאמת את פעולתו. כל הכבוד למחבר! אמנם ניתן להשתמש בו בחינם, אך זכור כי פרסום חוזר של הקוד כפוף ל־כללי הבית שלנו.
Public-free scripts + invite-only AGPro workflows for market analysis, liquidity context, risk planning and execution review.
Rules-based. No hype. No guesswork.
Library & access: agprolabs.com/
Telegram: t.me/agprolabs
Rules-based. No hype. No guesswork.
Library & access: agprolabs.com/
Telegram: t.me/agprolabs
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.
סקריפט קוד פתוח
ברוח האמיתית של TradingView, יוצר הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יוכלו לעיין בו ולאמת את פעולתו. כל הכבוד למחבר! אמנם ניתן להשתמש בו בחינם, אך זכור כי פרסום חוזר של הקוד כפוף ל־כללי הבית שלנו.
Public-free scripts + invite-only AGPro workflows for market analysis, liquidity context, risk planning and execution review.
Rules-based. No hype. No guesswork.
Library & access: agprolabs.com/
Telegram: t.me/agprolabs
Rules-based. No hype. No guesswork.
Library & access: agprolabs.com/
Telegram: t.me/agprolabs
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.