OPEN-SOURCE SCRIPT
Deviation Lens [JOAT]

Deviation Lens [JOAT]
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:
Pine Script®
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%:
Pine Script®
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:
Pine Script®
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:
Pine Script®
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
Input Parameters
Z-Score Settings:
Dimension Weights:
Divergence:
Display:
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
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:
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
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[divLook] and priceZ < priceZ[divLook] // Price up, Z down = bull div
bearDiv = close < close[divLook] and priceZ > priceZ[divLook] // 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
Script open-source
Dans l'esprit TradingView, le créateur de ce script l'a rendu open source afin que les traders puissent examiner et vérifier ses fonctionnalités. Bravo à l'auteur! Bien que vous puissiez l'utiliser gratuitement, n'oubliez pas que la republication du code est soumise à nos Règles.
The AI Trading Ecosystem, Built to win trades 📈
Get Full Access 👇
jackofalltrades.vip 🌐
t.me/jackofalltradesvip 🃏
Get Full Access 👇
jackofalltrades.vip 🌐
t.me/jackofalltradesvip 🃏
Clause de non-responsabilité
Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.
Script open-source
Dans l'esprit TradingView, le créateur de ce script l'a rendu open source afin que les traders puissent examiner et vérifier ses fonctionnalités. Bravo à l'auteur! Bien que vous puissiez l'utiliser gratuitement, n'oubliez pas que la republication du code est soumise à nos Règles.
The AI Trading Ecosystem, Built to win trades 📈
Get Full Access 👇
jackofalltrades.vip 🌐
t.me/jackofalltradesvip 🃏
Get Full Access 👇
jackofalltrades.vip 🌐
t.me/jackofalltradesvip 🃏
Clause de non-responsabilité
Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.