Deviation Lens [JOAT]Deviation Lens
Introduction
Deviation Lens is an open-source multi-dimensional statistical displacement tool that applies Z-Score analysis simultaneously to three market dimensions: price level, close-to-close price change, and volume. Rather than using arbitrary overbought/oversold thresholds derived from historical maxima and minima, Deviation Lens computes exactly how many standard deviations each dimension is from its recent rolling mean. This provides a precise, adaptive, distribution-aware measure of how statistically extreme current market conditions are.
The core insight is that markets are mean-reverting systems over short time horizons. Statistical extremes — conditions where price, momentum, or volume are far from their recent averages — represent transient states. The further from the mean, the greater the statistical probability that conditions will normalize. Deviation Lens quantifies this probability directly, from 0% (at the mean) to 99.7% (at three standard deviations), and displays it as a live reversal probability for every bar.
Core Concepts
1. Three-Dimensional Z-Score Calculation
Three independent Z-Scores are computed on every bar:
The Price Z-Score measures how far the current close is from the rolling mean close in standard deviation units. This captures whether the current price level is statistically cheap or expensive relative to recent history.
The Change Z-Score measures how far the current bar's close-to-close price change is from the rolling mean change — quantifying momentum extremity rather than price level extremity.
The Volume Z-Score measures how far the current volume is from the rolling mean volume. High-volume Z-Score values identify bars where unusual institutional participation is statistically evident:
priceZ = priceStd > 0 ? (close - priceMean) / priceStd : 0.0
changeZ = changeStd > 0 ? (chg - changeMean) / changeStd : 0.0
volumeZ = volStd > 0 ? (volume - volMean) / volStd : 0.0
2. Reversal Probability Mapping
The absolute Z-Score is mapped to a reversal probability percentage based on the properties of the normal distribution. A Z-Score of 1.0 corresponds to 68.3% of values lying within one standard deviation — meaning only 31.7% of readings exceed this level, implying a 68.3% probability of mean reversion. A Z-Score of 2.0 corresponds to 95.4%, and 3.0 to 99.7%:
calcRevProb(float z) =>
float absZ = math.abs(z)
absZ >= 3.0 ? 99.7 : absZ >= 2.5 ? 98.8 : absZ >= 2.0 ? 95.4 : absZ >= 1.5 ? 86.6 : absZ >= 1.0 ? 68.3 : absZ >= 0.5 ? 38.3 : 0.0
This probability is displayed in the dashboard alongside the live Z-Score value, giving the trader both the raw statistical reading and its corresponding reversal likelihood.
3. Composite Z-Score and Zone Classification
The three individual Z-Scores are combined into a composite score using configurable weights for each dimension. The composite is then classified into a zone: EXTREME (above the configurable extreme threshold), ELEVATED, NEUTRAL, or the opposing directional equivalents. Zone classification determines the dashboard color coding and alert triggers:
composite = (priceZ * wPrice + changeZ * wChange + volumeZ * wVolume) / totalWeight
4. Divergence and Hidden Divergence Detection
Deviation Lens monitors for two divergence conditions. Standard divergence occurs when the Z-Score direction disagrees with the price direction — price makes a higher high but the Z-Score makes a lower high (bearish divergence), or price makes a lower low but the Z-Score makes a higher low (bullish divergence). Hidden divergence occurs when the Z-Score makes an extreme move while price action is relatively contained — a potential continuation pattern. Divergence events are labeled directly on the chart with bold, clearly sized labels:
bullDiv = close > close and priceZ < priceZ // Price up, Z down = bull div
bearDiv = close < close and priceZ > priceZ // Price down, Z up = bear div
Labels: BULL DIV, BEAR DIV (size.small), H.BULL, H.BEAR (size.tiny for hidden divergence).
5. Multi-Dimensional Dashboard
The institutional dashboard presents all three Z-Scores, the composite Z-Score, current zone classification, reversal probability, and divergence status simultaneously. The layout is designed so the most actionable information — Zone and Rev. Probability — is displayed at the largest text size, with supporting metrics at smaller sizes.
Features
Three independent Z-Scores: Price level, price change (momentum), and volume — each computed on its own rolling mean and standard deviation
Configurable Z-Score weights: The composite score uses adjustable per-dimension weights allowing emphasis on price, momentum, or volume depending on trading context
Live reversal probability: Probability percentage mapped directly from the Z-Score using normal distribution properties (68.3% at 1σ through 99.7% at 3σ)
Zone classification: Composite Z-Score classified as Extreme, Elevated, or Neutral in both directions with color-coded dashboard display
Divergence labels (BULL DIV / BEAR DIV): Z-Score vs price direction disagreement labeled on-chart at size.small
Hidden divergence labels (H.BULL / H.BEAR): Z-Score extreme with contained price action labeled at size.tiny
Configurable extreme and elevated thresholds: Both Z-Score thresholds independently adjustable
Institutional dashboard (top right): 14-row table with Price Z, Change Z, Volume Z, Composite Z, Zone, Reversal Probability, and divergence status
Adaptive thresholds: All calculations normalize to the rolling lookback period, adapting to current instrument and timeframe volatility
Alerts: Separate alertconditions for extreme bull and extreme bear composite Z-Score readings
Input Parameters
Z-Score Settings:
Z-Score Length: Rolling window for all three Z-Score calculations (default: 20)
Extreme Threshold: Z-Score magnitude classified as Extreme zone (default: 2.0)
Elevated Threshold: Z-Score magnitude classified as Elevated zone (default: 1.0)
Dimension Weights:
Price Weight: Relative weight of the price Z-Score in composite (default: 1.0)
Change Weight: Relative weight of the momentum Z-Score in composite (default: 1.0)
Volume Weight: Relative weight of the volume Z-Score in composite (default: 0.5)
Divergence:
Divergence Lookback: Bars back for divergence comparison (default: 5)
Show Divergence Labels toggle
Display:
Show Dashboard toggle
Bull and Bear color inputs
How to Use This Indicator
Step 1: Read the Composite Zone
The Zone row in the dashboard shows the current composite Z-Score classification. EXTREME readings at the top of the scale indicate the highest statistical probability of mean reversion. NEUTRAL readings indicate current conditions are close to the mean and have low statistical directional edge from this tool alone.
Step 2: Check Reversal Probability
The Rev. Probability row translates the Z-Score magnitude directly into a percentage. A reading above 95% means the current composite Z-Score is in the outer 5% of its historical distribution — a statistical extreme that has preceded mean reversion 95% of the time in the measured period.
Step 3: Assess Each Dimension Independently
The three individual Z-Score rows reveal which dimension is driving the composite. A high composite driven entirely by volume Z-Score is a different setup than one driven by price Z-Score. Understanding which dimension is extreme helps filter entries: a price Z-Score extreme without supporting momentum or volume Z-Score extremes may be a lower-conviction reading.
Step 4: React to Divergence Labels
BULL DIV and BEAR DIV labels appear when Z-Score momentum diverges from price direction. These signal that the statistical driver of a move is weakening even as price continues. H.BULL and H.BEAR hidden divergence labels flag potential continuation setups where Z-Score is extreme but price is not.
Step 5: Combine with Structural Context
Deviation Lens produces the highest value when its extreme readings coincide with a structural confluence point — an order block, session low, or structure level. A 99.7% reversal probability at a tested support zone is a higher-conviction setup than the same reading in open air.
Indicator Limitations
All Z-Scores are computed relative to the rolling lookback window. The lookback defines what "normal" means. A very short lookback will produce extreme readings frequently; a very long lookback will rarely reach the extreme threshold. Calibration to the instrument and timeframe is required
The reversal probability percentages are derived from the normal distribution assumption. Price change and volume distributions are not perfectly normal — they exhibit fat tails and skew. The probabilities are approximations, not precise statistical guarantees
The composite Z-Score uses equal weights by default. Changing dimension weights significantly alters which market conditions produce extreme readings. Weight adjustments should be based on the specific instrument's characteristics
Divergence detection uses a simple lookback comparison, not a peak-detection algorithm. In choppy markets, divergence labels may appear frequently without providing actionable signals
Originality Statement
Deviation Lens is original in its simultaneous, weighted multi-dimensional Z-Score framework that maps composite statistical extremity directly to a reversal probability percentage. This indicator is published because:
Applying Z-Score analysis to three independent market dimensions simultaneously — price level, momentum (close-to-close change), and volume — rather than a single oscillator provides a richer statistical picture of current market extremity than any single-dimension Z-Score tool
The direct mapping of Z-Score magnitude to reversal probability percentages using normal distribution properties gives traders an immediately interpretable statistic rather than a raw number requiring subjective interpretation
The composite weighted Z-Score system, where each dimension's contribution to the overall reading is configurable, allows the indicator to be tuned toward price-mean-reversion strategies, momentum exhaustion strategies, or volume anomaly detection depending on the trader's methodology
The combined detection of standard divergence and hidden divergence between the Z-Score and price direction provides trend continuation and reversal signals from the same framework
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Z-Score readings and reversal probability percentages are statistical tools based on historical distributions and do not guarantee any future price behavior. The normal distribution assumption applied to price and volume data is an approximation. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicateur

Oscillator Confluence Tracker [JOAT]Oscillator Confluence Tracker
Introduction
The Oscillator Confluence Tracker is an advanced open-source multi-oscillator divergence detection indicator that combines RSI divergence analysis, MACD momentum tracking, Stochastic extreme identification, volume divergence detection, and pattern recognition into a unified smart money divergence system. This indicator helps traders identify when price and momentum are moving in opposite directions - a powerful signal that the current trend is losing strength and a reversal may be imminent.
Unlike basic oscillator indicators that simply show overbought/oversold levels, this system detects divergences across multiple oscillators simultaneously and quantifies confluence. Regular divergences signal potential reversals, hidden divergences signal trend continuation, and multi-oscillator confluence provides the highest probability setups. The indicator is designed for traders who understand that divergences reveal institutional positioning changes before they're visible in price action.
Why This Indicator Exists
This indicator addresses a critical challenge in divergence trading: single oscillator divergences produce many false signals. By combining multiple oscillators and requiring confluence, this indicator reveals:
RSI Divergence Detection: Identifies when price makes new highs/lows but RSI doesn't - signals momentum exhaustion
MACD Momentum Analysis: Tracks MACD line and histogram for momentum shifts and crossovers
Stochastic Extreme Zones: Identifies overbought (>80) and oversold (<20) conditions for context
Hidden Divergence Patterns: Detects hidden divergences that signal trend continuation rather than reversal
Volume Divergence: Identifies when price makes new highs/lows on decreasing volume - warns of weak moves
Multi-Oscillator Confluence: Quantifies how many oscillators show divergence simultaneously
Momentum Divergence: Detects when price momentum and oscillator momentum conflict
Each component provides a different lens on momentum. RSI shows relative strength, MACD shows trend momentum, Stochastic shows extremes, volume shows participation, and confluence shows conviction. Together, they create a comprehensive view of smart money divergence.
Core Components Explained
1. Regular Bearish Divergence (Price HH, RSI LH)
Regular bearish divergence occurs when price makes a higher high but RSI makes a lower high - signals uptrend exhaustion:
// Detect pivot highs in both price and RSI
pricePivotHigh = ta.pivothigh(high, 5, 5)
rsiPivotHigh = ta.pivothigh(rsi, 5, 5)
// Compare current pivot to previous pivot
if pricePivotHigh > lastPriceHigh and rsiPivotHigh < lastRsiHigh:
// Bearish divergence detected
drawDivergenceLines()
createDivergenceLabel("BEAR DIV")
The indicator identifies bearish divergence by:
Tracking swing highs in both price and RSI using pivot detection
Comparing current swing high to previous swing high
Confirming price made higher high while RSI made lower high
Drawing solid line on price chart and dashed line on RSI
Creating "BEAR DIV" label at the divergence point
Bearish divergence is most powerful when:
RSI is in overbought zone (>70) - "BEAR DIV EXTREME" label
Multiple oscillators show divergence simultaneously
Volume is decreasing on the higher high
Occurs at resistance or Fibonacci level
2. Regular Bullish Divergence (Price LL, RSI HL)
Regular bullish divergence occurs when price makes a lower low but RSI makes a higher low - signals downtrend exhaustion:
// Detect pivot lows in both price and RSI
pricePivotLow = ta.pivotlow(low, 5, 5)
rsiPivotLow = ta.pivotlow(rsi, 5, 5)
// Compare current pivot to previous pivot
if pricePivotLow < lastPriceLow and rsiPivotLow > lastRsiLow:
// Bullish divergence detected
drawDivergenceLines()
createDivergenceLabel("BULL DIV")
The indicator identifies bullish divergence by:
Tracking swing lows in both price and RSI
Comparing current swing low to previous swing low
Confirming price made lower low while RSI made higher low
Drawing solid line on price chart and dashed line on RSI
Creating "BULL DIV" label at the divergence point
Bullish divergence is most powerful when:
RSI is in oversold zone (<30) - "BULL DIV EXTREME" label
Multiple oscillators show divergence simultaneously
Volume is decreasing on the lower low
Occurs at support or Fibonacci level
3. Hidden Bullish Divergence (Price HL, MACD LL)
Hidden bullish divergence occurs when price makes a higher low but MACD makes a lower low - signals uptrend continuation:
// Price makes higher low (bullish structure)
if pricePivotLow > lastPriceLow and macdPivotLow < lastMacdLow:
// Hidden bullish divergence - trend continuation signal
drawHiddenDivergence("H-BULL")
Hidden divergences are different from regular divergences:
Signal trend continuation, not reversal
Occur during pullbacks in established trends
Show that momentum is building despite price correction
Drawn with dotted lines to distinguish from regular divergence
Labeled "H-BULL" or "H-BEAR" for clarity
Hidden divergences are powerful for:
Entering pullbacks in strong trends
Adding to winning positions
Confirming trend strength
Identifying optimal re-entry points
4. Volume Divergence Detection
Volume divergence occurs when price makes new highs/lows but volume decreases - warns of weak moves:
// Track volume at pivot highs
volPivotHigh = ta.pivothigh(volume, 5, 5)
// Price makes higher high, volume makes lower high
if pricePivotHigh > lastPriceHigh and volPivotHigh < lastVolHigh:
label.new(bar_index, high, "VOL DIV", color=COLOR_VOL_DIV)
Volume divergence reveals:
Decreasing participation in the move
Lack of institutional conviction
Potential exhaustion or trap
Warning that trend may not continue
Volume divergence combined with RSI/MACD divergence creates extremely high-probability reversal setups.
5. Momentum Divergence Analysis
Momentum divergence occurs when price momentum and oscillator momentum move in opposite directions:
rsiMomentum = ta.change(rsi, 5)
macdMomentum = ta.change(macdLine, 5)
priceMomentum = ta.change(close, 5)
// Price momentum positive but RSI momentum negative
momentumDivergence = (priceMomentum > 0 and rsiMomentum < 0) or
(priceMomentum < 0 and rsiMomentum > 0)
Momentum divergence shows:
Acceleration/deceleration conflicts
Early warning of trend changes
Momentum exhaustion before price exhaustion
Institutional positioning shifts
The dashboard displays momentum divergence status (Active/Aligned) with color coding.
6. Multi-Oscillator Confluence Scoring
The indicator quantifies confluence by counting how many oscillators show divergence simultaneously:
confluenceScore = 0
if rsi_divergence:
confluenceScore += 1
if macd_divergence:
confluenceScore += 1
if stochastic_extreme:
confluenceScore += 1
if volume_divergence:
confluenceScore += 1
if momentum_divergence:
confluenceScore += 1
// Classify confluence
confluenceLevel = confluenceScore >= 4 ? "EXTREME BULL/BEAR" :
confluenceScore >= 3 ? "STRONG BULL/BEAR" :
confluenceScore >= 2 ? "MODERATE" : "NONE"
Confluence scoring reveals:
Setup quality (higher score = higher probability)
How many independent signals confirm the divergence
Whether to take the trade (3+ recommended)
Position sizing guidance (higher score = larger size)
The dashboard displays confluence score and classification with color intensity.
7. Enhanced Candlestick Coloring
The indicator colors candles based on trend strength and momentum:
// Determine trend
trendStrength = ta.ema(close, 20)
isBullTrend = close > trendStrength
isBearTrend = close < trendStrength
// Momentum strength
momentumStrong = abs(rsiMomentum) > 5 or abs(macdMomentum) > abs(macdHist) * 0.5
// Color candles
if isBullTrend:
candleColor = momentumStrong ? COLOR_BULL_STRONG : COLOR_BULL_WEAK
else if isBearTrend:
candleColor = momentumStrong ? COLOR_BEAR_STRONG : COLOR_BEAR_WEAK
Candlestick coloring shows:
Bright green: Strong bullish momentum
Light green: Weak bullish momentum
Bright red: Strong bearish momentum
Light red: Weak bearish momentum
This provides instant visual feedback on trend and momentum strength.
Visual Elements
Divergence Lines: Solid lines on price, dashed lines on oscillator connecting pivot points
Divergence Labels: "BULL DIV", "BEAR DIV", "H-BULL", "H-BEAR" at divergence points
Extreme Labels: "BULL DIV EXTREME" or "BEAR DIV EXTREME" in overbought/oversold zones
Volume Labels: "VOL DIV" markers when volume diverges
Divergence Zones: Semi-transparent boxes highlighting divergence areas
Enhanced Candles: Color-coded by trend and momentum strength
Volume Spike Boxes: Gold boxes around high-volume candles
Extreme Zone Backgrounds: Red tint when RSI >70 and Stochastic >80, green tint when RSI <30 and Stochastic <20
Dashboard: Real-time oscillator states and confluence metrics
The dashboard displays 9 key metrics:
1. RSI State (value and Overbought/Oversold/Neutral)
2. MACD Flow (Bullish/Bearish and Strong/Weak)
3. Stochastic (value and Extreme/Normal)
4. Momentum Div (Active/Aligned)
5. Volume Profile (ratio and Spike/Elevated/Low)
6. Trend Strength (Bullish/Bearish and Strong/Weak)
7. Confluence (Extreme/Strong/Moderate/None)
8. Signal Quality (Elite Setup/Strong Setup/Moderate/Weak)
Input Parameters
Oscillator Settings:
RSI Period: Length for RSI calculation (default: 14)
MACD Fast: Fast EMA for MACD (default: 12)
MACD Slow: Slow EMA for MACD (default: 26)
MACD Signal: Signal line period (default: 9)
Stochastic Period: Length for Stochastic calculation (default: 14)
Divergence Detection:
Pivot Detection: Lookback for swing detection (default: 5)
Regular Divergence: Enable/disable regular divergence detection
Hidden Divergence: Enable/disable hidden divergence detection
Multi-Oscillator Confluence: Require multiple oscillators
Extreme Zones Only: Only detect divergences in overbought/oversold
Volume Analysis:
Volume Analysis Period: Length for volume average (default: 20)
Volume Divergence: Enable/disable volume divergence detection
Volume Spike Threshold: Multiplier for spike detection (default: 1.5x)
How to Use This Indicator
Step 1: Monitor RSI State
Check dashboard for RSI level. Divergences in extreme zones (>70 or <30) are most powerful. Wait for extremes for best setups.
Step 2: Watch for Divergence Labels
When "BULL DIV" or "BEAR DIV" labels appear, divergence is detected. "EXTREME" suffix means it's in overbought/oversold - highest probability.
Step 3: Check Confluence Score
Dashboard shows confluence level. "EXTREME" or "STRONG" = multiple oscillators confirming. Only trade 3+ confluence setups.
Step 4: Confirm with Volume
Look for "VOL DIV" labels. Volume divergence + oscillator divergence = very high probability. Volume confirms the divergence.
Step 5: Assess Signal Quality [/b>
Dashboard shows "ELITE SETUP" when momentum divergence + extreme RSI/Stochastic + high confluence. "STRONG SETUP" for good setups. Only trade Elite and Strong.
Step 6: Use Hidden Divergence for Continuation
"H-BULL" or "H-BEAR" labels signal trend continuation. Enter pullbacks in strong trends when hidden divergence appears.
Step 7: Monitor Trend Strength Best Practices
Divergences in extreme zones (RSI >70 or <30) are most reliable
Multi-oscillator confluence (3+) significantly increases win rate
Volume divergence adds powerful confirmation
Hidden divergences are for trend continuation, not reversal
Regular divergences are for reversal, not continuation
Momentum divergence provides early warning before price divergence
Extreme zone backgrounds (red/green tint) show best divergence areas
Enhanced candle colors show when momentum is weakening
Confluence score guides position sizing (higher = larger)
Signal quality in dashboard filters low-probability setups
Indicator Limitations
Divergences can persist for extended periods before reversing
Not all divergences result in reversals - some fail
Strong trends can produce multiple divergences before reversing
Hidden divergences require established trend context
Volume divergence less reliable on low-volume instruments
Pivot detection requires sufficient volatility
Multiple divergences in short period may signal consolidation
The indicator shows momentum conflicts, not guaranteed reversals
Extreme zones can remain extreme longer than expected
Technical Implementation
Built with Pine Script v6 using:
RSI divergence detection with pivot comparison
MACD momentum analysis with histogram tracking
Stochastic extreme zone identification
Volume divergence detection with pivot tracking
Momentum divergence calculations (rate-of-change)
Multi-oscillator confluence scoring system
Enhanced candlestick coloring based on trend and momentum
Volume spike detection with box visualization
Extreme zone background gradients
Real-time dashboard with 9 divergence metrics
The code is fully open-source and can be modified to suit individual trading styles and preferences.
Originality Statement
This indicator is original in its comprehensive divergence integration approach. While individual components (RSI, MACD, Stochastic, volume) are established concepts, this indicator is justified because:
It synthesizes multiple oscillator divergence detection into unified confluence scoring
The multi-oscillator confluence system quantifies setup quality across independent signals
Hidden divergence detection distinguishes continuation from reversal patterns
Volume divergence integration adds participation confirmation layer
Momentum divergence analysis provides early warning system
Enhanced candlestick coloring shows trend and momentum strength visually
Signal quality classification (Elite/Strong/Moderate/Weak) filters setups
Extreme zone backgrounds highlight optimal divergence areas
Real-time dashboard presents 9 metrics simultaneously for holistic divergence analysis
Each component contributes unique information: RSI shows relative strength, MACD shows momentum, Stochastic shows extremes, volume shows participation, momentum shows acceleration, confluence shows conviction, and quality shows probability. The indicator's value lies in presenting these complementary perspectives simultaneously with unified classification and actionable trade signals.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss and is not suitable for all investors.
Divergence analysis is a tool for identifying potential reversals and continuations, not a crystal ball for predicting future price movement. Divergences do not guarantee reversals. Confluence does not guarantee success. Past divergence patterns do not guarantee future divergence patterns. Market conditions change, and strategies that worked historically may not work in the future.
The divergences displayed are analytical constructs based on current market data, not predictions of future price movement. High confluence scores do not guarantee profitable trades. Users must conduct their own analysis and risk assessment before making trading decisions.
Always use proper risk management, including stop losses and position sizing appropriate for your account size and risk tolerance. Never risk more than you can afford to lose. Consider consulting with a qualified financial advisor before making investment decisions.
The author is not responsible for any losses incurred from using this indicator. Users assume full responsibility for all trading decisions made using this tool.
-Made with passion by officialjackofalltrades Indicateur

Stratégie
