OPEN-SOURCE SCRIPT
Telah dikemas kini Multi Divergence WALLDEM

The Multi Divergence Indicator is designed to identify price-oscillator divergences across eight common technical oscillators (RSI, MACD, Stochastic, CCI, Momentum, Williams %R, Awesome Oscillator, and OBV), helping traders spot potential reversals or continuations. The original version effectively draws lines and labels for detected divergences but lacks outputs compatible with TradingView's Pine Screener, leading to the error: "The indicator misses plots or alert conditions, have access restrictions, or another issue." This stems from Pine Screener's requirements for at least one plot() or alertcondition() to enable filtering and scanning across symbols.
To resolve this, the fixed version incorporates several enhancements while maintaining the core logic of pivot detection using ta.pivotlow() and ta.pivothigh() with user-defined lookback periods (default: 5 left/right). Divergences are now separated into regular and hidden types for both bullish and bearish cases, aligning more closely with advanced divergence screeners like the provided example from Trendoscope. This separation uses distinct colors (green/lime for bullish regular/hidden, red/orange for bearish) and tooltips listing contributing oscillators.
Detailed Changes and Rationale
The updates focus on compatibility, usability, and granularity:
Overlay Setting: Changed to overlay=false to treat it as a non-overlay indicator suitable for screeners (similar to the example). Drawings (lines/labels) use force_overlay=true to ensure they appear on the main chart pane.
Divergence Separation: Instead of a single bull_count or bear_count, we now calculate:
Regular bullish: Price makes lower low, but oscillator makes higher low.
Hidden bullish: Price makes higher low, but oscillator makes lower low.
Regular bearish: Price makes higher high, but oscillator makes lower high.
Hidden bearish: Price makes lower high, but oscillator makes higher high.
This is checked per oscillator if enabled via inputs, incrementing separate counters and building dedicated tooltips.
Alert Conditions: Added alertcondition() calls when a divergence type's count > 0. This creates selectable alert conditions in TradingView's alert dialog and satisfies screener requirements. Messages include the tooltip for context (e.g., which oscillators contributed).
Plots for Screening: Four new plot() statements output the counts (0 if no detection) with display = display.data_window. These appear in the data window and enable screener filters like "value > 0" or "value >= 3" (for strong signals from multiple oscillators). Plots are hidden from the chart to avoid clutter.
No Impact on Performance: Calculations remain efficient, only triggering on confirmed pivots (delayed by lbR bars for accuracy). The max distance (maxDist) prevents outdated pivot comparisons.
Oscillator-Specific Logic
Each oscillator's divergence check uses its respective value (e.g., MACD histogram for MACD, smoothed %D for Stochastic). Users can toggle calculations via boolean inputs, reducing computation if not needed. Here's a table summarizing the oscillators and their roles:
To resolve this, the fixed version incorporates several enhancements while maintaining the core logic of pivot detection using ta.pivotlow() and ta.pivothigh() with user-defined lookback periods (default: 5 left/right). Divergences are now separated into regular and hidden types for both bullish and bearish cases, aligning more closely with advanced divergence screeners like the provided example from Trendoscope. This separation uses distinct colors (green/lime for bullish regular/hidden, red/orange for bearish) and tooltips listing contributing oscillators.
Detailed Changes and Rationale
The updates focus on compatibility, usability, and granularity:
Overlay Setting: Changed to overlay=false to treat it as a non-overlay indicator suitable for screeners (similar to the example). Drawings (lines/labels) use force_overlay=true to ensure they appear on the main chart pane.
Divergence Separation: Instead of a single bull_count or bear_count, we now calculate:
Regular bullish: Price makes lower low, but oscillator makes higher low.
Hidden bullish: Price makes higher low, but oscillator makes lower low.
Regular bearish: Price makes higher high, but oscillator makes lower high.
Hidden bearish: Price makes lower high, but oscillator makes higher high.
This is checked per oscillator if enabled via inputs, incrementing separate counters and building dedicated tooltips.
Alert Conditions: Added alertcondition() calls when a divergence type's count > 0. This creates selectable alert conditions in TradingView's alert dialog and satisfies screener requirements. Messages include the tooltip for context (e.g., which oscillators contributed).
Plots for Screening: Four new plot() statements output the counts (0 if no detection) with display = display.data_window. These appear in the data window and enable screener filters like "value > 0" or "value >= 3" (for strong signals from multiple oscillators). Plots are hidden from the chart to avoid clutter.
No Impact on Performance: Calculations remain efficient, only triggering on confirmed pivots (delayed by lbR bars for accuracy). The max distance (maxDist) prevents outdated pivot comparisons.
Oscillator-Specific Logic
Each oscillator's divergence check uses its respective value (e.g., MACD histogram for MACD, smoothed %D for Stochastic). Users can toggle calculations via boolean inputs, reducing computation if not needed. Here's a table summarizing the oscillators and their roles:
Nota Keluaran
Separate pine Has been removed visible only on chartNota Keluaran
Key Fixes in the Updated Multi Divergence IndicatorSafe Volume Referencing: Replaced direct volume[prevLowBar]/volume[prevHighBar] with volume[bar_index - prevLowBar] (and similar for highs) plus na checks to prevent invalid history errors on early bars.
Variable Shadowing Eliminated: Used unique names like lowPreviousSwing, highPreviousSwing, lowMaSlope, highMaSlope to avoid redeclaration conflicts in low/high sections.
Robust Trend Calculations: Added not na checks for previous/prevPrev pivots and MA values before computing swings/slopes—ensures stability on ranging charts.
Zigzag Filtering Reliable: Previous swing direction (3 pivots) with flat handling for detection in ranging markets; visible reduction vs "None" in trending.
Volume Confirmation Safe: Optional filter now uses na-safe previous volume for regular divergences.
These changes make the script compile cleanly, run without crashes, and deliver consistent Zigzag filtering with volume-backed quality on all charts.
Volume Confirmation Implementation
The optional volume filter (default off) requires classic support for regular divergences:
Bullish regular: Higher volume on lower low (accumulation).
Bearish regular: Lower volume on higher high (distribution).
Hidden unchanged.
Safe na handling prevents errors on early pivots.
Zigzag Method Behavior
Uses previous swing (prev vs prevPrev pivot):
Regular: Opposite or flat previous swing.
Hidden: Matching or flat previous swing.
Early (2 pivots): All shown.
Clear visible change from "None" in trending markets.
Testing & Compatibility
Compiles without errors; signals reliable on ranging (flat included) and trending charts. Volume filter reduces regular reversals for quality when enabled.
The updated Multi Divergence Indicator script represents a significant refinement, resolving the compilation and runtime issues that previously caused frustration, particularly around invalid history referencing, variable shadowing, and inconsistent trend filtering behavior. These fixes were implemented thoughtfully to ensure stability across all chart types and timeframes, from highly volatile crypto hourly charts to ranging equity dailies, while enhancing practical usability for divergence trading. The core multi-oscillator detection (8 sources: RSI, MACD histogram, Stochastic %D, CCI, Momentum, Williams %R, Awesome Oscillator, OBV) remains intact, with counting for labels, ATR-offset positioning for readability in volatile conditions, live color updates via tracking arrays and label.set_ calls (instant refresh on settings changes), repaint for timely last-bar potential signals (dashed lines + "(pot)" distinction), detailed tooltips listing contributing oscillators on hover, dynamic alerts with full context, and hidden data window plots for Pine Screener filtering by count.
The primary compilation problems stemmed from Pine Script v6's strict rules on history referencing and variable scoping. Direct access like volume[prevLowBar] risked invalid bar indices (e.g., when prevLowBar is na on early pivots or exceeds history), triggering "Invalid number of bars back" errors. The fix uses volume[bar_index - prevLowBar] with ternary na checks (na(prevLowBar) ? na : volume[...])—a standard safe pattern that calculates the offset dynamically while guarding against undefined states. This applies symmetrically to highs and potential pivots, eliminating crashes on short histories or sparse pivots common in lower timeframes.
Variable shadowing occurred from redeclaring names like previousSwing or maSlope in separate low/high sections, confusing the parser about scope. The solution introduces uniquely prefixed variables (lowPreviousSwing, highPreviousSwing, lowMaSlope, highMaSlope)—preventing conflicts while keeping code readable. Additional na checks for prevPrev pivots/MA ensure trend calculations (Zigzag previous swing, MA Difference slope) only proceed when sufficient data exists, defaulting to unfiltered for early divergences.
The Zigzag method now reliably provides visible, meaningful filtering: trend based on previous swing direction (sign(prevPivot - prevPrevPivot)), with flat swings (0) included for detection in ranging markets. Regular divergences require opposite or flat previous swing (reversals favored when swing opposes), hidden matching or flat (continuations when aligns). Early pairs (only two pivots) show all types for initial sensitivity; three+ pivots enforce context. This creates clear distinction from "None"—fewer inappropriate reversals against previous swing in trending markets, balanced detection in ranging—matching practical Trendoscope-style behavior without external libraries.
Volume-backed confirmation (optional, default off in new "Volume Filter" group) adds classic reversal support for regular divergences: higher volume on lower low for bullish regular (accumulation evidence), lower on higher high for bearish regular (distribution weakening). Hidden types remain unfiltered, as continuation patterns often lack strong volume divergence. Safe prevVolume calculation prevents errors, maintaining high signal count by default while offering quality toggle.
Performance remains efficient: conditional execution on pivots, small arrays for label tracking, no unnecessary calculations. The indicator now balances quantity (default "None" or off volume) and quality (Zigzag/MA + volume on) across market conditions, with robust error handling for consistent operation.
Fixed IssueOriginal ProblemImplemented SolutionBenefitInvalid History Referencingvolume[prevLowBar] crashes on na/out-of-rangevolume[bar_index - prevLowBar] with na ternarySafe on early bars/ranging chartsVariable ShadowingRedeclared previousSwing/maSlope in sectionsUnique prefixes (low/highPreviousSwing etc.)Clean scoping, no parser conflictsTrend Calculation Instabilityna values in swing/slope causing skips/errorsAdded not na checks for prevPrev/MAReliable filtering on all pivotsZigzag VisibilityNo meaningful change or no signalsPrevious swing (3 pivots) with flat includedVisible reduction vs "None" in trendsVolume Confirmation SafetyDirect referencing risked errorsna-safe prevVolume with ternaryQuality reversals without crashes
Nota Keluaran
This update adds prediction arrows to the Multi Divergence Indicator, visualizing where price is likely to go after a divergence is detected.Key Features
Feature Description
Prediction Multiplier Controls ATR-based price target (default: 2.0)
Prediction Bars Forward Number of bars to project forward (default: 20)
Arrow Colors Configurable green (bullish) / red (bearish)
How Arrows Work
Divergence Type Arrow Start Arrow Direction Predicted Price
Bullish Regular/Hidden Close price of pivot bar Diagonal UP + RIGHT Current low + (ATR × multiplier)
Bearish Regular/Hidden Close price of pivot bar Diagonal DOWN + RIGHT Current high - (ATR × multiplier)
Implementation Details
Start Position: Arrows begin at the close price of the bar where the divergence occurred
For bullish: starts at the close (top of bar)
For bearish: starts at the close (bottom of bar)
Direction: Diagonal projection combining price movement + forward time projection
Visual Layering: Uses chart.point.from_index() with xloc.bar_index to bring arrows to the front
Applies to Both:
Confirmed divergences (solid lines between pivots)
Potential divergences (dashed lines, repaint enabled)
Arrow Style: Uses line.style_arrow_right to clearly indicate direction
The arrows provide a visual target for where price could potentially move, helping traders anticipate the next move after a divergence signal! 📈📉
Skrip sumber terbuka
Dalam semangat TradingView sebenar, pencipta skrip ini telah menjadikannya sumber terbuka, jadi pedagang boleh menilai dan mengesahkan kefungsiannya. Terima kasih kepada penulis! Walaupuan anda boleh menggunakan secara percuma, ingat bahawa penerbitan semula kod ini tertakluk kepada Peraturan Dalaman.
Penafian
Maklumat dan penerbitan adalah tidak bertujuan, dan tidak membentuk, nasihat atau cadangan kewangan, pelaburan, dagangan atau jenis lain yang diberikan atau disahkan oleh TradingView. Baca lebih dalam Terma Penggunaan.
Skrip sumber terbuka
Dalam semangat TradingView sebenar, pencipta skrip ini telah menjadikannya sumber terbuka, jadi pedagang boleh menilai dan mengesahkan kefungsiannya. Terima kasih kepada penulis! Walaupuan anda boleh menggunakan secara percuma, ingat bahawa penerbitan semula kod ini tertakluk kepada Peraturan Dalaman.
Penafian
Maklumat dan penerbitan adalah tidak bertujuan, dan tidak membentuk, nasihat atau cadangan kewangan, pelaburan, dagangan atau jenis lain yang diberikan atau disahkan oleh TradingView. Baca lebih dalam Terma Penggunaan.