RSI DivergenceReal-Time ZigZag Divergence Engine
A dynamic market structure analyzer combining adaptive ZigZag pivot detection with multi-oscillator divergence identification, featuring real-time forming-signal alerts and advanced exhaustion filtering for high-probability reversal trading.
Overview
The Real-Time ZigZag Divergence Engine revolutionizes classical divergence analysis by calculating signals in real-time as price legs develop, rather than waiting for bar close confirmations. Using an adaptive ZigZag algorithm that responds to either percentage-based or volatility-adjusted (ATR) deviation thresholds, the system continuously tracks swing highs and lows while monitoring your choice of 7 major oscillators for momentum divergences. Advanced filtering mechanisms—including leg exhaustion ratios, minimum oscillation thresholds, and dynamic overbought/oversold zone requirements—ensure only structurally sound divergences trigger alerts, eliminating the noise common in standard divergence indicators.
User Guide: Input Parameters & Their Impact
ZigZag Configuration
These parameters control how the engine identifies swing highs and lows—the structural backbone of all divergence detection.
Deviation Mode (Percentage): Selects the methodology for determining when a swing leg is significant enough to register as a pivot. "Percentage" uses fixed percentage moves from highs/lows (traditional); "ATR" uses Average True Range multiples for volatility-adaptive pivot detection that automatically adjusts to quiet vs. volatile market conditions. Use ATR for forex/crypto where volatility regimes shift; use Percentage for equities with consistent tick sizes.
Deviation % (0.5): The minimum price movement required to confirm a pivot reversal (in percentage terms). Lower values (0.2-0.3) create more sensitive zigzags that catch minor swings and micro-divergences—ideal for scalping on lower timeframes. Higher values (1.0-2.0) filter for major structural swings only, showing only significant divergences suitable for swing trading. Increasing this reduces signal frequency but increases structural importance.
ATR Length (14): The lookback period for volatility calculation when in ATR mode. Standard 14-bar setting measures medium-term volatility; decrease (7-10) for short-term volatility responsiveness (catches quick regime changes); increase (20-30) for smoother volatility baselines that ignore short-term spikes.
ATR Multiplier (1.5): The deviation threshold expressed as a multiple of ATR when in ATR mode. Lower multipliers (0.8-1.0) create tight zigzags responsive to small volatility-adjusted moves; higher multipliers (2.0-3.0) require significant volatility-confirmed moves to register pivots. This directly scales with market noise—increase when experiencing whipsaws, decrease when volatility compresses.
Oscillator Settings
Controls the momentum indicator used for divergence comparison against price structure.
Type (RSI): The mathematical engine generating momentum readings. RSI measures
speed/magnitude of moves (standard); MFI adds volume weighting (better for spotting accumulation/distribution divergences); CCI measures deviation from statistical mean (effective for trend strength); Stochastics tracks position within recent range (optimal for range-bound markets); Williams %R is inverse stochastic (sensitive to overbought/oversold); ROC measures pure percentage change (momentum slope); CMO measures summed changes (smoother momentum). Select based on your market type—RSI for general use, MFI for volume analysis, Stochastics for ranges.
Length (14): The calculation period for the selected oscillator. Shorter lengths (7-9) create responsive, noisy oscillators that catch divergences quickly but generate more false signals. Longer lengths (21-30) smooth the oscillator, showing only significant momentum divergences that persist over time. This should align with your trading horizon—match to your typical holding period.
Smoothing EMA (1): Post-calculation exponential moving average applied to the oscillator output. Values above 1 (3-5) reduce oscillator noise, making divergence lines cleaner but potentially lagging; 1 means raw oscillator output for maximum responsiveness. Increase if experiencing oscillator whipsaws near pivot points.
Detection Settings
Controls which types of divergences are calculated and when signals appear.
Regular Divergences (true): Enables detection of classic reversal divergences where price makes higher highs while oscillator makes lower highs (bearish), or price makes lower lows while oscillator makes higher lows (bullish). These indicate momentum exhaustion and potential trend reversals. Disable if you only trade trend continuation.
Hidden Divergences (false): Enables detection of trend-continuation divergences where price makes higher lows while oscillator makes lower lows (bullish continuation in uptrend), or price makes lower highs while oscillator makes higher highs (bearish continuation in downtrend). These indicate momentum consolidation within trend direction. Enable for trend-following strategies, disable for pure mean-reversion.
Live (Forming) Signals (true): When enabled, displays potential divergences on the currently developing (unconfirmed) ZigZag leg. This gives early warning before pivot confirmation but carries risk of the leg extending and invalidating the signal. Disable for conservative trading requiring fully confirmed structure; enable for aggressive early entry with confirmation on next pivot.
Confirmed Signals (true): Displays divergences only after ZigZag pivots are fully confirmed (leg complete). These are historically validated structural points with defined risk levels. Keep enabled for standard trading; disable only if you want to see only live forming setups.
Filters
Advanced quality control mechanisms to eliminate weak or structurally unsound divergences.
Min Bars Between Pivots (3): The minimum number of bars required between two pivot points to validate a divergence. Prevents "clustered" signals in choppy, sideways markets where pivots form too close together. Increase (5-8) to ensure divergences develop over meaningful time periods; decrease (1-2) for faster-paced markets where quick reversals are valid.
Min Leg Size % (0.0): The minimum percentage movement required for a ZigZag leg to qualify for divergence checking. Filters out tiny, insignificant swings that lack structural importance. Set to 1.0-2.0 to require meaningful price moves before divergence analysis; keep at 0.0 to analyze all swings regardless of size.
Max Leg Ratio (0.0): An exhaustion filter comparing current leg size to previous same-direction leg size. When enabled (values like 1.5-2.0), it prevents signals where the current leg is excessively large compared to the previous leg, indicating potential blow-off exhaustion rather than sustainable divergence. Values above 1.0 mean current leg can be X times larger than previous; 0.0 disables. Use 1.2-1.5 to avoid entering extended trends near exhaustion points.
Min Osc Divergence (0.0): The minimum absolute difference in oscillator values required between two pivots to constitute a valid divergence. Filters weak "barely there" divergences. Set to 5.0-10.0 to require meaningful oscillator disagreement with price; keep at 0.0 for any directional disagreement to qualify.
Require OB/OS Zone (false): When enabled, divergences only trigger if the second pivot occurs in extreme oscillator territory (overbought for highs, oversold for lows). This ensures divergences occur at statistically extreme levels rather than mid-range noise. Enable for high-probability mean-reversion setups; disable to catch mid-trend divergences.
Overbought (70.0) / Oversold (30.0): The threshold levels defining extreme zones when "Require OB/OS Zone" is enabled. Adjust based on your oscillator type—standard for RSI (70/30), but for CCI use (+100/-100), for Stochastics (80/20).
Visual Settings
Controls display aesthetics and performance management.
ZigZag Lines (true): Toggle display of confirmed pivot-to-pivot trend lines. These show the structural path of price and help visualize trend progression. Disable to reduce chart clutter if focusing only on divergence signals.
Leg Measurements (false): Displays percentage move and bar count labels on each completed ZigZag leg. Useful for analyzing swing magnitude and duration; enable for structural analysis, disable for cleaner charts.
Divergence Lines on Price (true): Draws connecting lines between the two price pivot points forming a divergence. Provides visual confirmation of the structural relationship being analyzed.
Bullish/Bearish Colors: Standard and hidden divergence label colors. Green/Teal for bullish signals (regular/hidden); Red/Pink for bearish. Adjust for colorblind accessibility or personal preference.
Max Stored Objects (50): Memory management limit for lines and labels. Prevents performance degradation on charts with extensive history. Increase (100-200) for long-term analysis on high-timeframe charts; decrease (20-30) for intraday scalping where only recent signals matter.
How It Works
Adaptive Pivot Detection
The engine continuously tracks price extremes, updating the "live" pivot candidate as new highs or lows develop within the current leg. When price reverses by the deviation threshold (percentage or ATR-based), the live pivot becomes confirmed and stored in history, while a new opposite-direction tracking begins.
Oscillator Synchronization
At every confirmed pivot and every bar of the live forming leg, the selected oscillator value is captured. This creates a parallel track of momentum highs/lows corresponding to price structure.
Divergence Classification
The system compares current price and oscillator values against previous same-type pivots (high-to-high, low-to-low). When price makes a higher high but the oscillator makes a lower high (and filters pass), a regular bearish divergence registers. The classification engine distinguishes between reversal divergences (regular) and continuation divergences (hidden) based on relative positioning.
Real-Time vs. Confirmed Logic
Live signals calculate on the developing leg, allowing traders to anticipate potential setups before structural completion—marked with a "⚡" symbol. Confirmed signals validate only after the ZigZag algorithm confirms the pivot, ensuring the divergence exists on completed structure.
Use this tool to identify momentum exhaustion points where price structure and oscillator momentum disagree. For conservative trading, require OB/OS zone validation and set Min Leg Size to 1.0% to avoid noise; for aggressive scalping, enable live signals with Stochastics on 5-minute charts with tight filters. Watch for confluence where regular divergences appear near major ZigZag structural levels—this combination of momentum divergence and structural completion provides the highest probability reversal setups.
Pine Script® インジケーター






















