OPEN-SOURCE SCRIPT
Aktualisiert

SwingRegress Volatility Analytics [MarkitTick]

8 833
💡 A comprehensive, multi-dimensional charting tool designed to fuse structural market analysis, statistically derived linear regression pathways, and volatility compression mechanics into a single, cohesive interface. By dynamically adapting its calculations to the latest shifts in market structure—specifically Change of Character (CHoCH) events—this script offers an adaptive mapping of price action, trend trajectory, and potential breakout zones directly on the primary chart.

● ✨ Originality and Utility

Traditional linear regression tools often require manual anchoring or rely on fixed lookback periods that fail to adapt to rapidly unfolding price dynamics. The distinct utility of this script lies in its self-adjusting structural anchoring mechanism. By automatically locking the regression baseline to the most recent significant pivot high or pivot low immediately following a structural break, the channel remains mathematically and contextually relevant to the current market regime.

Furthermore, this tool eliminates the need for separate sub-chart oscillators by integrating a sophisticated Smart Volatility Squeeze engine. This engine compares price variance against true range to identify periods of extreme price compression, overlaying these signals directly within the active regression pathway. The result is a unified, chart-centric view of both directional trend geometry and kinetic energy build-up, allowing for a more focused and uncluttered analytical process.

● 🔬 Methodology and Concepts

The underlying logic of this script is driven by three core mathematical engines operating in tandem:

• Pivot Discovery and Market Structure
The script continuously scans incoming price data to identify localized extremes, defined as Pivot Highs and Pivot Lows. A candidate bar is confirmed as a pivot only if it remains unbroken for a user-defined number of bars both prior to and following its occurrence. Once confirmed, these pivots establish the market structure. If the closing price breaks beyond the most recent opposing pivot, a Change of Character (CHoCH) is triggered, officially shifting the trend state.

• Anchored Linear Regression
Upon the confirmation of a new CHoCH, the script calculates a fresh Linear Regression Channel (LRC). The anchoring point is the origin pivot of the newly established trend. The script uses the Ordinary Least Squares (OLS) method to compute the slope and intercept of the best-fit line through the closing prices of the current regime. It then calculates the standard error of the estimate (standard deviation of the residuals) to project upper and lower variance bands parallel to the mid-line.

• Volatility Squeeze Mechanics
To identify volatility compression, the script employs a comparative analysis between standard deviation and Average True Range (ATR). It calculates a Bollinger Band (representing standard deviation) and a Keltner Channel (representing ATR) around a moving average baseline. A "squeeze" is structurally confirmed when the outer limits of the Bollinger Bands contract entirely within the boundaries of the Keltner Channels. This signifies that historical variance has dropped substantially below the average true range, often preceding a dynamic expansion in price movement.

● 🎨 Visual Guide

The visual interface is highly detailed and structurally color-coded to provide immediate contextual awareness without cluttering the chart.

• Current Anchored LRC

  • Mid Line: A solid Neon Cyan line representing the true mean of the current trend regime.
    Band 1: A dashed Soft Cyan line mapping the first standard deviation threshold.
    Band 2: A dotted Deep Azure line mapping the secondary, outer standard deviation extreme.


• Previous Anchored LRC

  • Mid Line: A solid Magenta line representing the historical mean of the preceding trend.
    Band 1: A dashed Soft Magenta line for the historical inner variance.
    Band 2: A dotted Blue-Violet line for the historical outer variance.


• Swing Point Zones

  • Swing High Boxes: Translucent red zones originating from a confirmed pivot high, drawing forward to act as dynamic resistance until broken by price action.
    Swing Low Boxes: Translucent green zones originating from a confirmed pivot low, acting as dynamic support until structurally invalidated.


• Volatility Squeeze Candles

  • Cyber Gold Candles: When the market enters a state of extreme volatility compression (Bollinger Bands inside Keltner Channels) and is actively trading within the current or previous LRC pathway, the candles are painted a vibrant gold to highlight imminent kinetic release.


• Heads-Up Dashboard Display
Located in the top right corner, this self-updating data matrix provides critical real-time telemetry:

  • Structure Regime: Displays the active directional bias (Bullish, Bearish, or Neutral).
    Last CHoCH: Indicates the direction and age (in bars) of the most recent structural shift.
    Squeeze Intensity: A visual block-bar measuring the depth of the volatility compression.
    ATR (14): The current absolute value of the Average True Range.
    Dist to Swings: The percentage distance between the current price and the nearest Swing High/Low.
    Risk/Reward Quality: A dynamic measurement of potential risk versus structural reward.
    LRC Window Age: The duration of the current regression channel in bars.
    LRC Position: Indicates whether price is currently trading inside the active regression channel, the previous channel, or is entirely unanchored.


● 📖 How to Use

The primary application of this tool is identifying high-probability continuation or mean-reversion setups following structural confirmation.

When a CHoCH event occurs, wait for the new Linear Regression Channel to populate. This channel defines your trading parameters. A high-probability setup manifests when price pulls back to the inner or mid-line of the active LRC, accompanied by the appearance of Cyber Gold squeeze candles. This visual confluence suggests that price is compressing directly at the statistical mean of the new trend, building energy for a move in the direction of the underlying structural regime.

Conversely, if price approaches the outer standard deviation bands (Deep Azure) without structural confirmation of a breakout, it suggests the market is statistically overextended, offering a potential mean-reversion opportunity back toward the Neon Cyan mid-line.

Note on Mechanics: Because the pivot discovery process requires a defined number of bars to confirm a swing high or low, there is an inherent lookback period. The swing zones will only appear after the pivot has been structurally verified. Furthermore, the linear regression channel recalculates its slope dynamically as new price data is added to the active regime, meaning the exact angle of the channel adapts in real-time until a new CHoCH locks it into history as the "Previous LRC."

● ⚙️ Inputs and Settings

The configuration panel is logically divided into primary analytical modules to allow for precise user calibration.

• Current Anchored CHoCH LRC
Adjust the sensitivity of the pivot discovery engine by modifying the Left and Right Pivot Bars. You can also customize the multipliers for the primary and secondary standard deviation bands, as well as toggle their visibility and modify line weights.

• Previous Anchored CHoCH LRC
Allows for the toggling of the historical channel, providing context on how the previous trend failed. Color and visibility settings are fully adjustable here.

• Swing Points & Zones Settings
Toggle the structural resistance and support boxes on or off, and customize their respective color opacities for a cleaner chart overlay.

• Smart Volatility Squeeze (BB vs KC)
Tune the underlying volatility engine. You can adjust the lookback length for the variance baseline, as well as the specific deviation multipliers for both the Bollinger Band boundaries and the Keltner Channel limits.

• Webhook Execution Configuration
Input exact JSON payload action names for algorithmic execution routing (Long, Short, Close Long, Close Short).

• Dashboard Settings
Customize the background and text colors of the heads-up data matrix to match your specific chart theme.

● 🔍 Deconstruction of the Underlying Scientific and Academic Framework

The mathematical foundation of this script is anchored heavily in econometrics and statistical probability theory.

At its core, the linear regression calculation utilizes the Ordinary Least Squares (OLS) estimator. This formula determines the line of best fit through a sequence of time-series data points by minimizing the sum of the squared differences (residuals) between the observed closing prices and the values predicted by the linear model. The slope of this line represents the average rate of change per unit of time, mathematically quantifying the drift of the active regime.

The parallel bands wrapping the regression line are derived by calculating the standard error of the estimate. Assuming the residuals are normally distributed (Gaussian distribution), one standard deviation captures approximately 68 percent of the price variance, while two standard deviations capture roughly 95 percent. When price moves beyond these outer bands, it represents a statistically significant deviation from the mean, inherently increasing the probabilistic likelihood of mean reversion.

The volatility squeeze mechanic operates on the principle of variance compression. Bollinger Bands are a derivative of standard deviation, making them highly reactive to short-term variance. Keltner Channels utilize the Average True Range (ATR), which measures absolute periodic volatility independent of a central mean. When the standard deviation of price contracts to such a degree that the Bollinger Bands fall entirely within the ATR-based Keltner Channels, it statistically confirms a state of anomalous energy compression. In financial academia, periods of artificially suppressed variance are overwhelmingly followed by periods of geometric expansion, providing the theoretical basis for breakout execution.

⚠️ 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.
Versionshinweise
Differentiating the current regression channel from the previous regression channel.

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.