OPEN-SOURCE SCRIPT
Adaptive Linear Regression Structure [MarkitTick]

💡 This indicator, is a sophisticated analytical tool designed to bridge the gap between classical statistical modeling and modern price action theory. By leveraging high-performance Ordinary Least Squares (OLS) calculations, it dynamically identifies the most statistically significant market structures—specifically linear regression channels—based on historical pivot points. Unlike static channels that rely on arbitrary lookback periods, this script scans a historical "horizon" of structural pivots to find the model with the highest mathematical "fit," providing traders with a non-repainting, objective view of trend exhaustion and volatility boundaries.
✨ Originality and Utility
● Dynamic Model Selection
Most linear regression indicators require the user to manually define a start and end point, or they use a fixed lookback period. This script is original because it treats the starting point of the regression as a variable. It scans multiple historical pivots (Highs and Lows) and performs a competitive analysis between different potential channels. The channel that is eventually displayed is the one that achieves the highest performance score, calculated via a combination of the Coefficient of Determination ($R^2$) and the natural log of the duration. This ensures the channel is both mathematically reliable and structurally relevant.
● Market Structure Integration
The utility of the indicator is enhanced by its "Market Structure Registry." Instead of calculating regressions on every single bar blindly, the script identifies "Pivot Highs" and "Pivot Lows" to use as anchors. This aligns the statistical modeling with the way professional traders view the market, focusing on major turning points rather than noise.
● Institutional-Grade Telemetry
The inclusion of a real-time HUD (Heads-Up Display) dashboard provides traders with immediate transparency into the model's health. By displaying the $R^2$ value and Z-Score, the indicator moves beyond simple "lines on a chart" and offers a quantitative assessment of how well the current price action respects the established trend.
🔬 Methodology and Concepts
● The OLS Kernel
At the heart of the script is a custom-built OLS (Ordinary Least Squares) method. It calculates the slope ($\beta$) and the intercept ($\alpha$) of the best-fit line through the closing prices of the selected period. The mathematical goal is to minimize the sum of the squared errors (
SSE$), ensuring the median line represents the "true" equilibrium of price over that duration.
● Heuristic Performance Scoring
The indicator does not just look for the highest correlation. It uses a "Performance Score" heuristic:
This formula rewards models that maintain a high degree of linearity over longer periods. A short-term channel with a high $R^2$ might be dismissed in favor of a long-term channel that has a slightly lower $R^2$ but significantly more structural weight.
● Volatility-Adjusted Envelopes
The upper and lower boundaries are not arbitrary. They are calculated based on the standard deviation of the residuals (the distance between actual price and the regression line). By applying a user-defined "Deviation Factor," the script creates volatility bands that expand or contract based on how "noisy" the trend is.
🎨 Visual Guide
● The Regression Channel
• Median Vector: A solid line representing the linear mean of the current trend. It is colored Cyan for bullish slopes and Orange for bearish slopes.
• Volatility Bands: Two solid lines flanking the median. These represent the "Deviation Factor" boundaries (defaulting to 2.0 standard deviations).
• Fill Core: A transparent background fill between the upper and lower bands, allowing for easy visualization of the "fair value" zone. The color dynamically shifts between Cyan and Orange based on the trend bias.
● Signal Labels
• LONG Labels: Cyan labels appearing below price when a "Mean Reversion" setup is detected (price crossing above the lower band).
• SHORT Labels: Orange labels appearing above price when a "Mean Reversion" setup is detected (price crossing below the upper band).
• Details: Labels include the Entry Price (EP), Take Profit (TP) at the median, and a suggested Stop Loss (SL).
● Telemetry Dashboard (HUD)
• Model Quality (R²): A value between 0.0 and 1.0. Values above 0.7 indicate a very strong trend.
• Trend Bias: Explicitly states "BULLISH" or "BEARISH."
• Deviation (Z-Score): Measures how many standard deviations the current price is away from the mean.
• Duration: Displays how many bars the current model covers.
📖 How to Use
● Mean Reversion Strategy
The primary use case is identifying overextended price action. When price moves outside the volatility bands (high Z-Score) and then crosses back inside, it suggests a return to the median "equilibrium" price.
• Bullish Entry: Look for a Cyan "LONG" label when price recovers from the lower band.
• Bearish Entry: Look for an Orange "SHORT" label when price pulls back from the upper band.
● Trend Strength Assessment
Use the $R^2$ value in the dashboard to filter trades. If the $R^2$ is low (e.g., below 0.5), the market is in a "Random Walk" phase, and the regression lines may be less reliable. High $R^2$ values suggest a "Trending" phase where the channel boundaries act as significant support and resistance.
● Dynamic Take Profits
The median line (the Cyan/Orange vector) serves as a dynamic take-profit target. Since the line is based on a linear slope, the price target adjusts every bar to reflect the ongoing trend.
⚙️ Inputs and Settings
● Algorithmic Core
• Scan Horizon: Determines how many historical pivots the script should evaluate. A higher number increases the "search depth" but requires more processing.
• Deviation Factor: Controls the width of the channel. A value of 2.0 covers approximately 95% of price action if the distribution is normal.
• Structural Sensitivity: Controls the lookback for the Pivot High/Low detection. Smaller values find more "local" structures; higher values find "major" structures.
● Signal Processing
• Quality Threshold (R²): This is a "gatekeeper" setting. If no model reaches this minimum quality, the indicator will not display a channel, protecting the user from weak or chaotic patterns.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
● Statistical Basis (OLS)
The indicator is grounded in the Gauss-Markov theorem. By calculating the slope via the covariance of time and price divided by the variance of time, it provides the "Best Linear Unbiased Estimator" (BLUE) of the current price trajectory.
● Information Theory & Heuristics
The scoring mechanism (using the natural log of N) draws inspiration from Information Criteria (like AIC or BIC). In statistical modeling, increasing the sample size ($N$) usually improves the model's reliability but can introduce "lag." By using the log of duration, the script balances the benefit of a larger sample size against the need for current relevance.
● Standardized Residuals (Z-Scores)
The "Z-Metric" displayed in the dashboard is a calculation of:
This standardizes the distance of price from the mean across different assets and timeframes, allowing for a universal interpretation of "overbought" or "oversold" conditions based on the specific volatility of the current trend.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.
✨ Originality and Utility
● Dynamic Model Selection
Most linear regression indicators require the user to manually define a start and end point, or they use a fixed lookback period. This script is original because it treats the starting point of the regression as a variable. It scans multiple historical pivots (Highs and Lows) and performs a competitive analysis between different potential channels. The channel that is eventually displayed is the one that achieves the highest performance score, calculated via a combination of the Coefficient of Determination ($R^2$) and the natural log of the duration. This ensures the channel is both mathematically reliable and structurally relevant.
● Market Structure Integration
The utility of the indicator is enhanced by its "Market Structure Registry." Instead of calculating regressions on every single bar blindly, the script identifies "Pivot Highs" and "Pivot Lows" to use as anchors. This aligns the statistical modeling with the way professional traders view the market, focusing on major turning points rather than noise.
● Institutional-Grade Telemetry
The inclusion of a real-time HUD (Heads-Up Display) dashboard provides traders with immediate transparency into the model's health. By displaying the $R^2$ value and Z-Score, the indicator moves beyond simple "lines on a chart" and offers a quantitative assessment of how well the current price action respects the established trend.
🔬 Methodology and Concepts
● The OLS Kernel
At the heart of the script is a custom-built OLS (Ordinary Least Squares) method. It calculates the slope ($\beta$) and the intercept ($\alpha$) of the best-fit line through the closing prices of the selected period. The mathematical goal is to minimize the sum of the squared errors (
● Heuristic Performance Scoring
The indicator does not just look for the highest correlation. It uses a "Performance Score" heuristic:
Score = $R^2$ * ln(Duration)
This formula rewards models that maintain a high degree of linearity over longer periods. A short-term channel with a high $R^2$ might be dismissed in favor of a long-term channel that has a slightly lower $R^2$ but significantly more structural weight.
● Volatility-Adjusted Envelopes
The upper and lower boundaries are not arbitrary. They are calculated based on the standard deviation of the residuals (the distance between actual price and the regression line). By applying a user-defined "Deviation Factor," the script creates volatility bands that expand or contract based on how "noisy" the trend is.
🎨 Visual Guide
● The Regression Channel
• Median Vector: A solid line representing the linear mean of the current trend. It is colored Cyan for bullish slopes and Orange for bearish slopes.
• Volatility Bands: Two solid lines flanking the median. These represent the "Deviation Factor" boundaries (defaulting to 2.0 standard deviations).
• Fill Core: A transparent background fill between the upper and lower bands, allowing for easy visualization of the "fair value" zone. The color dynamically shifts between Cyan and Orange based on the trend bias.
● Signal Labels
• LONG Labels: Cyan labels appearing below price when a "Mean Reversion" setup is detected (price crossing above the lower band).
• SHORT Labels: Orange labels appearing above price when a "Mean Reversion" setup is detected (price crossing below the upper band).
• Details: Labels include the Entry Price (EP), Take Profit (TP) at the median, and a suggested Stop Loss (SL).
● Telemetry Dashboard (HUD)
• Model Quality (R²): A value between 0.0 and 1.0. Values above 0.7 indicate a very strong trend.
• Trend Bias: Explicitly states "BULLISH" or "BEARISH."
• Deviation (Z-Score): Measures how many standard deviations the current price is away from the mean.
• Duration: Displays how many bars the current model covers.
📖 How to Use
● Mean Reversion Strategy
The primary use case is identifying overextended price action. When price moves outside the volatility bands (high Z-Score) and then crosses back inside, it suggests a return to the median "equilibrium" price.
• Bullish Entry: Look for a Cyan "LONG" label when price recovers from the lower band.
• Bearish Entry: Look for an Orange "SHORT" label when price pulls back from the upper band.
● Trend Strength Assessment
Use the $R^2$ value in the dashboard to filter trades. If the $R^2$ is low (e.g., below 0.5), the market is in a "Random Walk" phase, and the regression lines may be less reliable. High $R^2$ values suggest a "Trending" phase where the channel boundaries act as significant support and resistance.
● Dynamic Take Profits
The median line (the Cyan/Orange vector) serves as a dynamic take-profit target. Since the line is based on a linear slope, the price target adjusts every bar to reflect the ongoing trend.
⚙️ Inputs and Settings
● Algorithmic Core
• Scan Horizon: Determines how many historical pivots the script should evaluate. A higher number increases the "search depth" but requires more processing.
• Deviation Factor: Controls the width of the channel. A value of 2.0 covers approximately 95% of price action if the distribution is normal.
• Structural Sensitivity: Controls the lookback for the Pivot High/Low detection. Smaller values find more "local" structures; higher values find "major" structures.
● Signal Processing
• Quality Threshold (R²): This is a "gatekeeper" setting. If no model reaches this minimum quality, the indicator will not display a channel, protecting the user from weak or chaotic patterns.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
● Statistical Basis (OLS)
The indicator is grounded in the Gauss-Markov theorem. By calculating the slope via the covariance of time and price divided by the variance of time, it provides the "Best Linear Unbiased Estimator" (BLUE) of the current price trajectory.
● Information Theory & Heuristics
The scoring mechanism (using the natural log of N) draws inspiration from Information Criteria (like AIC or BIC). In statistical modeling, increasing the sample size ($N$) usually improves the model's reliability but can introduce "lag." By using the log of duration, the script balances the benefit of a larger sample size against the need for current relevance.
● Standardized Residuals (Z-Scores)
The "Z-Metric" displayed in the dashboard is a calculation of:
$Z = (Price - Estimated Price) / Standard Error$
This standardizes the distance of price from the mean across different assets and timeframes, allowing for a universal interpretation of "overbought" or "oversold" conditions based on the specific volatility of the current trend.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.
开源脚本
秉承TradingView的精神,该脚本的作者将其开源,以便交易者可以查看和验证其功能。向作者致敬!您可以免费使用该脚本,但请记住,重新发布代码须遵守我们的网站规则。
Passionate technical analysts developing proprietary indicators. We provide unique market insights that reshape your trading perspective. Upgrade your charts with premium access: markittick.com
免责声明
这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。
开源脚本
秉承TradingView的精神,该脚本的作者将其开源,以便交易者可以查看和验证其功能。向作者致敬!您可以免费使用该脚本,但请记住,重新发布代码须遵守我们的网站规则。
Passionate technical analysts developing proprietary indicators. We provide unique market insights that reshape your trading perspective. Upgrade your charts with premium access: markittick.com
免责声明
这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。