Smart Divergence Engine Overlay [ChartNation]

═══════════════════════════════════════════
TECHNICAL OVERVIEW
═══════════════════════════════════════════
Smart Divergence Engine Overlay renders pivot-confirmed RSI divergences directly on the price chart with candle-anchored lines and labels. This companion overlay shares the identical detection logic as the panel version but visualizes signals at their exact price levels rather than in oscillator space.
The overlay implements repainting-proof divergence detection through pivot-locked RSI evaluation at historical bars (rsi[pivotR]), ensuring all lines and labels remain stable as new bars form. Visual elements anchor to xloc.bar_index coordinates, maintaining precise positioning across zoom levels and timeframe changes.
═══════════════════════════════════════════
CORE ARCHITECTURE
═══════════════════════════════════════════
PIVOT-LOCKED DETECTION SYSTEM
The overlay evaluates RSI at confirmed pivot bars, not at the current bar:
Technical implementation:
Price pivots detected via ta.pivotlow() / ta.pivothigh() with configurable Left/Right parameters
RSI value captured at the pivot bar: rsi[pivotR] (historical bar offset)
Divergence comparison performed between stored pivot values (lowRsiPrev vs lowRsiCurr)
State management via var floats prevents recalculation across bars
Result: Once a divergence line prints, it never moves or disappears. Historical stability is guaranteed because RSI evaluation occurs at a locked bar index (bar_index - pivotR), not at the moving present.
Bullish divergence logic:
if not na(lowPricePrev) and lowPriceCurr < lowPricePrev and lowRsiCurr > lowRsiPrev
→ Price made lower low, RSI made higher low
→ Divergence confirmed at lowIdxCurr (pivot bar index)
Bearish divergence logic:
if not na(highPricePrev) and highPriceCurr > highPricePrev and highRsiCurr < highRsiPrev
→ Price made higher high, RSI made lower high
→ Divergence confirmed at highIdxCurr (pivot bar index)
RSI ENGINE
The overlay uses the same RSI calculation as the panel version to ensure signal synchronization:
- Base calculation: ta.rsi(src, 14) — standard RSI momentum window
- Smoothing layer: ta.rma(rsiRaw, 2) — reduces high-frequency noise
- Volatility bands: 34-period SMA basis with 1.618 standard deviation multiplier
- Purpose: Bands define adaptive overbought/oversold context (not plotted on overlay)
The volatility framework exists in the calculation layer to maintain logic parity with the panel version, ensuring divergences trigger at identical bars across both implementations.
CANDLE-ANCHORED RENDERING
All visual elements use xloc.bar_index positioning:
Line rendering:
line.new(x1=lowIdxPrev, y1=lowPricePrev, x2=lowIdxCurr, y2=lowPriceCurr,
xloc=xloc.bar_index, color=bullCol, width=lineW)
This anchors lines to specific bar indices and price levels, not to time coordinates. Result: Lines maintain exact positioning when zooming, panning, or switching timeframes.
Label rendering:
label.new(x=lowIdxCurr, y=lowPriceCurr, text="BUY",
xloc=xloc.bar_index, style=label.style_label_up)
Labels attach to the second pivot's bar index and price level, scaling naturally with chart transformations.
═══════════════════════════════════════════
VISUAL IMPLEMENTATION
═══════════════════════════════════════════
DIVERGENCE LINES
Bullish divergence: Connects two price swing lows with upward-sloping line
- Color: Configurable (default lime green)
- Width: 1-6 pixels (configurable)
- Endpoint 1: Previous swing low (lowPricePrev at lowIdxPrev)
- Endpoint 2: Current swing low (lowPriceCurr at lowIdxCurr)
- Requirement: Current price lower than previous, current RSI higher than previous
Bearish divergence: Connects two price swing highs with downward-sloping line
- Color: Configurable (default red)
- Width: 1-6 pixels (configurable)
- Endpoint 1: Previous swing high (highPricePrev at highIdxPrev)
- Endpoint 2: Current swing high (highPriceCurr at highIdxCurr)
- Requirement: Current price higher than previous, current RSI lower than previous
Lines extend between pivot bars only (extend.none), never projecting into future.
DIVERGENCE LABELS
Optional BUY/SELL markers render at the second pivot:
BUY label (bullish divergence):
Position: Below current swing low (label.style_label_up)
Text: "BUY"
Color: Matches bullish line color
Size: Normal (size.normal)
SELL label (bearish divergence):
Position: Above current swing high (label.style_label_down)
Text: "SELL"
Color: Matches bearish line color
Size: Normal (size.normal)
Labels can be toggled independently of lines via showLabels input.
═══════════════════════════════════════════
CONFIGURATION PARAMETERS
═══════════════════════════════════════════
RSI CALCULATION SETTINGS:
- Price Source: close (configurable to any price field)
- RSI Length: 14 (standard momentum window)
- Volatility Band Length: 34 (SMA period for RSI basis)
- Band Multiplier: 1.618 (standard deviation expansion)
- Note: Bands calculate internally but don't plot (logic parity with panel)
DIVERGENCE DETECTION SETTINGS:
- Pivot Left: 10 bars (left-side swing confirmation)
- Pivot Right: 10 bars (right-side swing confirmation)
- Overbought Level: 68 (reference, does not affect logic)
- Oversold Level: 32 (reference, does not affect logic)
Pivot parameters control strictness:
- Higher values = fewer, more significant divergences (requires wider swings)
- Lower values = more frequent divergences (detects smaller swings)
VISUAL SETTINGS:
- Show Divergence Lines: true/false toggle
- Show BUY/SELL Labels: true/false toggle (independent of lines)
- Line Width: 1-6 pixels
- Bull Color: Configurable (default lime green)
- Bear Color: Configurable (default red)
═══════════════════════════════════════════
ALERT SYSTEM
═══════════════════════════════════════════
Two alert conditions trigger at identical timing as visual signals:
"Bullish Divergence (Overlay)"
Triggers when: Bullish divergence confirms at second pivot
Timing: Fires AFTER Pivot Right bars complete (delayed but stable)
Message: "TDI: Bullish divergence"
Reliability: Never repaints (confirmation locked at rsi[pivotR])
"Bearish Divergence (Overlay)"
Triggers when: Bearish divergence confirms at second pivot
Timing: Fires AFTER Pivot Right bars complete (delayed but stable)
Message: "TDI: Bearish divergence"
Reliability: Never repaints (confirmation locked at rsi[pivotR])
Alert configuration:
Set once on any chart/timeframe
Fires only when divergence condition evaluates true
Synchronized with visual rendering (alert = line + label appear)
═══════════════════════════════════════════
TRADING IMPLEMENTATION
═══════════════════════════════════════════
VISUAL ANALYSIS WORKFLOW
The overlay provides direct price-level context for divergence signals:
Bullish divergence interpretation:
- Identify two connected swing lows with upward-sloping line
- Lower price low indicates selling pressure weakening
- Higher RSI low indicates momentum refusing to confirm price weakness
- BUY label marks the second swing low (divergence confirmation point)
Bearish divergence interpretation:
- Identify two connected swing highs with downward-sloping line
- Higher price high indicates buying pressure weakening
- Lower RSI high indicates momentum refusing to confirm price strength
- SELL label marks the second swing high (divergence confirmation point)
CONFLUENCE WITH PRICE STRUCTURE
Overlay enables direct correlation with chart elements:
Support/Resistance alignment:
- Bullish divergence at major support level = higher probability reversal
- Bearish divergence at major resistance level = higher probability reversal
- Divergence in middle of range = lower conviction signal
Volume confirmation:
- Divergence with decreasing volume = confirms momentum exhaustion
- Divergence with increasing volume = mixed signal, proceed with caution
Multi-timeframe context:
- Higher timeframe trend alignment increases signal reliability
- Counter-trend divergences (against HTF trend) require additional confirmation
ENTRY/EXIT FRAMEWORK
The overlay marks divergence confirmation points, not entry triggers:
Entry consideration process:
- Divergence line appears → structure-confirmed momentum divergence detected
- Wait for price confirmation (engulfing candle, break of structure, rejection wick)
- Validate with additional confluence (volume, support/resistance, HTF trend)
- Enter with predefined stop below/above divergence pivot
- Size position according to distance to invalidation level
Exit planning:
- Initial target: Previous swing high (bullish) / swing low (bearish)
- Trail stop: Move to breakeven after initial profit target
- Invalidation: Close below divergence low (bullish) / above divergence high (bearish)
═══════════════════════════════════════════
PANEL VS OVERLAY USAGE
═══════════════════════════════════════════
IDENTICAL DETECTION LOGIC
Both versions implement the same pivot-locked RSI evaluation:
- Same RSI calculation (14-length with 2-period RMA smoothing)
- Same volatility band framework (34-SMA + 1.618σ)
- Same pivot confirmation (10 Left + 10 Right)
- Same divergence comparison (rsi[pivotR] at locked bar indices)
Result: Divergences trigger at identical bars across both implementations.
RENDERING DIFFERENCES
Panel version (overlay=false):
- Renders in separate pane below price chart
- Displays RSI line, volatility bands, 50-line midline
- Divergence lines drawn in oscillator space (RSI value coordinates)
- Optional Shark Fin exhaustion visualization
- Labels positioned relative to RSI levels
Overlay version (overlay=true):
- Renders directly on price chart
- No RSI line or bands visible (calculate internally for logic only)
- Divergence lines drawn in price space (actual price coordinates)
- No Shark Fin visualization (price chart remains clean)
- Labels positioned at actual swing high/low prices
COMPLEMENTARY WORKFLOW
Recommended usage pattern:
- Panel version: Monitor RSI regime (above/below 50), band interactions, Shark Fin exhaustion
- Overlay version: Identify exact divergence price levels, correlate with support/resistance
- Combined analysis: Use panel for momentum context, overlay for entry/exit precision
Alternative workflow (overlay only):
- If RSI analysis not required, overlay version provides clean divergence detection
- Pair with external RSI indicator if separate momentum visualization needed
- Focuses chart space on price action and divergence markers only
═══════════════════════════════════════════
TECHNICAL SPECIFICATIONS
═══════════════════════════════════════════
RESOURCE ALLOCATION:
- max_lines_count: 500 (divergence connector lines)
- max_labels_count: 500 (BUY/SELL markers)
- Suitable for most chart configurations and timeframes
RENDERING STABILITY:
- xloc.bar_index positioning ensures visual stability across zoom/pan operations
- Historical divergences never move once printed
- Lines and labels scale proportionally with chart transformations
TIMEFRAME COMPATIBILITY:
- Functions on any timeframe (1m to 1M)
- Pivot detection adapts to bar spacing automatically
- Lower timeframes generate more frequent signals (smaller swings)
- Higher timeframes generate fewer signals (larger swings)
SYMBOL COMPATIBILITY:
- Works on all asset classes (stocks, forex, crypto, futures, indices)
- No symbol-specific logic or calculations
- Universal RSI-based divergence detection
PERFORMANCE CHARACTERISTICS:
- Lightweight calculation overhead (RSI + pivot detection + state management)
- Visual rendering occurs only on divergence confirmation (not every bar)
- No continuous repainting or historical recalculation
═══════════════════════════════════════════
USE CASE SCENARIOS
═══════════════════════════════════════════
SCENARIO 1: Support/Resistance Divergence
Setup: Price tests major support level twice, second test makes lower low
Signal: Bullish divergence line appears, RSI makes higher low at support
Interpretation: Momentum refusing to confirm price weakness at critical level
Action: Consider long entry on next bullish candle above divergence low
SCENARIO 2: Trend Exhaustion
Setup: Strong uptrend, price makes new high but momentum slowing
Signal: Bearish divergence line appears, RSI makes lower high
Interpretation: Buying pressure weakening despite higher price high
Action: Consider profit-taking on longs, watch for reversal confirmation
SCENARIO 3: Range-Bound Reversal
Setup: Price oscillating in horizontal range, tests lower boundary
Signal: Bullish divergence at range support
Interpretation: Oversold bounce opportunity within defined range
Action: Long entry targeting range midpoint or upper boundary
SCENARIO 4: Failed Breakout
Setup: Price breaks resistance but momentum doesn't confirm
Signal: Bearish divergence forms immediately after breakout
Interpretation: Breakout lacks momentum conviction, likely false breakout
Action: Consider fade setup (short) with stop above divergence high
═══════════════════════════════════════════
LIMITATIONS & CONSIDERATIONS
═══════════════════════════════════════════
SIGNAL TIMING:
Divergences print AFTER Pivot Right bars complete. This delay is intentional:
- Ensures structure confirmation (full swing formation)
- Prevents real-time repaint issues
- Trades confirmation reliability for signal speed
Users requiring instant signals should use real-time divergence detectors (with repaint risk).
Users requiring reliable, stable signals should accept the confirmation delay.
LINE CLUTTER:
On lower timeframes with sensitive pivot settings:
High signal frequency may create visual clutter
Solution: Increase Pivot Left/Right values to filter smaller swings
Alternative: Use panel version for primary analysis, overlay for key divergences only
FALSE SIGNALS:
Divergences indicate momentum divergence, not guaranteed reversals:
- Strong trends can maintain divergent conditions for extended periods
- Divergence in isolation is a warning sign, not a trade trigger
- Requires confluence with price action, volume, structure for high-probability setups
VOLATILITY BAND CONTEXT:
Bands calculate internally but don't visualize on overlay:
- Users lose visual context of RSI overbought/oversold zones
- Solution: Use panel version alongside overlay for complete RSI regime awareness
- Alternative: Add separate RSI indicator to chart for band visualization
═══════════════════════════════════════════
Smart Divergence Engine Overlay provides candle-anchored, repainting-proof RSI divergence visualization directly on price charts. Lines and labels render at exact pivot price levels using xloc.bar_index positioning, maintaining stability across all chart transformations. Divergence detection uses pivot-locked RSI evaluation (rsi[pivotR]) to ensure historical signals never move or disappear.
The overlay shares identical detection logic with the panel version but renders in price space rather than oscillator space, enabling direct correlation with support/resistance levels and price structure. All visual elements trigger only after full pivot confirmation (Pivot Left + Pivot Right bars), trading signal speed for absolute reliability.
סקריפט להזמנה בלבד
רק משתמשים שאושרו על ידי המחבר יכולים לגשת לסקריפט הזה. יהיה עליך לשלוח בקשת גישה ולקבל אישור לשימוש. בדרך כלל, הגישה ניתנת לאחר תשלום. למידע נוסף, עקוב אחר ההוראות של היוצר בהמשך או צור קשר עם chartnation ישירות.
TradingView לא ממליצה לשלם עבור סקריפט או להשתמש בו אלא אם כן אתה סומך לחלוטין על המחבר שלו ומבין כיצד הוא פועל. ייתכן שתוכל גם למצוא חלופות חינמיות וקוד פתוח ב-סקריפטים הקהילתיים שלנו.
הוראות המחבר
כתב ויתור
סקריפט להזמנה בלבד
רק משתמשים שאושרו על ידי המחבר יכולים לגשת לסקריפט הזה. יהיה עליך לשלוח בקשת גישה ולקבל אישור לשימוש. בדרך כלל, הגישה ניתנת לאחר תשלום. למידע נוסף, עקוב אחר ההוראות של היוצר בהמשך או צור קשר עם chartnation ישירות.
TradingView לא ממליצה לשלם עבור סקריפט או להשתמש בו אלא אם כן אתה סומך לחלוטין על המחבר שלו ומבין כיצד הוא פועל. ייתכן שתוכל גם למצוא חלופות חינמיות וקוד פתוח ב-סקריפטים הקהילתיים שלנו.