OPEN-SOURCE SCRIPT
Adaptive Z-Score Oscillator [QuantAlgo]

🟢 Overview
The Adaptive Z-Score Oscillator transforms price action into statistical significance measurements by calculating how many standard deviations the current price deviates from its moving average baseline, then dynamically adjusting threshold levels based on historical distribution patterns. Unlike traditional oscillators that rely on fixed overbought/oversold levels, this indicator employs percentile-based adaptive thresholds that automatically calibrate to changing market volatility regimes and statistical characteristics. By offering both adaptive and fixed threshold modes alongside multiple moving average types and customizable smoothing, the indicator provides traders and investors with a robust framework for identifying extreme price deviations, mean reversion opportunities, and underlying trend conditions through the visualization of price behavior within a statistical distribution context.

🟢 How It Works
The indicator begins by establishing a dynamic baseline using a user-selected moving average type applied to closing prices over the specified length period, then calculates the standard deviation to measure price dispersion:
Pine Script®
The core Z-Score calculation quantifies how many standard deviations the current price sits above or below the moving average basis, creating a normalized oscillator that facilitates cross-asset and cross-timeframe comparisons:
Pine Script®
The adaptive threshold mechanism employs percentile calculations over a historical lookback period to determine statistically significant extreme zones. Rather than using fixed levels like ±2.0, the indicator identifies where a specified percentage of historical Z-Score readings have fallen, automatically adjusting to market regime changes:
Pine Script®
The visualization architecture creates a four-tier coloring system that distinguishes between extreme conditions (beyond the adaptive thresholds) and moderate conditions (between the midpoint and threshold levels), providing visual gradation of statistical significance through opacity variations and immediate recognition of distribution extremes.

🟢 How to Use This Indicator
▶ Overbought and Oversold Identification:
The indicator identifies potential overbought conditions when the smoothed Z-Score crosses above the upper threshold, indicating that price has deviated to a statistically extreme level above its mean. Conversely, oversold conditions emerge when the Z-Score crosses below the lower threshold, signaling statistically significant downward deviation. In adaptive mode (default), these thresholds automatically adjust to the asset's historical behavior, i.e., during high volatility periods, the thresholds expand to accommodate wider price swings, while during low volatility regimes, they contract to capture smaller deviations as significant. This dynamic calibration reduce false signals that plague fixed-level oscillators when market character shifts between volatile and ranging conditions.

▶ Mean Reversion Trading Applications:
The Z-Score framework excels at identifying mean reversion opportunities by highlighting when price has stretched too far from its statistical equilibrium. When the oscillator reaches extreme bearish levels (below the lower threshold with deep red coloring), it suggests price has become statistically oversold and may snap back toward the mean, presenting potential long entry opportunities for mean reversion traders. Symmetrically, extreme bullish readings (above the upper threshold with bright green coloring) indicate potential short opportunities or long exit points as price becomes statistically overbought. The moderate zones (lighter colors between midpoint and threshold) serve as early warning areas where traders can prepare for potential reversals, while exits from extreme zones (crossing back inside the thresholds) often provide confirmation that mean reversion is underway.

▶ Trend and Distribution Analysis:
Beyond discrete overbought/oversold signals, the histogram's color pattern and shape reveal the underlying trend structure and distribution characteristics. Sustained periods where the Z-Score oscillates primarily in positive territory (green bars) indicate a bullish trend where price consistently trades above its moving average baseline, even if not reaching extreme levels. Conversely, predominant negative readings (red bars) suggest bearish trend conditions. The distribution shape itself provides insight into market behavior, e.g., a narrow, centered distribution clustering near zero indicates tight ranging conditions with price respecting the mean, while a wide distribution with frequent extreme readings reveals volatile trending or choppy conditions. Asymmetric distributions skewed heavily toward one side demonstrate persistent directional bias, whereas balanced distributions suggest equilibrium between bulls and bears.

▶ Built-in Alerts:
Seven alert conditions enable automated monitoring of statistical extremes and trend transitions. Enter Overbought and Enter Oversold alerts trigger when the Z-Score crosses into extreme zones, providing early warnings of potential reversal setups. Exit Overbought and Exit Oversold alerts signal when price begins reverting from extremes, offering confirmation that mean reversion has initiated. Zero Cross Up and Zero Cross Down alerts identify transitions through the neutral line, indicating shifts between above-mean and below-mean price action that can signal trend changes. The Extreme Zone Entry alert fires on any extreme threshold penetration regardless of direction, allowing unified monitoring of both overbought and oversold opportunities.

▶ Color Customization:
Six visual themes (Classic, Aqua, Cosmic, Ember, Neon, plus Custom) accommodate different chart backgrounds and aesthetic preferences, ensuring optimal contrast and readability across trading platforms. The bar transparency control (0-90%) allows fine-tuning of visual prominence, with minimal transparency creating bold, attention-grabbing bars for primary analysis, while higher transparency values produce subtle background context when using the oscillator alongside other indicators. The extreme and moderate zone coloring system uses automatic opacity variation to create instant visual hierarchy, with darkest colors highlight the most statistically significant deviations demanding immediate attention, while lighter shades mark developing conditions that warrant monitoring but may not yet justify action. Optional candle coloring extends the Z-Score color scheme directly to the price candles on the main chart, enabling traders to instantly recognize statistical extremes and trend conditions without needing to reference the oscillator panel, creating a unified visual experience where both price action and statistical analysis share the same color language.






The Adaptive Z-Score Oscillator transforms price action into statistical significance measurements by calculating how many standard deviations the current price deviates from its moving average baseline, then dynamically adjusting threshold levels based on historical distribution patterns. Unlike traditional oscillators that rely on fixed overbought/oversold levels, this indicator employs percentile-based adaptive thresholds that automatically calibrate to changing market volatility regimes and statistical characteristics. By offering both adaptive and fixed threshold modes alongside multiple moving average types and customizable smoothing, the indicator provides traders and investors with a robust framework for identifying extreme price deviations, mean reversion opportunities, and underlying trend conditions through the visualization of price behavior within a statistical distribution context.
🟢 How It Works
The indicator begins by establishing a dynamic baseline using a user-selected moving average type applied to closing prices over the specified length period, then calculates the standard deviation to measure price dispersion:
basis = ma(close, length, maType)
stdev = ta.stdev(close, length)
The core Z-Score calculation quantifies how many standard deviations the current price sits above or below the moving average basis, creating a normalized oscillator that facilitates cross-asset and cross-timeframe comparisons:
zScore = stdev != 0 ? (close - basis) / stdev : 0
smoothedZ = ma(zScore, smooth, maType)
The adaptive threshold mechanism employs percentile calculations over a historical lookback period to determine statistically significant extreme zones. Rather than using fixed levels like ±2.0, the indicator identifies where a specified percentage of historical Z-Score readings have fallen, automatically adjusting to market regime changes:
upperThreshold = adaptive ? ta.percentile_linear_interpolation(smoothedZ, percentilePeriod, upperPercentile) : fixedUpper
lowerThreshold = adaptive ? ta.percentile_linear_interpolation(smoothedZ, percentilePeriod, lowerPercentile) : fixedLower
The visualization architecture creates a four-tier coloring system that distinguishes between extreme conditions (beyond the adaptive thresholds) and moderate conditions (between the midpoint and threshold levels), providing visual gradation of statistical significance through opacity variations and immediate recognition of distribution extremes.
🟢 How to Use This Indicator
▶ Overbought and Oversold Identification:
The indicator identifies potential overbought conditions when the smoothed Z-Score crosses above the upper threshold, indicating that price has deviated to a statistically extreme level above its mean. Conversely, oversold conditions emerge when the Z-Score crosses below the lower threshold, signaling statistically significant downward deviation. In adaptive mode (default), these thresholds automatically adjust to the asset's historical behavior, i.e., during high volatility periods, the thresholds expand to accommodate wider price swings, while during low volatility regimes, they contract to capture smaller deviations as significant. This dynamic calibration reduce false signals that plague fixed-level oscillators when market character shifts between volatile and ranging conditions.
▶ Mean Reversion Trading Applications:
The Z-Score framework excels at identifying mean reversion opportunities by highlighting when price has stretched too far from its statistical equilibrium. When the oscillator reaches extreme bearish levels (below the lower threshold with deep red coloring), it suggests price has become statistically oversold and may snap back toward the mean, presenting potential long entry opportunities for mean reversion traders. Symmetrically, extreme bullish readings (above the upper threshold with bright green coloring) indicate potential short opportunities or long exit points as price becomes statistically overbought. The moderate zones (lighter colors between midpoint and threshold) serve as early warning areas where traders can prepare for potential reversals, while exits from extreme zones (crossing back inside the thresholds) often provide confirmation that mean reversion is underway.
▶ Trend and Distribution Analysis:
Beyond discrete overbought/oversold signals, the histogram's color pattern and shape reveal the underlying trend structure and distribution characteristics. Sustained periods where the Z-Score oscillates primarily in positive territory (green bars) indicate a bullish trend where price consistently trades above its moving average baseline, even if not reaching extreme levels. Conversely, predominant negative readings (red bars) suggest bearish trend conditions. The distribution shape itself provides insight into market behavior, e.g., a narrow, centered distribution clustering near zero indicates tight ranging conditions with price respecting the mean, while a wide distribution with frequent extreme readings reveals volatile trending or choppy conditions. Asymmetric distributions skewed heavily toward one side demonstrate persistent directional bias, whereas balanced distributions suggest equilibrium between bulls and bears.
▶ Built-in Alerts:
Seven alert conditions enable automated monitoring of statistical extremes and trend transitions. Enter Overbought and Enter Oversold alerts trigger when the Z-Score crosses into extreme zones, providing early warnings of potential reversal setups. Exit Overbought and Exit Oversold alerts signal when price begins reverting from extremes, offering confirmation that mean reversion has initiated. Zero Cross Up and Zero Cross Down alerts identify transitions through the neutral line, indicating shifts between above-mean and below-mean price action that can signal trend changes. The Extreme Zone Entry alert fires on any extreme threshold penetration regardless of direction, allowing unified monitoring of both overbought and oversold opportunities.
▶ Color Customization:
Six visual themes (Classic, Aqua, Cosmic, Ember, Neon, plus Custom) accommodate different chart backgrounds and aesthetic preferences, ensuring optimal contrast and readability across trading platforms. The bar transparency control (0-90%) allows fine-tuning of visual prominence, with minimal transparency creating bold, attention-grabbing bars for primary analysis, while higher transparency values produce subtle background context when using the oscillator alongside other indicators. The extreme and moderate zone coloring system uses automatic opacity variation to create instant visual hierarchy, with darkest colors highlight the most statistically significant deviations demanding immediate attention, while lighter shades mark developing conditions that warrant monitoring but may not yet justify action. Optional candle coloring extends the Z-Score color scheme directly to the price candles on the main chart, enabling traders to instantly recognize statistical extremes and trend conditions without needing to reference the oscillator panel, creating a unified visual experience where both price action and statistical analysis share the same color language.
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
🎁🎄 Christmas SALE 50% Off with code XMAS50 (ends Dec 28) at whop.com/quantalgo/
📩 DM if you need any custom-built indicators or strategies.
📩 DM if you need any custom-built indicators or strategies.
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
🎁🎄 Christmas SALE 50% Off with code XMAS50 (ends Dec 28) at whop.com/quantalgo/
📩 DM if you need any custom-built indicators or strategies.
📩 DM if you need any custom-built indicators or strategies.
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.