SwingRegress Volatility Analytics [MarkitTick]💡 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. Indicator

Regression-Aligned Candlestick Architect [MarkitTick]💡 The Regression-Aligned Candlestick Architect is an advanced, institutional-grade technical analysis instrument engineered to seamlessly fuse structural market context with precise, deterministic candlestick morphology. Rather than presenting isolated, noisy signals, this indicator operates as a holistic market mapping system. It dynamically identifies changes in market character (CHoCH), anchors statistical regression channels to these pivotal structural nodes, and overlays a rigorously filtered, strength-tiered candlestick pattern recognition engine. This tool empowers analysts to visualize the exact mathematical relationship between micro-level price action anomalies and macro-level statistical deviations.
● ✨ Originality and Utility
Standard candlestick recognition tools often suffer from a fatal flaw: signal noise. By identifying every single pattern across the chart regardless of context, they overwhelm the analyst with false positives. This indicator revolutionizes pattern detection by introducing a multi-dimensional filtering matrix.
Contextual Awareness: Patterns are cross-referenced against a dynamic Simple Moving Average (SMA) baseline, ensuring that continuation patterns are only validated when aligned with the prevailing macroeconomic trend.
Hierarchical Strength Matrix: Patterns are not treated equally. They are mathematically scored and classified into five distinct strength tiers, from baseline indecision to highly reliable structural anomalies.
Anchored Statistical Modeling: Instead of static support and resistance lines, this tool maps volatility using an anchored Linear Regression Channel (LRC) that resets automatically upon validated structural breaks (CHoCH), providing an evolving map of fair value and extreme deviation.
Institutional Automation Ready: Built-in webhook templates format high-conviction signals directly into actionable JSON payloads, bridging the gap between discretionary charting and algorithmic execution.
● 🔬 Methodology and Concepts
The architecture of this script relies on a confluence of three primary mathematical and logical engines.
• Quantitative Pattern Recognition
The core engine deconstructs each individual candlestick into absolute mathematical variables: body size, total high-low range, upper shadow ratio, and lower shadow ratio. By applying rigid algorithmic tolerance thresholds (e.g., Dojis strictly requiring a body-to-range ratio of less than 5%), the script actively eliminates subjective interpretation.
• The Strength Stratification System
The indicator systematically grades market geometry into five actionable categories:
Strength 1 (Indecision): Identifies market equilibrium phases and compression (e.g., Doji, Spinning Tops).
Strength 2 (Weak Signals): Early signs of exhaustion that require further context (e.g., Hanging Man, Inverted Hammer).
Strength 3 (Moderate Confirmations): Standard two-candle reversal structures (e.g., Harami, Piercing Line, Dark Cloud Cover).
Strength 4 (Strong Confirmations): High-conviction multi-candle configurations (e.g., Engulfing setups, Morning/Evening Stars, Marubozu).
Strength 5 (Extreme Conviction): Rare, highly reliable setups signaling massive structural imbalances (e.g., Three White Soldiers, Breakaway Gaps).
• Structural CHoCH and LRC Anchoring
The script continuously scans for localized Pivot Highs and Pivot Lows using customizable look-left and look-right parameters. When the price closes beyond the most recent opposing pivot node, a Change of Character (CHoCH) is registered. This event immediately triggers the recalculation of the Linear Regression Channel, anchoring the starting point to the critical pivot and projecting statistical deviation bands forward to track the new trend's trajectory.
● 🎨 Visual Guide
The interface is meticulously designed with a 3D holographic aesthetic to ensure clarity without cluttering the primary price action.
• Candlestick Labels and Holographic Colors
Indigo Glass (Strength 1): Muted, translucent tones denoting indecision and market pauses without demanding immediate attention.
Cyber Blue & Violet (Strength 2 & 3): Intermediate colors highlighting developing reversals or moderate continuation patterns.
Neon Mint (Bullish Strength 4-5): Bright, high-contrast markers indicating strong bullish dominance (e.g., BE+, 3WS), plotted below the bar.
Hot Pink (Bearish Strength 4-5): Intense, high-visibility markers warning of severe bearish pressure (e.g., BE-, 3BC), plotted above the bar.
Cyber Gold (Special/Exhaustion): Reserved strictly for profound trend exhaustion signatures, such as the Three Line Strike configuration.
To learn more about Candlestick patterns, access the following link:
Quantitative Analysis of Algorithmic Candlestick Pattern
• Linear Regression Channel Bands
Active LRC: Displays a Neon Cyan midline representing the mean regression. Soft Cyan and Deep Azure dashed and dotted lines represent the first and second standard deviation bands respectively, filled with translucent gradient shading to represent volatility zones.
Historical LRC: Previous channels are preserved in deep Magenta and Blue-Violet hues. This allows the analyst to review past structural behavior, momentum shifts, and how price transitioned between volatility states.
● 📖 How to Use
This indicator is optimized for confluence trading. Discretionary traders should look for optimal alignment between the LRC boundaries and high-tier candlestick patterns.
Define the Structural Boundary: Observe the active Neon Cyan LRC. Determine if the current micro-trend is contained safely within the inner standard deviation bands or if it is stretching into extreme statistical anomaly (touching or piercing Band 2).
Wait for Signal Convergence: A standalone pattern is interesting, but confluence is key. A Strength 4 (Neon Mint) Bullish Engulfing pattern occurring exactly at the lower boundary (Band 2) of an ascending LRC presents an exceptionally high-probability mean-reversion or trend-continuation setup.
Automate Execution: Utilize the built-in alert system to capture the exact entry price alongside dynamically calculated ATR-based Stop Loss and Take Profit levels when a tier 4 or 5 pattern confirms.
Adapt to Trend Shifts: If a CHoCH occurs, the channel will instantly snap to the new trajectory. Immediately shift your directional bias and await new pattern formations that align with the updated regression mean.
● ⚙️ Inputs and Settings
The indicator provides granular control over internal parameters, allowing adaptation to varying asset classes and timeframes.
• General & Strength Filters
Max Patterns to Display: Limits historical label rendering to keep the chart performant and visually clean.
Show Only Trend-Appropriate Patterns: A critical toggle that forces the engine to ignore counter-trend signals by filtering outputs through the internal SMA logic.
Strength Toggles (S1 - S5): Allows the user to independently enable or disable specific tiers. Professional traders often disable tiers 1-3 to focus exclusively on high-probability tier 4 and 5 formations.
• Current Anchored CHoCH LRC
Pivot Left/Right Bars: Dictates the sensitivity of the Change of Character detection. Higher numbers require major macro swings to shift the channel, while lower numbers tightly track micro-structure fluctuations.
Band Multipliers (1 & 2): Adjusts the mathematical standard deviation widths of the regression channel. Defaulted to standard 1.0 and 2.0 deviations.
• Webhook Execution Configuration
Action Strings: Define custom text identifiers (e.g., 'long', 'closeshort') that will be injected into the automated JSON payload when high-strength signals or CHoCH events trigger on a confirmed bar close.
● 🔍 Deconstruction of the Underlying Scientific and Academic Framework
The analytical depth of this script is heavily grounded in established statistical mathematics and heuristic geometric modeling.
• Statistical Modeling via Ordinary Least Squares (OLS)
The dynamic Linear Regression Channel is derived using the Ordinary Least Squares method. The script iteratively loops through the dynamically anchored period (from the algorithmic CHoCH trigger to the current bar index) to calculate the line of best fit. It computes the summation of price coordinates, calculating the slope and y-intercept to minimize the sum of the squared residuals.
Furthermore, the indicator calculates the population standard deviation of these residuals (errors) to project the outer variance bands. In a normally distributed financial dataset, approximately 68% of price action should remain within Band 1, and 95% within Band 2. When price forcefully breaches Band 2, it statistically indicates an unsustainable momentum extreme, shifting the probability matrix heavily toward imminent mean-reversion.
• Quantitative Candlestick Heuristics
Traditional Japanese Candlestick theory relies heavily on qualitative visual assessment. This indicator transforms it into a rigorous quantitative science. By expressing wicks, shadows, and true bodies as strict fractional ratios of the total period variance, the algorithm entirely removes psychological bias. For instance, an Engulfing pattern is not merely determined by a visual overlap; the internal logic mathematically validates that the current open and close parameters completely eclipse the previous period's boundaries, while simultaneously verifying that the absolute body size explicitly exceeds the prior via comparative array lookbacks. Furthermore, advanced configurations like the 'Three Line Strike' necessitate the sequential tracking of four independent vector arrays to confirm precise exhaustion geometry and statistical anomaly.
⚠️ 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. Indicator

AG Pro Regression Range Map [AGPro Series]AG Pro Regression Range Map
OVERVIEW
AG Pro Regression Range Map is a statistical corridor overlay built to answer one practical question as clearly as possible: what type of active movement corridor is price traveling in right now?
Instead of treating the market as a sequence of isolated signals, the script models the current price path as a rolling regression backbone surrounded by residual dispersion bands. This allows the chart to be read as a live structure: a directional corridor, a flat corridor, or a weakening corridor that is losing discipline.
The result is a clean visual framework that helps users judge whether price is progressing inside an organized range map or drifting without stable structure. The script is designed as an analytical overlay, not as a forecasting engine.
UNIQUE EDGE
The core idea here is different from indicators that measure simple distance from a moving average, fixed volatility envelopes, or breakout-style event detection.
This script does not ask, “How far is price from a reference?” It asks, “Given the current regression slope and the current residual dispersion, what movement corridor is active now?”
That distinction matters.
The center line is not a generic average. It is a rolling linear regression backbone. The bands are not ATR shells or standard deviation bands around price itself. They are built from the residual dispersion around the active regression backbone. In other words, the script maps drift and dispersion together.
This produces a different analytical lens:
- the backbone defines directional drift
- the corridor width reflects residual dispersion around that drift
- the containment rate shows whether price is respecting that corridor
- the quality score estimates how coherent the corridor currently is
This makes the tool suitable for users who want to evaluate market structure in a disciplined way without turning the chart into a signal-heavy dashboard.
WHAT THE SCRIPT DOES
The script plots:
- a rolling regression backbone
- an inner corridor around that backbone
- an outer corridor around that backbone
- subtle fill to make the active corridor readable without obscuring price
- a compact mini panel with corridor metrics
It also classifies the current corridor state into one of three modes:
- Uptrend Range
- Flat Range
- Downtrend Range
The intention is to show whether price is currently traveling inside an upward corridor, a neutral corridor, or a downward corridor, while also indicating how stable that corridor is.
METHODOLOGY
1) Regression backbone
The center line is a rolling linear regression calculated over the selected lookback window. This backbone is used as the active structural reference for the current chart state.
2) Residual dispersion corridor
After calculating the backbone, the script measures the residual distance between price and the regression line. The standard deviation of those residuals becomes the corridor unit.
The inner and outer bands are then built by multiplying that residual dispersion unit by user-defined multipliers.
This means the corridor is not based on absolute price volatility alone. It is based on how price is dispersing around the active regression path.
3) Normalized slope
The slope of the regression backbone is normalized relative to ATR so the directional reading is more comparable across instruments and conditions.
That normalized slope is then used to classify the corridor as upward, flat, or downward.
4) Containment
Containment measures how consistently price has remained inside the outer corridor over the selected lookback period.
A high containment reading suggests that price is respecting the active corridor. A lower reading suggests that the corridor is less representative of current behavior.
5) Range Width
Range Width expresses the outer corridor width relative to the current center value. This helps users quickly judge whether the active map is relatively tight or relatively wide.
6) Width Stability
Width Stability estimates how stable the corridor width has been over time. This helps distinguish between a corridor that is behaving consistently and one that is expanding or contracting too erratically.
7) Drift Quality
Drift Quality is a composite score derived from containment, normalized slope strength, width stability, and fit quality. It is not a prediction score. It is a structural quality score describing how coherent the active corridor currently is.
HOW TO USE IT
A practical way to read the script is to begin with the mode, then confirm the quality of the structure.
Mode
Start with the mode label:
- Uptrend Range suggests the active regression backbone is rising with enough normalized slope to avoid being treated as flat
- Flat Range suggests directional drift is weak relative to the selected threshold
- Downtrend Range suggests the active regression backbone is declining with enough normalized slope to define a downward corridor
Containment
Then check containment. High containment means price has been spending most of its recent time inside the outer corridor. This usually indicates that the displayed map is representative of the current market path.
Drift Quality
Use Drift Quality to judge whether the active corridor is coherent enough to be worth respecting as a structure. Higher values suggest cleaner organization. Lower values suggest weaker corridor integrity.
Range Width and Width Stability
Use these two together. A corridor can be narrow but unstable, or wide but orderly. The combination is often more informative than either metric alone.
VISUAL INTERPRETATION
In practice, the script is designed to help with questions such as:
- Is price traveling inside an orderly directional corridor or just moving noisily?
- Is the current range map still representative of behavior, or is it degrading?
- Is the structure flat, directional, tight, or loose?
- Is the current drift readable enough to justify a structure-based chart interpretation?
This makes the tool useful for context reading, corridor analysis, and chart organization. It is intentionally restrained in its presentation so price remains the primary object on the chart.
KEY INPUTS
Source
Selects the price source used to build the regression backbone.
Regression Length
Controls the lookback window used for the rolling linear regression center line. Shorter values make the map more reactive. Longer values make it smoother and more structural.
Containment Lookback
Defines the number of bars used to measure how consistently price remains inside the outer corridor.
Inner Band Multiplier
Controls the distance of the inner corridor around the regression backbone.
Outer Band Multiplier
Controls the distance of the outer corridor around the regression backbone.
Flat Threshold
Defines the normalized slope threshold below which the corridor is classified as flat.
Theme Preset
Provides a dark and light visual preset for better chart integration.
Mini Panel Controls
The panel can be shown or hidden and positioned in different chart corners depending on layout preference.
WHAT THIS SCRIPT IS NOT
This script is not a future path projection model.
It does not forecast a target.
It does not mark buy or sell entries.
It does not attempt to predict reversals.
It does not replace execution logic, confirmation logic, or risk management.
Its job is narrower and more disciplined: it maps the active regression corridor and summarizes how coherent that corridor currently is.
LIMITATIONS AND TRANSPARENCY
Like any rolling statistical model, this script is sensitive to lookback selection. Shorter lengths will react faster but may produce more frequent structural changes. Longer lengths will be smoother but slower to adapt.
Because the corridor is recalculated on a rolling basis, the map should be interpreted as a live description of current structure, not as a permanent historical truth.
The script also simplifies market behavior into a corridor framework. Strong news shocks, gap-like behavior, or abrupt volatility expansion can temporarily reduce corridor usefulness.
Drift Quality is a descriptive composite score, not an absolute truth metric. It should be used as context, not as a standalone trading decision.
HOW I THINK IT IS BEST USED
In my view, this tool works best when combined with discretionary chart reading or a broader structured workflow.
Examples:
- use it to decide whether a chart currently deserves trend-continuation thinking or range-neutral thinking
- use it to evaluate whether pullbacks are occurring inside a disciplined corridor or inside a deteriorating structure
- use it to compare the cleanliness of movement across symbols or timeframes
- use it as a chart-organization layer before applying separate execution logic
It is especially useful when the goal is not to chase events, but to understand the condition of the active movement map.
RISK DISCLOSURE
This script is an analytical indicator for chart interpretation. It does not provide financial advice, investment advice, or trading guarantees.
All trading decisions involve risk. Users should evaluate settings, market context, and risk management independently before using any indicator in live decision-making. Indicator

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 ( LSE: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:
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. Indicator

Indicator

Smart Money Dynamics Blocks - Pearson MatrixSmart Money Dynamics Blocks — Pearson Matrix
A structural fusion of Prime Number Theory, Pearson Correlation, and Cumulative Delta Geometry.
1. Mathematical Foundation
This indicator is built on the intersection of Prime Number Theory and the Pearson correlation coefficient, creating a structural framework that quantifies how price and time evolve together.
Prime numbers — unique, indivisible, and irregular — are used here as nonlinear time intervals. Each prime length (2, 3, 5, 7, 11…97) represents a regression horizon where correlation is measured between price and time. The result is a multi-scale correlation lattice — a geometric matrix that captures hidden directional strength and temporal bias beyond traditional moving averages.
2. The Pearson Matrix Logic
For every prime interval p, the indicator calculates the linear correlation:
r_p = corr(price, bar_index, p)
Each r_p reflects how closely price and time move together across a prime-defined window. All r_p values are then averaged to create avgR, a single adaptive coefficient summarizing overall structural coherence.
- When avgR > 0.8 → strong positive correlation (labeled R+).
- When avgR < -0.8 → strong negative correlation (labeled R−).
This approach gives a mathematically grounded definition of trend — one that isn’t based on pattern recognition, but on measurable correlation strength.
3. Sequential Prime Slope and Median Pivot
Using the ordered sequence of 25 prime intervals, the model computes sequential slopes between adjacent primes. These slopes represent the rate of change of structure between two prime scales. A robust median aggregator smooths the slopes, producing a clean, stable directional vector.
The system anchors this slope to the 41-bar pivot — the median of the first 25 primes — serving as the geometric midpoint of the prime lattice. The resulting yellow line on the chart is not an ordinary regression line; it’s a dynamic prime-slope function, adapting continuously with correlation feedback.
4. Regression-Style Parallel Bands
Around this prime-slope line, the indicator constructs parallel bands using standard deviation envelopes — conceptually similar to a regression channel but recalculated through the prime–Pearson matrix.
These bands adjust dynamically to:
- Volatility, via standard deviation of residuals.
- Correlation strength, via avgR sign weighting.
Together, they visualize statistical deviation geometry, making it easier to observe symmetry, expansion, and contraction phases of price structure.
5. Volume and Cumulative Delta Peaks
Below the geometric layer, the indicator incorporates a custom lower-timeframe volume feed — by default using 15-second data (custom_tf_input_volume = “15S”). This allows precise delta computation between up-volume and down-volume even on higher timeframe charts.
From this feed, the indicator accumulates delta over a configurable period (default: 100 bars). When cumulative delta reaches a local maximum or minimum, peak and trough markers appear, showing the precise bar where buying or selling pressure statistically peaked.
This combination of geometry and order flow reveals the intersection of market structure and energy — where liquidity pressure expresses itself through mathematical form.
6. Chart Interpretation
The primary chart view represents the live execution of the indicator. It displays the relationship between structural correlation and volume behavior in real time.
Orange “R+” and blue “R−” labels indicate regions of strong positive or negative Pearson correlation across the prime matrix. The yellow median prime-slope line serves as the structural backbone of the indicator, while green and red parallel bands act as dynamic regression boundaries derived from the underlying correlation strength. Peaks and troughs in cumulative delta — displayed as numerical annotations — mark statistically significant shifts in buying and selling pressure.
The secondary visualization (Prime Regression Concept) expands on this by illustrating how regression behavior evolves across prime intervals. Each colored regression fan corresponds to a prime number window (2, 3, 5, 7, …, 97), demonstrating how multiple regression lines would appear if drawn independently. The indicator integrates these into one unified geometric model — eliminating the need to plot tens of regression lines manually. It’s a conceptual tool to help visualize the internal logic: the synthesis of many small-scale regressions into a single coherent structure.
7. Interpretive Insight
This model is not a prediction tool; it’s an instrument of mathematical observation. By translating price dynamics into a prime-structured correlation space, it reveals how coherence unfolds through time — not as a forecast, but as a measurable evolution of structure.
It unifies three analytical domains:
- Prime distribution — defines a nonlinear temporal architecture.
- Pearson correlation — quantifies statistical cohesion.
- Cumulative delta — expresses behavioral imbalance in order flow.
The synthesis creates a geometric analysis of liquidity and time — where structure meets energy, and where the invisible rhythm of market flow becomes measurable.
8. Contribution & Feedback
Share your observations in the comments:
- The time gap and alternation between R+ and R− clusters.
- How different timeframes change delta sensitivity or reveal compression/expansion.
- Prime intervals/clusters that tend to sit near turning points or liquidity shifts.
- How avgR behaves across assets or regimes (trending, ranging, high-vol).
- Notable interactions with the parallel bands (touches, breaks, mean-revert).
Your field notes help others read the model more effectively and compare contexts.
Summary
- Primes define the structure.
- Pearson quantifies coherence.
- Slope median stabilizes geometry.
- Regression bands visualize deviation.
- Cumulative delta locates imbalance.
Together, they construct a framework where mathematics meets market behavior.
Indicator

Log Regression Oscillator Channel [BigBeluga]
This unique overlay tool blends logarithmic trend analysis with dynamic oscillator behavior. It projects RSI, MFI, or Stochastic lines directly into a log regression channel on the price chart — offering an intuitive way to detect overbought/oversold momentum within the broader price structure.
🔵Key Features:
Logarithmic Regression Channel:
➣ Draws a trend-based channel using logarithmic regression, adapting to price growth curvature over time.
➣ Features upper, lower, and optional midline boundaries to visualize trend flow and range extremes.
Oscillator Overlay (RSI / MFI / Stochastic):
➣ Projects your chosen oscillator inside the channel using dynamic polylines.
➣ Allows switching between RSI, Money Flow Index, or Stochastic for versatile momentum insight.
Threshold-Based Scaling:
➣ The top and bottom of the channel represent traditional oscillator thresholds (e.g., RSI 70/30).
➣ Users can modify the scale in settings to customize what "overbought" or "oversold" means visually.
Signal Line Integration:
➣ Adds a yellow moving average (signal line) for smoother confirmation of oscillator turns.
➣ Helps identify divergence, momentum shifts, and fakeouts with better clarity.
Live Oscillator Readout:
➣ Displays the real-time oscillator value at the right edge of the chart.
➣ Ensures traders stay aware of current momentum levels without switching panels.
🔵Usage:
Momentum Context:
➣ When the oscillator touches the upper regression band, it may signal local overbought pressure.
➣ Touching the lower band may indicate oversold conditions within the current log trend.
Divergence Detection:
➣ Use the oscillator’s behavior relative to the channel slope to spot divergence from price.
➣ For example, RSI rising inside a falling channel can flag early trend shifts.
Trend-Sensitive Entries:
➣ Combine oscillator signals with log channel direction to filter trades in trend alignment.
➣ Signal line crossovers inside the channel act as early warning for momentum turns.
The Log Regression Oscillator Channel transforms how traders view classic momentum tools. By embedding oscillators into a logarithmic trend structure, it offers unmatched clarity on momentum positioning relative to price expansion. Ideal for swing traders, mean-reverters, or trend followers looking to sharpen entries and exits with style. Indicator

Nadaraya-Watson: Envelope (Non-Repainting)Due to popular request, this is an envelope implementation of my non-repainting Nadaraya-Watson indicator using the Rational Quadratic Kernel. For more information on this implementation, please refer to the original indicator located here:
What is an Envelope?
In technical analysis, an "envelope" typically refers to a pair of upper and lower bounds that surrounds price action to help characterize extreme overbought and oversold conditions. Envelopes are often derived from a simple moving average (SMA) and are placed at a predefined distance above and below the SMA from which they were generated. However, envelopes do not necessarily need to be derived from a moving average; they can be derived from any estimator, including a kernel estimator such as Nadaraya-Watson.
How to use this indicator?
Overall, this indicator offers a high degree of flexibility, and the location of the envelope's bands can be adjusted by (1) tweaking the parameters for the Rational Quadratic Kernel and (2) adjusting the lookback window for the custom ATR calculation. In a trending market, it is often helpful to use the Nadaraya-Watson estimate line as a floating SR and/or reversal zone. In a ranging market, it is often more convenient to use the two Upper Bands and two Lower Bands as reversal zones.
How are the Upper and Lower bounds calculated?
In this indicator, the Rational Quadratic (RQ) Kernel estimates the price value at each bar in a user-defined lookback window. From this estimation, the upper and lower bounds of the envelope are calculated based on a custom ATR calculated from the kernel estimations for the high, low, and close series, respectively. These calculations are then scaled against a user-defined multiplier, which can be used to further customize the Upper and Lower bounds for a given chart.
How to use Kernel Estimations like this for other indicators?
Kernel Functions are highly underrated, and when calibrated correctly, they have the potential to provide more value than any mundane moving average. For those interested in using non-repainting Kernel Estimations for technical analysis, I have written a Kernel Functions library that makes it easy to access various well-known kernel functions quickly. The Rational Quadratic Kernel is used in this implementation, but one can conveniently swap out other kernels from the library by modifying only a single line of code. For more details and usage examples, please refer to the Kernel Functions library located here:
Indicator

GAURs Polynomial Regression ChannelsThanks to The Sweet Lord , here is the Gaur's Polynomial Regression Channel.
Its a Polynomial Regression Channel but applied a little differently. Wont go into technical details much. Overview of options is as follows-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Channel Options
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1. Degree of Polynomial: 1/2/3
Default = 3
Defines the degree of polynomials - 1,2,3. Note here, degree 1 will not be a straight line since its applied differently.
Try different degrees for different fits and market conditions.
2. Channel Length:
Default 30 (candles)
You can go beyond 100 or 200 candle lengths but smaller is the usual preference of Poly-Reg-channel traders. It all depends on market conditions and your style of trading. Do your research. I am usually comfortable with a range of 20-50 (in crypto markets).
3. Basis of Channel height/boundries: ATR/Manual
Default: ATR
ATR provides a dynamically adjusted entry/exit bounds of the channels. As ATR changes, the channel bounds also changes its height. It can also be fixed manually. Manual heights wont change automatically.
4. Basis of Y-Value: open/close/ sma / ema / wma /hilow
Default: close
Y- value is the y value of the (x,y) coordinates used while calculating the regression coefficients. Dont worry about it, its nothing serious.
5. Apply channel smoothning using sma?: Yes/No
Default: Yes
Without smoothning, the channel does not "look" good.
6. Shaded Area Height Percentage:
Its the extra margin for the channel. Its in percentage of the total height (defined 3 above) of channels. The shaded area provides an extra allowance for your entries or exits beyond the ATR or manual heights.
7. Plot RSI?: Yes/No
Default: Yes
Plots RSI (orange line in between the channel - its different from the dotted center line) considering the downbound of channels as 0 (oversold) and upbound of channels as 100 (overbought)
8. Plot 200 sma?: Yes/No
Default: Yes
It plots a 200 period fast (green) and 225 period slow (red) sma . I usually use two MAs. Its visually very easy to understand.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sample Strategy
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
You can develop your own strategy with the channels. But following is just one of the ways you can trade.
Best Application: Ranging markets. But can be happily used in volatile conditions, with a little experience.
1. SMA: -- (this condition is optional really)
If green (200) is above red (225) go only long. If red is above green go only short. Defines long term trend of the market.
2. Channel slope: -- (this stuff needs practice/experience)
Depending on the channel slope, like if its tending to go up or down, you can choose to take only short or long trades. It defines short term momentum of the market.
3. ATR based heights:
Since its ATR based, the channel height are our natural entry and exit points.
Long:
When price touches lower shaded area, consider possible long entry. Exit on price entering the upper shaded area.
Short:
Enter on upper bound shaded area, exit on lower.
4. RSI:
For additional conformations. Again note, the RSI considers the lower bound of channel as 0 and upper as 100. But since, the channel moves up and down, the RSI will also move not only as RSI but also with the channel. Meaning, say if the RSI is valued at 50, then it will be near the center of the channel but since the center changes as time and price changes, the RSI valued at 50 at different times will not be at the same horizontal level respect to the graph, although it will be at the same level (center) respect to the channel.
5. PRC Channel Percentage label:
This label is at the lower side a bit ahead of the current candle. Provides you info on what is the channel percentage. This is especially helpful in crypto markets to gauge your possible percentage profit where profits can be much higher than forex or other instruments. It can also helps you select a suitable market/instrument if the channels are based on ATR.
6. Extra indicators:
I usually use stochastic along with this setup for extra conformations.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Donate
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Use freely and donate generously if you find value. Your help will really help.
I had earlier provided BTC addresses for donations but it seems to violate TV House rules.
Hope they make TV coins redeemable in future.
- Pranav Joshi
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Extra Info
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// © cpranavjoshi
// special thanks to the "Trading View" people for providing this great platform for free
// ------------------------
// MATH
// ------------------------
// special thanks to an article on the web that provided layman friendly explanation of the maths
// unfortunately i wont be able to provide the link to that article owing to TV restrictions, though i sincerely would have liked to credit the author.
// Google search this phrase, and you should be able to get it in one of the first results - "polynomialregression Mathematics of Polynomial Regression"
// my regression math calculation is a further resolution upon the generalized matrix formula given in the that article.
// the generalized matrix looks scary but in fact its much simpler than one may assume
// the summation sign things are just float numbers that can be easily found out
// so we get a matrix with number of equations equal to the number of unknowns.
// e.g. if its a 3rd degree poly, it has 4 unknowns (c0,c1,c2,c3) with 4 equations as in the generalized matrix
// it can be resolved by simple algebra
// Note: the results have been verified with excel using same input data points.
// pine was difficult for me so i coded it in python first to verify
// ------------------------
// WHY
// ------------------------
// this script was coded because Pranav badly needed Polynomial channels (had used them in mt4 earlier)
// and at the time of this coding, i could not find any readily available script in the trading view public library ( tnx public)
// the complex math was probably the hurdle
// i m not good in maths, but by the Will of the Lord, i could resolve the issue with simple algebra and logic
// ------------------------
// PINE
// ------------------------
// i am just an average (even poor probably) programmer and pine script is not my language
// this is a humble attempt to write my first pine with whatever i could do quickly
// experts - feel free to develop if needed. have used some workarounds in drawings/plottings. rectify them if possible
//
//
// - Pranav Joshi Indicator
