PROTECTED SOURCE SCRIPT
Statistical Reversion Framework

Introduction and Core Philosophy
The Statistical Reversion Framework constitutes a sophisticated quantitative trading instrument designed to identify high-probability mean reversion opportunities across financial markets. Unlike traditional technical indicators that rely on a single dimension of market data, this framework adopts a multi-faceted approach, synthesizing statistical probability, volume profile analysis, institutional money flow proxies, and standard technical momentum into a singular composite score. The core philosophy driving this script is the concept of confluence through heterogeneity; by combining uncorrelated or loosely correlated market factors—such as price deviation (statistics), participant commitment (volume), and macro sentiment (intermarket data)—the algorithm aims to filter out the noise inherent in standard oscillators and isolate moments where market pricing has deviated unsustainably from its intrinsic equilibrium. This tool is specifically engineered to detect market extremes—tops and bottoms—where the probability of a counter-trend move or a snap-back to the mean is mathematically significant. It operates on the premise that while asset prices can remain irrational in the short term, they are bound by statistical variance and mean-reverting properties over longer horizons, particularly when institutional flows and volume exhaustion patterns align with those statistical extremes.
Methodology: The Composite Scoring Architecture
The underlying methodology of the framework relies on a weighted composite scoring system. Rather than generating binary buy or sell signals based on a threshold crossover, the script calculates a granular score ranging from zero to one hundred for various market dimensions. These dimension-specific scores are then weighted according to user-defined inputs to produce a final "Composite Score." This approach allows for a nuanced assessment of market conditions; a setup might have extreme statistical deviation but lack volume confirmation, resulting in a lower confidence score than a setup where price, volume, and macro factors all align. The algorithm normalizes all input data into a standardized scale, typically converting raw values—such as Z-Scores or volume ratios—into a zero-to-ten ranking before aggregating them. This normalization process is critical because it allows the algorithm to compare apples to oranges mathematically, treating a standard deviation of 3.0 and a Relative Strength Index (RSI) of 20 as compatible inputs within the same equation. By summing these normalized values and applying regime-based confidence adjustments, the framework produces a dynamic signal that adapts to the volatility and trend intensity of the current market environment.
Algorithmic Component I: Statistical Analysis via Multi-Timeframe Z-Scores
The backbone of the framework is the Statistical Component, which utilizes the Z-Score (or Standard Score) to quantify the degree of price deviation. The Z-Score measures how many standard deviations the current price is from its moving average. A crucial aspect of this algorithm is its fractal nature; it does not rely on a single lookback period. Instead, it computes Z-Scores across three distinct timeframes—Daily, Weekly, and Monthly—and within each timeframe, it calculates deviations for short, medium, and long-term periods. For instance, on the daily timeframe, it assesses deviation from 50-day, 200-day, and 500-day means simultaneously. This multi-timeframe approach is designed to filter out ephemeral noise. A price move that appears extreme on a 10-day basis but is normal on a 200-day basis is likely a trend pull-back rather than a reversal. Conversely, when the Z-Scores across daily, weekly, and monthly timeframes all register values beyond significant thresholds (such as 2.0 or 3.0 standard deviations), it indicates a rare fractal alignment where the asset is historically overextended on all relevant scales. The algorithm aggregates these nine distinct Z-Score data points to form the "Statistical Score," heavily rewarding scenarios where multiple timeframes show directional alignment, as these synchronized deviations often precede powerful mean-reversion events.
Algorithmic Component II: Volume Signature and Participation Analysis
While statistical deviation highlights where the price is, the Volume Component analyzes the conviction behind the move to determine if a reversal is imminent. This section of the code employs several sophisticated logic gates to identify specific volume signatures known as Capitulation and Exhaustion. The algorithm compares current volume against a 50-day moving average to generate a volume ratio. It then correlates this ratio with price action. For example, the script identifies "Capitulation" when price collapses significantly (more than 2%) on volume that is at least three times the average. This specific signature—panic selling—often marks the psychological wash-out necessary for a market bottom. Conversely, the script detects "Volume Exhaustion" when prices drift without conviction on extremely low volume, indicating a lack of participant interest in pushing the trend further. Furthermore, the algorithm integrates On-Balance Volume (OBV) analysis, specifically looking for divergences. It detects subtle shifts where the price makes a new low, but the OBV makes a higher low, signaling that smart money is accumulating positions despite the falling price. This divergence logic is automated using pivot-based high/low detection arrays, adding a layer of foreshadowing that price-only indicators often miss.
Algorithmic Component III: Institutional Proxy and Intermarket Correlations
The Institutional Component distinguishes this framework from standard retail indicators by incorporating intermarket data that serves as a proxy for macro sentiment and institutional flow. The script pulls data from extraneous tickers—specifically the VIX (Volatility Index), Government Bond Yields (10-year and 2-year), Copper, Gold, and the Dollar Index (DXY). The logic here is grounded in fundamental market mechanics. For instance, the script analyzes the VIX to gauge market fear; however, it applies a contrarian logic. An extremely high VIX (panic) coincident with a low equity price is scored as a bullish factor, while a complacently low VIX at market highs is viewed as bearish. Similarly, the algorithm analyzes the Yield Curve (the spread between 10-year and 2-year yields). A steepening or flattening curve provides context on economic expectations, influencing the score based on whether the environment is "risk-on" or "risk-off." The Copper/Gold ratio is utilized as a barometer for global economic health; rising copper relative to gold suggests industrial demand and growth, confirming bullish setups, whereas falling copper prices signal contraction. By integrating these non-price variables, the framework ensures that a trade signal is not just technically sound but is also supported by the broader macroeconomic undercurrents that drive institutional capital allocation.
Algorithmic Component IV: Technical Momentum and Structure
The final layer of input comes from standard Technical Analysis, which serves to fine-tune the timing of the entry. This component aggregates readings from the Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), Bollinger Bands, and Support/Resistance proximity. While Z-Scores measure linear distance from the mean, the RSI and Bollinger Bands measure the velocity and elasticity of that move. The algorithm assigns higher scores when RSI hits extreme levels (below 20 or above 80) and when price action pierces the outer bounds of the Bollinger Bands. Additionally, the MACD is monitored for histogram reversals and signal line crosses that align with the mean reversion bias. A unique feature of this component is the proximity logic, which calculates how close the current price is to a 50-period high or low. If a statistical extreme coincides with a retest of a major structural support level, the technical score is maximized. This ensures that the trader is not catching a falling knife in a void, but rather identifying a reversal at a location where technical structure provides a natural floor or ceiling for price.
Regime Detection and Confidence Adjustment
A critical vulnerability of mean reversion strategies is that they can suffer severe drawdowns during strong, unidirectional trending markets (momentum regimes). To mitigate this, the framework incorporates a Regime Detection module using the Average Directional Index (ADX) and volatility thresholds. The script calculates the ADX to measure trend strength regardless of direction. If the ADX is above a certain threshold (default 25), the market is classified as "Trending." The script then cross-references this with volatility data to classify the environment into regimes such as "Crisis," "Trending," "Range," or "Mean-Revert." This classification is not merely cosmetic; it actively influences the final output through a "Regime Confidence" multiplier. If the system detects a strong trending regime, it dampens the Composite Score, requiring extraordinary evidence from the other components to trigger a signal. Conversely, if the market is detected as "Mean-Revert" or "Low-Vol Range," the confidence multiplier boosts the score, making the system more sensitive to reversion signals. This adaptive logic helps protect the trader from fading strong breakouts while aggressively capitalizing on ranging markets.
Usage Instructions and Dashboard Interpretation
Traders utilizing this framework should primarily interact with the on-screen Dashboard, which provides a real-time summary of all computed metrics. The dashboard is organized hierarchically, with the "Composite Score" and "Signal Status" at the top. A Composite Score above 70 is generally considered actionable, with scores above 85 representing "Exceptional" setups. The Dashboard is color-coded: green hues indicate bullish/oversold conditions suitable for buying, while red hues indicate bearish/overbought conditions suitable for selling or shorting. Traders should look for "Confluence" across the rows. Ideally, a robust signal will show a high Statistical score (indicating price is cheap/expensive), a high Volume score (indicating capitulation or accumulation), and a supportive Institutional score. If the Composite Score is high but the Institutional score is low, the trader should proceed with caution, as the macro environment may not support the trade.
The chart visuals provide immediate entry triggers. "Strong Bottom" (Green Triangle) and "Strong Top" (Red Triangle) shapes appear when the Composite Score breaches the high threshold and Z-Scores are at extremes. These are the primary execution signals. Smaller "Potential" markers indicate developing setups that may require lower timeframe confirmation. Additionally, specific volume icons (Diamonds) will appear to denote Capitulation or Climax events. A trader should ideally wait for the candle to close to confirm these signals. The alerts configured in the script allow the trader to be notified of these events remotely. For risk management, because this is a mean reversion tool, stop-losses should typically be placed below the swing low of the capitulation candle (for longs) or above the swing high of the climax candle (for shorts), anticipating that the statistical extreme marks the distinct turning point. By systematically waiting for the Composite Score to align with the visual signals and verifying the regime context on the dashboard, the trader effectively filters out low-probability trades, engaging only when statistics, volume, and macro-economics align.
The Statistical Reversion Framework constitutes a sophisticated quantitative trading instrument designed to identify high-probability mean reversion opportunities across financial markets. Unlike traditional technical indicators that rely on a single dimension of market data, this framework adopts a multi-faceted approach, synthesizing statistical probability, volume profile analysis, institutional money flow proxies, and standard technical momentum into a singular composite score. The core philosophy driving this script is the concept of confluence through heterogeneity; by combining uncorrelated or loosely correlated market factors—such as price deviation (statistics), participant commitment (volume), and macro sentiment (intermarket data)—the algorithm aims to filter out the noise inherent in standard oscillators and isolate moments where market pricing has deviated unsustainably from its intrinsic equilibrium. This tool is specifically engineered to detect market extremes—tops and bottoms—where the probability of a counter-trend move or a snap-back to the mean is mathematically significant. It operates on the premise that while asset prices can remain irrational in the short term, they are bound by statistical variance and mean-reverting properties over longer horizons, particularly when institutional flows and volume exhaustion patterns align with those statistical extremes.
Methodology: The Composite Scoring Architecture
The underlying methodology of the framework relies on a weighted composite scoring system. Rather than generating binary buy or sell signals based on a threshold crossover, the script calculates a granular score ranging from zero to one hundred for various market dimensions. These dimension-specific scores are then weighted according to user-defined inputs to produce a final "Composite Score." This approach allows for a nuanced assessment of market conditions; a setup might have extreme statistical deviation but lack volume confirmation, resulting in a lower confidence score than a setup where price, volume, and macro factors all align. The algorithm normalizes all input data into a standardized scale, typically converting raw values—such as Z-Scores or volume ratios—into a zero-to-ten ranking before aggregating them. This normalization process is critical because it allows the algorithm to compare apples to oranges mathematically, treating a standard deviation of 3.0 and a Relative Strength Index (RSI) of 20 as compatible inputs within the same equation. By summing these normalized values and applying regime-based confidence adjustments, the framework produces a dynamic signal that adapts to the volatility and trend intensity of the current market environment.
Algorithmic Component I: Statistical Analysis via Multi-Timeframe Z-Scores
The backbone of the framework is the Statistical Component, which utilizes the Z-Score (or Standard Score) to quantify the degree of price deviation. The Z-Score measures how many standard deviations the current price is from its moving average. A crucial aspect of this algorithm is its fractal nature; it does not rely on a single lookback period. Instead, it computes Z-Scores across three distinct timeframes—Daily, Weekly, and Monthly—and within each timeframe, it calculates deviations for short, medium, and long-term periods. For instance, on the daily timeframe, it assesses deviation from 50-day, 200-day, and 500-day means simultaneously. This multi-timeframe approach is designed to filter out ephemeral noise. A price move that appears extreme on a 10-day basis but is normal on a 200-day basis is likely a trend pull-back rather than a reversal. Conversely, when the Z-Scores across daily, weekly, and monthly timeframes all register values beyond significant thresholds (such as 2.0 or 3.0 standard deviations), it indicates a rare fractal alignment where the asset is historically overextended on all relevant scales. The algorithm aggregates these nine distinct Z-Score data points to form the "Statistical Score," heavily rewarding scenarios where multiple timeframes show directional alignment, as these synchronized deviations often precede powerful mean-reversion events.
Algorithmic Component II: Volume Signature and Participation Analysis
While statistical deviation highlights where the price is, the Volume Component analyzes the conviction behind the move to determine if a reversal is imminent. This section of the code employs several sophisticated logic gates to identify specific volume signatures known as Capitulation and Exhaustion. The algorithm compares current volume against a 50-day moving average to generate a volume ratio. It then correlates this ratio with price action. For example, the script identifies "Capitulation" when price collapses significantly (more than 2%) on volume that is at least three times the average. This specific signature—panic selling—often marks the psychological wash-out necessary for a market bottom. Conversely, the script detects "Volume Exhaustion" when prices drift without conviction on extremely low volume, indicating a lack of participant interest in pushing the trend further. Furthermore, the algorithm integrates On-Balance Volume (OBV) analysis, specifically looking for divergences. It detects subtle shifts where the price makes a new low, but the OBV makes a higher low, signaling that smart money is accumulating positions despite the falling price. This divergence logic is automated using pivot-based high/low detection arrays, adding a layer of foreshadowing that price-only indicators often miss.
Algorithmic Component III: Institutional Proxy and Intermarket Correlations
The Institutional Component distinguishes this framework from standard retail indicators by incorporating intermarket data that serves as a proxy for macro sentiment and institutional flow. The script pulls data from extraneous tickers—specifically the VIX (Volatility Index), Government Bond Yields (10-year and 2-year), Copper, Gold, and the Dollar Index (DXY). The logic here is grounded in fundamental market mechanics. For instance, the script analyzes the VIX to gauge market fear; however, it applies a contrarian logic. An extremely high VIX (panic) coincident with a low equity price is scored as a bullish factor, while a complacently low VIX at market highs is viewed as bearish. Similarly, the algorithm analyzes the Yield Curve (the spread between 10-year and 2-year yields). A steepening or flattening curve provides context on economic expectations, influencing the score based on whether the environment is "risk-on" or "risk-off." The Copper/Gold ratio is utilized as a barometer for global economic health; rising copper relative to gold suggests industrial demand and growth, confirming bullish setups, whereas falling copper prices signal contraction. By integrating these non-price variables, the framework ensures that a trade signal is not just technically sound but is also supported by the broader macroeconomic undercurrents that drive institutional capital allocation.
Algorithmic Component IV: Technical Momentum and Structure
The final layer of input comes from standard Technical Analysis, which serves to fine-tune the timing of the entry. This component aggregates readings from the Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), Bollinger Bands, and Support/Resistance proximity. While Z-Scores measure linear distance from the mean, the RSI and Bollinger Bands measure the velocity and elasticity of that move. The algorithm assigns higher scores when RSI hits extreme levels (below 20 or above 80) and when price action pierces the outer bounds of the Bollinger Bands. Additionally, the MACD is monitored for histogram reversals and signal line crosses that align with the mean reversion bias. A unique feature of this component is the proximity logic, which calculates how close the current price is to a 50-period high or low. If a statistical extreme coincides with a retest of a major structural support level, the technical score is maximized. This ensures that the trader is not catching a falling knife in a void, but rather identifying a reversal at a location where technical structure provides a natural floor or ceiling for price.
Regime Detection and Confidence Adjustment
A critical vulnerability of mean reversion strategies is that they can suffer severe drawdowns during strong, unidirectional trending markets (momentum regimes). To mitigate this, the framework incorporates a Regime Detection module using the Average Directional Index (ADX) and volatility thresholds. The script calculates the ADX to measure trend strength regardless of direction. If the ADX is above a certain threshold (default 25), the market is classified as "Trending." The script then cross-references this with volatility data to classify the environment into regimes such as "Crisis," "Trending," "Range," or "Mean-Revert." This classification is not merely cosmetic; it actively influences the final output through a "Regime Confidence" multiplier. If the system detects a strong trending regime, it dampens the Composite Score, requiring extraordinary evidence from the other components to trigger a signal. Conversely, if the market is detected as "Mean-Revert" or "Low-Vol Range," the confidence multiplier boosts the score, making the system more sensitive to reversion signals. This adaptive logic helps protect the trader from fading strong breakouts while aggressively capitalizing on ranging markets.
Usage Instructions and Dashboard Interpretation
Traders utilizing this framework should primarily interact with the on-screen Dashboard, which provides a real-time summary of all computed metrics. The dashboard is organized hierarchically, with the "Composite Score" and "Signal Status" at the top. A Composite Score above 70 is generally considered actionable, with scores above 85 representing "Exceptional" setups. The Dashboard is color-coded: green hues indicate bullish/oversold conditions suitable for buying, while red hues indicate bearish/overbought conditions suitable for selling or shorting. Traders should look for "Confluence" across the rows. Ideally, a robust signal will show a high Statistical score (indicating price is cheap/expensive), a high Volume score (indicating capitulation or accumulation), and a supportive Institutional score. If the Composite Score is high but the Institutional score is low, the trader should proceed with caution, as the macro environment may not support the trade.
The chart visuals provide immediate entry triggers. "Strong Bottom" (Green Triangle) and "Strong Top" (Red Triangle) shapes appear when the Composite Score breaches the high threshold and Z-Scores are at extremes. These are the primary execution signals. Smaller "Potential" markers indicate developing setups that may require lower timeframe confirmation. Additionally, specific volume icons (Diamonds) will appear to denote Capitulation or Climax events. A trader should ideally wait for the candle to close to confirm these signals. The alerts configured in the script allow the trader to be notified of these events remotely. For risk management, because this is a mean reversion tool, stop-losses should typically be placed below the swing low of the capitulation candle (for longs) or above the swing high of the climax candle (for shorts), anticipating that the statistical extreme marks the distinct turning point. By systematically waiting for the Composite Score to align with the visual signals and verifying the regime context on the dashboard, the trader effectively filters out low-probability trades, engaging only when statistics, volume, and macro-economics align.
סקריפט מוגן
סקריפט זה פורסם כמקור סגור. עם זאת, תוכל להשתמש בו בחופשיות וללא כל מגבלות – למד עוד כאן
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.
סקריפט מוגן
סקריפט זה פורסם כמקור סגור. עם זאת, תוכל להשתמש בו בחופשיות וללא כל מגבלות – למד עוד כאן
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.