Smart Divergence Engine [ChartNation]

═══════════════════════════════════════════
Smart Divergence Engine solves three critical problems that plague free RSI divergence indicators:
PROBLEM 1: REPAINTING DIVERGENCES
Most divergence scripts detect divergence in real-time as bars form. This causes signals to appear, disappear, and reappear unpredictably—making them unusable for alerts or systematic trading.
OUR SOLUTION: Pivot-Locked Detection
Smart Divergence Engine evaluates RSI at the exact bar where price structure confirms (rsi[pivotR]), not at the current bar. Once a divergence prints, it NEVER disappears. This is implemented via:
- Full swing confirmation (Pivot Left + Pivot Right bars must complete)
- RSI evaluation at historical bar: rsi[pivotR], not rsi[0]
- Divergence triggers AFTER structure lock, not during formation
Technical implementation: The script stores RSI values at confirmed pivot bars using var floats (lowRsiPrev, lowRsiCurr, highRsiPrev, highRsiCurr), then compares these locked values when new pivots confirm. This prevents any possibility of historical repaint.
PROBLEM 2: FALSE POSITIVE OVERLOAD
Divergence scripts trigger on ANY price-RSI mismatch, flooding charts with weak signals during choppy conditions. No filtering means traders must manually screen out noise.
OUR SOLUTION: Shark Fin Exhaustion Filter
Before any divergence can be considered actionable, Smart Divergence Engine requires RSI to demonstrate genuine momentum exhaustion through our proprietary "Shark Fin" detection:
Shark Fin Logic (Not Found in Free Scripts):
- RSI must pierce the outer volatility band by a configurable buffer (default 1.5 RSI points)
- RSI must re-enter the band with directional confirmation (positive slope for bullish, negative slope for bearish)
- Band width must exceed minimum standard deviation threshold (volatility qualification)
- Cooldown period enforced (default 25 bars) to prevent signal clustering
This multi-condition filter dramatically reduces false divergences by requiring RSI to physically demonstrate exhaustion BEFORE structure confirmation matters.
Technical implementation: The Shark Fin state machine uses boolean flags (bullFinForming, bearFinForming) to track when RSI is stretched beyond bands, then validates re-entry using ta.crossover(rsi, lower) / ta.crossunder(rsi, upper) with slope checks (ta.change(rsi) > 0 / < 0) and volatility gates (dev >= finMinDev).
PROBLEM 3: NO VOLATILITY CONTEXT
Divergence scripts use fixed RSI levels (30/70 or similar) that fail to adapt to changing market conditions. What's "overbought" in a low-volatility regime differs drastically from high-volatility conditions.
OUR SOLUTION: Adaptive Volatility Bands
Smart Divergence Engine calculates dynamic overbought/oversold zones using:
- 34-period SMA of RSI as basis
- 1.618 standard deviation multiplier (golden ratio expansion)
- Real-time band expansion/contraction based on RSI volatility
The bands provide three advantages:
- Shark Fin events only qualify when RSI breaches ADAPTIVE thresholds, not arbitrary fixed levels
- Band width (standard deviation) serves as volatility filter—narrow bands = low conviction moves get rejected
- 50-line midline provides regime context (above 50 = bullish bias, below 50 = bearish bias)
Technical implementation: basis = ta.sma(rsi, 34), dev = ta.stdev(rsi, 34), upper/lower = basis ± dev * 1.618. Shark Fin logic requires rsi < (lower - finBuffer) or rsi > (upper + finBuffer) to trigger, ensuring exhaustion is measured relative to CURRENT volatility, not historical constants.
═══════════════════════════════════════════
METHODOLOGY COMPARISON VS FREE ALTERNATIVES
═══════════════════════════════════════════
STANDARD DIVERGENCE SCRIPTS:
- Detection timing: Real-time (current bar)
- Historical stability: Repaints continuously
- Signal filtering: None or minimal
- Volatility adaptation: Fixed levels (30/70)
- Exhaustion confirmation: Not implemented
- Confirmation layers: 1 (divergence only)
- Alert reliability: Unreliable (signals disappear)
SMART DIVERGENCE ENGINE:
- Detection timing: Pivot-confirmed (rsi[pivotR])
- Historical stability: Locked at structure bar
- Signal filtering: Shark Fin + cooldown + stdev gate
- Volatility adaptation: Dynamic bands (34-SMA + 1.618σ)
- Exhaustion confirmation: Required via Shark Fin
- Confirmation layers: 3 (structure + exhaustion + volatility)
- Alert reliability: Stable (never repaints)
═══════════════════════════════════════════
TECHNICAL SPECIFICATIONS
═══════════════════════════════════════════
RSI ENGINE:
- Base calculation: ta.rsi(src, 14)
- Smoothing: ta.rma(rsiRaw, 2) — reduces whipsaw noise
- Source: Configurable (default close)
VOLATILITY BANDS:
- Basis: 34-period SMA of RSI
- Multiplier: 1.618 (golden ratio)
- Upper band: basis + (stdev * 1.618)
- Lower band: basis - (stdev * 1.618)
- Purpose: Creates adaptive overbought/oversold zones
DIVERGENCE DETECTION:
- Pivot confirmation: 10 left bars + 10 right bars (default)
- RSI evaluation: Locked at rsi[pivotR] (historical bar, never current)
- Bullish divergence: price lower low + RSI higher low
- Bearish divergence: price higher high + RSI lower high
- Rendering: Lines drawn between last two confirmed pivots with labels
SHARK FIN EXHAUSTION FILTER:
- Depth buffer: 1.5 RSI points (penetration threshold beyond band)
- Min band stdev: 1.0 (volatility qualification)
- Cooldown: 25 bars minimum between Shark Fin confirmations
- Slope validation: Requires ta.change(rsi) > 0 (bullish) or < 0 (bearish)
- State tracking: Boolean flags prevent premature confirmations
VISUAL CUSTOMIZATION:
- Beauty Mode: Six-layer gradient fill anchored at 50-line
- • Purple regime (above 50) with configurable opacity
- • Green regime (below 50) with configurable opacity
- • Gradient layers: 33%, 66%, 100% intensity
- Divergence lines: Glow effect (6px) + core line (3px), both configurable
- Shark Fin rendering: 20% fill between RSI and violated band (ephemeral)
- Labels: Compact "Bull"/"Bear" markers with dot indicators
═══════════════════════════════════════════
ALERT SYSTEM
═══════════════════════════════════════════
Four distinct alert conditions (configure once, fires on all intervals):
"RSI Shark Fin — Bullish"
- Triggers when: RSI re-enters lower band from below with slope + stdev + cooldown confirmation
- Use case: Momentum exhaustion at oversold extreme
- Reliability: No repaint (confirmation locked at re-entry bar)
- "RSI Shark Fin — Bearish"
- Triggers when: RSI re-enters upper band from above with slope + stdev + cooldown confirmation
- Use case: Momentum exhaustion at overbought extreme
Reliability: No repaint (confirmation locked at re-entry bar)
"Bullish Divergence (Panel)"
- Triggers when: Pivot-confirmed bullish divergence completes (price LL + RSI HL)
- Timing: Fires AFTER Pivot Right bars complete (delayed but stable)
- Reliability: Never repaints (divergence locked at rsi[pivotR])
"Bearish Divergence (Panel)"
- Triggers when: Pivot-confirmed bearish divergence completes (price HH + RSI LH)
- Timing: Fires AFTER Pivot Right bars complete (delayed but stable)
- Reliability: Never repaints (divergence locked at rsi[pivotR])
═══════════════════════════════════════════
TRADING IMPLEMENTATION
═══════════════════════════════════════════
CONFLUENCE FRAMEWORK:
Highest-probability setups occur when three conditions align:
Bullish Setup:
- Shark Fin confirms below lower band (exhaustion)
- Bullish divergence prints at pivot (structure)
- RSI reclaims 50 line (regime shift to bullish)
- → Entry consideration at next price structure (support, swing low)
Bearish Setup:
- Shark Fin confirms above upper band (exhaustion)
- Bearish divergence prints at pivot (structure)
- RSI loses 50 line (regime shift to bearish)
- → Entry consideration at next price structure (resistance, swing high)
TREND CONTEXT:
- Strong uptrends: Prioritize bullish divergence + lower band Shark Fins (buy dips)
- Strong downtrends: Prioritize bearish divergence + upper band Shark Fins (sell rallies)
- Range-bound markets: Use 50-line crossovers as additional confirmation filter
RISK MANAGEMENT:
Smart Divergence Engine provides CONTEXT, not entries:
- Wait for price confirmation (engulfing candle, rejection wick, structure break)
- Place stops below/above pivot structure that triggered divergence
- Size positions based on distance to invalidation level
- Divergence + Shark Fin = elevated probability, not certainty
═══════════════════════════════════════════
CONFIGURATION PARAMETERS
═══════════════════════════════════════════
RSI SETTINGS:
- RSI Length: 14 (default, standard momentum window)
- Price Source: close (configurable to any price source)
- Note: 2-period RMA smoothing is hardcoded (reduces noise)
VOLATILITY BAND SETTINGS:
- Band Length: 34 (SMA period for RSI basis)
- Band Multiplier: 1.618 (golden ratio, adjustable)
- Show Bands: Toggle visibility (true/false)
DIVERGENCE SETTINGS:
- Pivot Left: 10 bars (left-side swing confirmation)
- Pivot Right: 10 bars (right-side swing confirmation)
- Overbought Level: 68 (reference line, does not affect logic)
- Oversold Level: 32 (reference line, does not affect logic)
SHARK FIN SETTINGS:
- Fin Depth Buffer: 1.5 RSI points (penetration threshold)
- Min Band Stdev: 1.0 (volatility qualification gate)
- Min Bars Between Fins: 25 (cooldown period)
VISUAL SETTINGS (Beauty Mode):
Enable Beauty Mode: true/false (gradient rendering)
- Divergence Glow: true/false (glow effect on lines)
- Glow Width: 3-10 px (glow layer thickness)
- Main Line Width: 1-6 px (divergence core line)
- Top Color: Purple (configurable, above-50 regime)
- Bottom Color: Green (configurable, below-50 regime)
- Top Opacity: 0-100% (gradient base transparency)
- Bottom Opacity: 0-100% (gradient base transparency)
═══════════════════════════════════════════
PERFORMANCE & LIMITATIONS
═══════════════════════════════════════════
RESOURCE ALLOCATION:
- max_lines_count: 500 (divergence + Shark Fin lines)
- max_labels_count: 500 (divergence markers)
- max_bars_back: 500 (historical pivot lookback)
- Suitable for most timeframes; reduce limits if performance degrades on low-end devices
SIGNAL TIMING:
Divergences print AFTER Pivot Right bars complete. This is intentional:
- Delayed signals are more reliable than real-time signals
- Structure confirmation requires waiting for swing completion
- Users demanding instant signals should use free real-time divergence indicators
- Users demanding reliable signals that never disappear should use this
PANEL VS OVERLAY:
This is the panel version (overlay=false):
Renders in separate pane below price chart
RSI, bands, divergence lines, and Shark Fin fills appear in this pane
For price-chart annotations, use the companion overlay version (same logic, different rendering)
═══════════════════════════════════════════
This script implements proprietary methodology not available in regular community scripts:
REPAINTING-PROOF ARCHITECTURE
The pivot-locked detection system (rsi[pivotR] evaluation) is a non-trivial implementation that requires:
- State management across bars using var variables
- Historical RSI value storage at pivot confirmation
- Divergence comparison between stored values (not current bar)
- This architecture eliminates the #1 complaint with free divergence indicators: disappearing signals.
SHARK FIN EXHAUSTION LOGIC
The multi-condition state machine that validates momentum exhaustion is not found in free scripts:
- Penetration threshold (buffer beyond band)
- Directional slope confirmation on re-entry
- Volatility gate (minimum standard deviation)
- Cooldown enforcement (prevents clustering)
- This filter layer was developed through extensive backtesting to reduce false divergences during choppy conditions.
ADAPTIVE VOLATILITY FRAMEWORK
The dynamic band system (34-SMA + 1.618σ) provides context-aware overbought/oversold detection:
- Bands expand in volatile markets → signals adapt to conditions
- Bands contract in ranging markets → tighter detection thresholds
- 50-line regime framework → directional bias context
- This approach outperforms fixed-level systems (30/70) that ignore market context.
CONFLUENCE METHODOLOGY
The three-layer confirmation system (structure + exhaustion + volatility) was engineered to answer: "When is a divergence actually tradeable?" Free scripts detect divergence and stop there. Smart Divergence Engine asks: "Did RSI show exhaustion? Is volatility sufficient? Did structure confirm?"
This level of methodological depth—combined with repainting-proof architecture and professional-grade visual implementation—justifies closed-source protection and paid access.
═══════════════════════════════════════════
Smart Divergence Engine is engineered for traders who demand institutional-grade divergence detection without the noise, repainting, and false positives that plague free alternatives.
Access is restricted to maintain signal quality as methodology evolves.
Script sob convite
Somente usuários aprovados pelo autor podem acessar este script. Você precisará solicitar e obter permissão para usá-lo. Normalmente, essa permissão é concedida após o pagamento. Para obter mais detalhes, siga as instruções do autor abaixo ou entre em contato diretamente com chartnation.
A TradingView NÃO recomenda pagar ou usar um script, a menos que você confie totalmente em seu autor e entenda como ele funciona. Você também pode encontrar alternativas gratuitas e de código aberto em nossos scripts da comunidade.
Instruções do autor
Aviso legal
Script sob convite
Somente usuários aprovados pelo autor podem acessar este script. Você precisará solicitar e obter permissão para usá-lo. Normalmente, essa permissão é concedida após o pagamento. Para obter mais detalhes, siga as instruções do autor abaixo ou entre em contato diretamente com chartnation.
A TradingView NÃO recomenda pagar ou usar um script, a menos que você confie totalmente em seu autor e entenda como ele funciona. Você também pode encontrar alternativas gratuitas e de código aberto em nossos scripts da comunidade.