SuperTrend Logistic Regression | Flux ChartsGENERAL OVERVIEW
The SuperTrend Logistic Regression indicator combines the classic SuperTrend trend-following tool with a self-training logistic regression model that assigns a probability percentage to every SuperTrend flip. Each time the SuperTrend changes direction, the indicator evaluates the market conditions at the flip across 14 features spanning candle structure, trend context, and technical indicators, then outputs a probability score between 0% and 100% representing how similar the current setup is to past flips that resolved profitably on the same chart.
The model trains itself in real time using past SuperTrend signals as labeled examples. Each historical flip becomes a training example: the features captured at the flip are paired with the outcome at the next opposite flip, producing a continuously growing dataset that the model uses to refine its weights. The probability displayed on each new flip reflects what the model has learned about this specific instrument and timeframe, not a universal assumption about what makes a good signal.
screenshot: Full chart showing SuperTrend line with multiple flips and probability labels
🔹What is the purpose of the indicator?
The indicator addresses a common problem with SuperTrend: not every flip leads to a sustained trend. Many flips occur during choppy or transitional conditions and reverse quickly, producing losing signals. By scoring each flip with a probability, traders get a quantitative sense of how much confidence the model has in that specific signal based on similar past setups. The indicator does not change the SuperTrend calculation itself, so every flip is still detected and visualized. The probability score adds a filtering layer that helps traders separate high-confidence flips from low-confidence ones.
🔹What is the theory behind the indicator?
The indicator is built on the idea that market behavior around trend reversals is not random. Certain combinations of candle structure, volatility conditions, volume patterns, and prior trend context tend to precede trends that follow through, while different combinations tend to precede trends that reverse quickly. Logistic regression is a statistical method well-suited to learning these relationships. Given a set of input features and historical outcomes, it produces a set of weights that map feature combinations to probability estimates.
In this indicator, each SuperTrend flip becomes a data point. The features at the flip are recorded, and the outcome is determined at the next opposite flip. If price moved in the signal's direction (higher for bull, lower for bear), the signal is labeled as a win. Otherwise, it is labeled as a loss. The model continuously retrains on this growing dataset, adjusting weights so that feature patterns historically associated with wins produce higher probabilities, and feature patterns associated with losses produce lower probabilities.
SUPERTREND LOGISTIC REGRESSION FEATURES
SuperTrend Core
Logistic Regression Model
Candle Features
Trend Context Features
Technical Features
Separate Bull and Bear Models
Exponential Decay Weighting
Minimum Sample Gating
Probability Labels and Filtering
Gradient-Colored SuperTrend Visualization
Optional Momentum Dots
Alerts
SUPERTREND CORE
The SuperTrend is the foundation of every signal. All detection, training, and prediction is tied to SuperTrend flips. The core SuperTrend calculation in this indicator is standard: ATR multiplied by a user-defined factor produces the trailing line, and a flip occurs when price crosses through the line, changing the direction state.
🔹How SuperTrend is calculated
The SuperTrend is derived from Average True Range (ATR) with a user-configurable period and factor. When the calculated line is below price, the indicator is in an uptrend state and the line acts as dynamic support. When the line is above price, the indicator is in a downtrend state and the line acts as dynamic resistance. A flip occurs at the exact bar where price crosses through the line, changing the direction from bullish to bearish or vice versa.
🔹Why SuperTrend was chosen
SuperTrend is one of the most widely used trend-following tools on PulseWire. It produces clean, deterministic signals with well-understood behavior. Rather than reinventing or modifying the underlying calculation, this indicator treats SuperTrend as a signal source and adds a separate statistical layer on top. This keeps the core behavior familiar to traders already using SuperTrend and ensures that every flip is still detected, regardless of the probability score.
🔹SuperTrend Inputs
Two inputs control the SuperTrend calculation: Factor (the ATR multiplier, default 3.0) and ATR Period (the number of bars in the ATR calculation, default 10). These correspond to the standard SuperTrend parameters. Changing these values affects where flips occur, which in turn affects what signals the model trains on.
LOGISTIC REGRESSION MODEL
Logistic regression is a statistical model that predicts binary outcomes from a set of input features. It takes each feature, multiplies it by a learned weight, sums the results, adds a bias term, and passes the total through a sigmoid function that maps the output to a probability between 0 and 1. The model learns the weights by comparing its predictions against actual outcomes and adjusting through gradient descent.
🔹What is Logistic Regression?
Logistic regression works by finding the set of weights that best separates winning signals from losing signals in feature space. A large positive weight on a feature means that higher values of that feature are associated with winning outcomes. A large negative weight means higher values are associated with losing outcomes. A weight near zero means the feature does not discriminate between winners and losers on this chart.
The sigmoid function is what turns the weighted sum into a probability. It outputs values near 0 when the weighted sum is very negative, values near 1 when the weighted sum is very positive, and values near 0.5 when the weighted sum is near zero. This gives the output a natural probability interpretation.
🔹How the model is trained
Training happens every time a new SuperTrend flip occurs. The indicator looks at all past resolved signals (signals that have already seen their next opposite flip and therefore have a known outcome) and runs gradient descent over them. Gradient descent calculates how much each weight should change to reduce the model's prediction error, then applies those changes iteratively. The indicator runs multiple training epochs on each update to ensure the weights converge reasonably well to the current data.
L2 regularization is applied to prevent any single weight from becoming extreme. Weight clipping further constrains weights to a reasonable range, avoiding instability when training data is thin or features are noisy. Together, these make the model more robust on small sample sizes.
🔹Outcome evaluation
For training to work, every historical signal needs a win/loss label. The indicator uses flip-to-flip evaluation: a bull signal is considered a win if the close at the next bear flip is higher than the close at the bull flip. A bear signal is considered a win if the close at the next bull flip is lower than the close at the bear flip. This matches the natural lifecycle of a SuperTrend trade, where entry and exit are both on flips.
🔹A Winning Signal Example
A winning bull signal forms when a bull flip occurs and, by the time the next bear flip occurs, the close at the bear flip is higher than the close at the bull flip. The probability label on the bull flip reflects the model's confidence at entry, while the outcome is confirmed at the next flip.
🔹A Losing Signal Example
A losing signal forms when price fails to move in the signal's direction by the next opposite flip. For example, a bull flip where price immediately reverses and ends lower than entry when the next bear flip occurs.
CANDLE FEATURES
Candle features describe the shape and volume of the flip candle itself, compared against recent averages. These are the most direct, local features the model uses. All candle features are toggleable in the "Candle Features" input group and are normalized to a range centered at zero, where zero means the feature value matches the recent average.
🔹Body
Body measures the size of the flip candle's body (the absolute distance from open to close) relative to the average body size over the recent lookback window. A value above zero means the flip candle had a larger body than recent candles, suggesting stronger conviction. A value below zero means the body was smaller than usual, suggesting indecision. The model learns whether strong-bodied flips tend to produce winning trends on this chart.
🔹Upper Wick
Upper Wick measures the length of the upper wick (the distance from the body top to the high) relative to recent average upper wicks. Long upper wicks can indicate rejection at highs, while short upper wicks suggest price accepted the top of the candle cleanly. The model learns how upper wick behavior at flips correlates with outcomes.
🔹Lower Wick
Lower Wick measures the length of the lower wick (the distance from the body bottom to the low) relative to recent average lower wicks. Long lower wicks can indicate rejection at lows, while short lower wicks suggest clean acceptance. This feature is disabled by default because it historically showed the weakest predictive signal across tested instruments.
🔹Range
Range measures the total high-to-low range of the flip candle relative to the recent average range. A wide-range flip candle indicates volatility expansion, while a tight-range candle suggests contraction. The model learns whether flips during volatility expansion tend to perform differently from flips during contraction.
🔹Volume
Volume compares the flip candle's volume to the average volume over the recent lookback window. Higher than average volume at a flip generally indicates stronger participation, while lower than average volume suggests weak conviction. The model learns how volume conviction at flips relates to trend outcomes.
🔹Delta Volume
Delta Volume estimates the net buying versus selling pressure within the flip candle by sampling 1-minute lower timeframe bars. The indicator distributes each 1-minute bar's volume to either the bullish or bearish side based on whether that bar closed up or down, then outputs the net direction as a feature value from fully bearish to fully bullish. This gives the model a finer-grained view of what happened inside the flip candle beyond the aggregate close.
TREND CONTEXT FEATURES
Trend context features describe the market conditions leading into the flip, not just the flip candle itself. These are calculated from the lookback window before the flip. All trend context features are toggleable in the "Trend Features" input group.
🔹Momentum
Momentum counts consecutive candle direction leading into the flip. Each bullish candle increments the streak in the positive direction, and each bearish candle increments it in the negative direction. The value is capped so very long streaks do not dominate. A strongly positive momentum value before a bull flip indicates buying was already building; a strongly negative value before a bull flip indicates a sharp reversal from recent selling. The model learns which regime tends to produce better bull outcomes.
🔹Pre-Flip Trend
Pre-Flip Trend averages the signed candle bodies (close minus open) over the recent lookback window, normalized by the average range. This gives a broader picture of whether the market was drifting up, drifting down, or chopping sideways before the flip. Unlike momentum, which only counts direction, pre-flip trend captures the magnitude of the directional bias.
🔹ATR Slope
ATR Slope compares the current ATR value to the ATR value from the lookback period ago. A positive slope means volatility is expanding into the flip, often associated with stronger follow-through. A negative slope means volatility is contracting, often associated with weaker signals. The model learns whether volatility expansion at the flip is a positive or negative factor for the specific instrument.
🔹Volume Trend
Volume Trend compares the average volume of recent bars to the average volume of bars further back. A positive value means participation is increasing; a negative value means it is fading. This feature is disabled by default because it historically showed weak signal across tested instruments.
🔹ST Distance
ST Distance measures how far price was from the SuperTrend line before the flip, normalized by ATR. A value near zero means the flip was a tight cross; a larger absolute value means price was well above or below the line and had to travel significantly to trigger the flip. The model learns whether tight crosses or aggressive breaks produce better outcomes.
🔹Trend Duration
Trend Duration measures how many bars the previous trend lasted before flipping. Short previous trends might indicate choppy conditions where flips come and go quickly. Longer previous trends might signal genuine exhaustion at reversal. The model learns how previous trend length relates to the success of the current flip.
TECHNICAL FEATURES
Technical features bring in classic technical indicator readings at the flip point. These are toggleable in the "Technical Features" input group.
🔹RSI
RSI (Relative Strength Index) is calculated with the same lookback as the other features and then centered around the 50 level. Values near the oversold end push the feature toward -1, values near the overbought end push it toward +1, and values near 50 are near zero. The model learns whether overbought or oversold RSI readings at flips correlate with different outcomes on the specific chart. On some instruments, flips at extreme RSI readings perform well; on others, they perform poorly. The model discovers this from the data.
🔹BB Position
BB Position measures where price sits within Bollinger Bands at the flip. Price at the lower band gives a value of -1, price at the basis gives 0, and price at the upper band gives +1. The Bollinger Bands are calculated with the same lookback as the other features. This feature captures mean-reversion versus breakout context: a flip near the lower band is different from a flip near the upper band, and the model learns which band positions tend to precede successful trends.
SEPARATE BULL AND BEAR MODELS
The indicator maintains completely independent models for bull signals and bear signals. Each has its own set of weights, its own training dataset, and its own prediction logic.
🔹Why separate models?
A single model that assumes features mean opposite things for opposite directions would be an oversimplification. For example, a long lower wick on a bull flip might indicate strong buyer defense, while a long lower wick on a bear flip might indicate weak sellers. These are different setups with different implications, and forcing them into one model with flipped signs would blur the signal.
By training separate bull and bear models, the indicator gives each direction room to learn its own relationships. A feature that strongly predicts bull wins might be irrelevant or even negatively correlated for bear wins, and the separate models can capture this without interference.
🔹Implementation
Each direction has its own array of signals and its own weights array. When a bull flip occurs, the bull signals array is updated and the bull model is retrained. When a bear flip occurs, the bear signals array and bear model are updated separately. The two models never share state, and their predictions are based only on their own training data.
EXPONENTIAL DECAY WEIGHTING
Not all training examples are equally relevant. Recent signals reflect current market conditions, while older signals may reflect regimes that no longer apply. The indicator addresses this with exponential decay weighting during training.
🔹How decay works
Each resolved signal is assigned a weight based on its age. The newest resolved signal gets the highest weight (1.0 after normalization), and older signals get progressively smaller weights based on a decay factor. A decay factor close to 1 means old and new signals are weighted roughly equally. A decay factor close to 0 means recent signals dominate and old signals are effectively ignored.
🔹Why decay is important
Markets change. A feature that strongly predicted wins six months ago might have weak or reversed predictive power now. Without decay weighting, the model would be slow to adapt to new conditions because old data would dilute the influence of recent outcomes. With decay weighting, the model naturally updates its weights to reflect the most recent dynamics while still using historical data to maintain stability.
PROBABILITY LABELS AND FILTERING
When a new flip passes the minimum sample gate, the indicator calculates the probability from the current feature values and the trained weights. This is displayed as a colored triangle label at the flip bar.
🔹Label Appearance
Bull flip labels appear below the bar as upward-pointing green triangles with the probability percentage inside. Bear flip labels appear above the bar as downward-pointing red triangles with the probability percentage inside. The colors are partially transparent so the labels do not obscure price action.
🔹High Probability Example
A high probability label means the model found the current flip's features similar to past flips that resolved as wins. For example, a bull flip with strong pre-flip momentum, expanding volatility, positive delta volume, and price well above the SuperTrend line might receive a probability above 65% if those conditions have historically preceded successful bull trends.
🔹Low Probability Example
A low probability label means the model found the current flip's features similar to past flips that resolved as losses. Low probability signals might share characteristics with flips that occurred during choppy conditions or weak momentum regimes.
🔹Min Probability Filter
A Min Probability input lets users hide labels below a confidence threshold. Setting it to 0 shows every signal. Setting it to 60 only shows labels where the model estimates at least 60% probability of a profitable outcome. This filter only affects visual display and alerts. The SuperTrend line and color change still appear on every flip, and the model still trains on every signal regardless of the filter.
🔹Interpreting the probability
The probability represents the model's estimate that the current flip will resolve profitably by the next opposite flip, based on how similar past flips performed. A 70% label does not guarantee a win; it means the model finds this flip's conditions more similar to past winners than past losers. Probabilities should be interpreted relative to the base rate (the overall percentage of past flips that won) rather than as absolute guarantees.
VISUAL CUSTOMIZATION
The indicator includes several visual elements that help traders see the SuperTrend state and the probability labels clearly.
🔹Gradient-Colored SuperTrend
The SuperTrend line is plotted with a color gradient based on how far current price has moved from the line since the most recent flip. The color intensifies as price extends further in the trend direction, giving a visual indication of how developed the trend is at any point. Fills between the body midpoint and the SuperTrend line reinforce this gradient effect.
🔹Momentum Dots
An optional momentum dots display overlays circles on the SuperTrend line with colors that shift between yellow and the trend color (green or red) based on price position. This provides a secondary visual cue for trend strength. The Enable Momentum Dots input toggles this display on or off.
INPUTS
🔹SuperTrend
Factor: ATR multiplier used in the SuperTrend calculation. Default is 3.0. Increasing this value makes the SuperTrend less sensitive and produces fewer, wider flips. Decreasing it makes the SuperTrend more sensitive and produces more frequent flips.
ATR Period: Number of bars used in the ATR calculation. Default is 10. Larger periods smooth the ATR, while smaller periods make it more reactive.
🔹Display
Enable Momentum Dots: Toggles the momentum dots overlay on the SuperTrend line. Default is on.
🔹Filters
Min Probability %: Minimum probability required for a signal label to appear on the chart. Default is 0 (show all signals). Setting this to a higher value hides lower-confidence signals.
🔹Candle Features
Body: Enable body size feature. Default is on.
Upper Wick: Enable upper wick feature. Default is on.
Lower Wick: Enable lower wick feature. Default is off.
Range: Enable candle range feature. Default is on.
Volume: Enable volume feature. Default is on.
Delta Vol: Enable delta volume feature using 1-minute LTF data. Default is on.
🔹Trend Features
Momentum: Enable consecutive candle direction feature. Default is on.
Pre-Flip Trend: Enable average directional body feature. Default is on.
ATR Slope: Enable volatility expansion feature. Default is on.
Volume Trend: Enable volume building feature. Default is off.
ST Distance: Enable distance from SuperTrend line feature. Default is on.
Trend Duration: Enable previous trend length feature. Default is on.
🔹Technical Features
RSI: Enable RSI feature. Default is on.
BB Position: Enable Bollinger Band position feature. Default is on.
ALERTS
The indicator includes alert conditions for the following events:
Bull Flip: Fires on a confirmed bullish SuperTrend flip that passes the Min Probability filter.
Bear Flip: Fires on a confirmed bearish SuperTrend flip that passes the Min Probability filter.
Users can configure alerts from the PulseWire alerts menu and choose which condition to subscribe to.
IMPORTANT NOTES
🔹Non-Repainting Behavior
Signals are detected and probability labels are calculated on the bar where the SuperTrend flip confirms. The probability value is based only on feature values at the time of the flip and the model weights as of that bar. The outcome label used for training is only recorded after the next opposite flip has occurred, so the current bar's prediction never uses future data.
🔹Probability Interpretation
The probability represents the model's learned estimate from past data on the current chart. It is not a guaranteed win rate. Markets can shift in ways the model has not yet seen, and sample size is always a limitation. Probabilities should be used as one input among many in a trading decision, not as a standalone signal.
UNIQUENESS
The SuperTrend Logistic Regression indicator takes a distinct approach to SuperTrend enhancement. Rather than altering the SuperTrend calculation itself, it preserves the classic SuperTrend behavior and adds a statistical layer on top that scores each flip independently. Every flip is still detected, so users never miss signals; the probability only determines what gets visually emphasized. The logistic regression implementation uses proper gradient descent with L2 regularization, weight clipping, and exponential decay weighting, making the training process stable and adaptive. Weights persist across bars and are refined with each new resolved signal rather than being recalculated from scratch. Separate bull and bear models learn direction-specific feature relationships independently, avoiding the oversimplification of assuming features have opposite meanings for opposite directions. All 14 features are toggleable, spanning candle structure, trend context, and technical indicators, so users can customize which market characteristics feed into the model. The probability is backed by a concrete, testable definition: the likelihood that the current flip will resolve profitably by the time the next opposite flip occurs, based on how similar past flips performed. This matches how SuperTrend is naturally traded on flip-to-flip cycles. Minimum sample gating ensures that probability labels only appear once the model has enough training data to make meaningful predictions, preventing misleading early signals. Together, these choices make the indicator a disciplined, data-driven extension of SuperTrend that adapts to each instrument and timeframe it runs on, rather than applying a one-size-fits-all scoring system. Indicator

Iterative Epanechnikov ChannelThe Iterative Epanechnikov Channel is a kernel-based smoothing and state estimation framework that applies an Epanechnikov kernel regression to price data, combined with a rolling standard deviation envelope to construct adaptive dynamic channel boundaries.
Unlike kernels with infinite support that allow distant historical observations to influence the estimate, the Epanechnikov kernel uses a compact weighting structure that strictly limits influence to a finite window. This ensures that only relevant, recent price information contributes to the regression, resulting in a more localized and structurally responsive estimate of price behavior.
The resulting channel is structurally responsive while remaining statistically efficient, making it particularly effective for tracking short-to-intermediate trend development, identifying localized overextension, and adapting quickly to evolving conditions.
Its primary utility is as a state estimation and structural tracking tool for price behavior, rather than a persistence-weighted regime model.
TRADING USES
The Epanechnikov Channel is best interpreted as a localized structural filter; within a multi-model framework, it captures the immediate structural state of price, helping distinguish early transitions, active trends, and short-term disequilibrium relative to slower, memory-weighted estimators.
Trend Detection
The channel basis line (Epanechnikov smoothed price) provides a responsive representation of underlying market direction. Sustained movement above or below the basis reflects directional continuation, while rapid shifts in the basis can indicate emerging changes in trend.
Structural Responsiveness
Due to the compact support of the Epanechnikov kernel, only recent price data contributes to the estimate. This produces sharper turning points and faster adaptation to new information, allowing the channel to respond efficiently to changes in market structure.
Mean Reversion Context
Because the estimator is more localized, price interacts with the channel boundaries more frequently. These interactions represent short-term deviations from the estimated state:
- Upper band: localized overextension
- Lower band: localized underextension
This makes the channel well-suited for mean reversion frameworks and volatility-based entry timing.
State Estimation
The channel functions as a continuous estimator of market state:
- The basis represents the inferred local price state
- The envelope represents dynamic volatility dispersion around that state
Compared to heavy-tailed kernels, the Epanechnikov-based state estimate is more sensitive to current conditions and less influenced by distant history, providing a clearer view of present market structure.
Volatility & Risk Context
The rolling standard deviation envelope expands and contracts based on realized volatility, providing a contextual risk framework. Wider channels indicate increased uncertainty and dispersion, while tighter channels indicate compression and lower variance conditions.
THEORY
The Epanechnikov kernel is a quadratic, compact-support kernel used in Nadaraya–Watson nonparametric regression, introduced by V. A. Epanechnikov (1969, Non-Parametric Estimation of a Multivariate Probability Density, Theory of Probability & Its Applications) as the mean squared error–optimal bounded kernel; in this implementation it is applied causally (non-repainting) and centered at the current bar using only historical data, with the original startAtBar offset removed to maintain proper kernel alignment with the estimation point.
It is defined as:
K(u) = 3/4 (1 − u²), for |u| ≤ 1
Where:
---> u represents normalized distance from the current observation
---> ℓ (lookback) defines the window over which the kernel operates
Unlike Gaussian kernels, which apply exponentially decaying weights over an infinite range, the Epanechnikov kernel assigns zero weight to all observations outside its finite support. This produces a strictly localized estimator that is both computationally efficient and statistically optimal in a mean squared error sense among bounded kernels.
Because the kernel is centered on the current observation and evaluated using only past data, the implementation remains causal and non-repainting while preserving the essential structure of kernel regression.
The rolling standard deviation complements this by measuring dispersion around the estimated state, forming a volatility-adaptive envelope. Rather than acting as a strict statistical confidence interval, it provides a dynamic representation of market expansion and contraction. The Epanechnikov kernel is a localized smoothing estimator rather than a structural similarity model, thus dispersion is defined using price-based volatility rather than kernel-weighted variance, providing a stable and interpretable envelope consistent with its role as a reactive state estimator.
The iterative implementation processes data sequentially (bar-by-bar), ensuring computational efficiency and making the indicator suitable for real-time use without repainting.
CALIBRATION
Calibration determines the balance between responsiveness, noise, and structural clarity.
Length (Lookback)
- Lower (8–16): More responsive, increased sensitivity to short-term structure
- Medium (20–40): Balanced for swing trading and intermediate regimes
- Higher (50–64+): Smoother output, reduced noise, slower response to turning points
Smoothing Mode (Single vs Double Pass)
Controls the tradeoff between responsiveness and stability:
Single Pass:
- Pure Epanechnikov regression
- Maximum responsiveness
- Faster detection of structural changes
- Increased sensitivity to noise
Double Pass:
- Applies the kernel regression twice
- Reduces variance and smooths fluctuations
- Produces cleaner structural output
- Introduces additional lag
This parameter allows users to tune the indicator based on whether early signal detection or stability is preferred.
MARKET USAGE
Stock, Forex, Crypto, Commodities, and Indices. Indicator

Sigma Channel [JOAT]JOAT Sigma Channel
Introduction
JOAT Sigma Channel is an open-source regression-based channel overlay built to identify the best-fit directional corridor across a search range of candidate windows.
It is designed to show whether price is traveling normally inside a fitted corridor, stretching away from it, reclaiming it, or moving into stress territory.
The problem it solves is model selection.
A fixed-length regression channel can look excellent in one regime and poor in the next.
If the market accelerates, slows down, or shifts its dominant drift horizon, a static window becomes less useful.
Sigma Channel solves that by searching a range of possible windows and selecting the strongest available fit.
That fit becomes the active corridor.
Around it the script builds multiple sigma tiers.
These tiers create a richer price-state map than a single upper and lower band.
The result is a more useful framework for reading acceptance, stretch, reclaim, and exhaustion.
Core Concepts
1. Multi-Window OLS Search
The script evaluates multiple candidate regression windows and scores them by fit quality.
for len = minWindow to maxWindow by stepWindow
= f_model(len)
2. Sigma-Tier Envelope Stack
The fitted centerline is surrounded by inner, core, outer, and stress layers.
3. Slope and Quality Diagnostics
The chosen model exposes both slope and fit quality.
4. Reclaim and Acceptance States
The script identifies when price reclaims or accepts back inside the corridor after extension.
5. Stress-State Shading
The most extreme statistical layer is visually emphasized.
6. Forward Projection
The active model projects forward to keep the corridor useful at the right edge.
7. Residual Awareness
Residual behavior helps judge whether the active model remains representative.
8. Gradient Candle Context
Bar coloring transitions with the current statistical state.
Features
Adaptive regression search: scans multiple windows instead of using one fixed length
Inner, core, outer, and stress bands: multiple sigma tiers for normal and abnormal travel
Slope-aware corridor logic: distinguishes positive and negative drift
Reclaim and acceptance events: return-to-channel behavior is identified
Stress shading: abnormal statistical extension is highlighted
Forward projection: the active corridor extends to the chart edge
Gradient candle tinting: bar color reflects the current z-state
Dashboard: slope, quality, window, and deviation state are summarized
Input Parameters
Model Search:
Minimum Window
Maximum Window
Window Step
Minimum R-Squared
Projection Bars
Deviation Envelope:
Inner Sigma
Core Sigma
Outer Sigma
Stress Sigma
Filter Stack / Visual System:
Bias EMA
ATR Length
Momentum RSI
Use EMA Bias Gate
Use RSI Gate
Use Volume Gate
Tint Bars
Show Projection
Show Dashboard
How to Use This Indicator
Step 1: Check the active slope and whether the corridor is upward, downward, or balanced.
Step 2: Check fit quality before trusting the active statistical path.
Step 3: Read whether price is inside the core corridor, at the outer layer, or in stress territory.
Step 4: Watch reclaims back into the channel after extension.
Step 5: Use the projection to organize the near-future chart space.
Indicator Limitations
The selected best-fit window can change as the market evolves
Linear regression becomes less representative in strongly nonlinear markets
Statistical extension does not guarantee immediate reversal
The indicator measures deviation from a model, not directional certainty
Originality Statement
This script is original in the way it combines adaptive regression selection, multi-tier sigma structure, reclaim logic, stress-state shading, and forward projection into one corridor framework.
The goal is not just to draw a regression channel.
The goal is to keep the active model responsive while preserving statistical context.
Disclaimer
This indicator is provided for educational and informational purposes only.
It is not financial advice.
Regression fit and statistical deviation do not predict future price with certainty.
Markets can remain extended or break away from the active fit entirely.
Best Use Cases
Reading whether price is behaving normally inside a fitted directional corridor
Identifying statistical stretch and stress states
Watching for reclaim behavior after extension
Combining statistical deviation with separate structure or liquidity analysis
Interpretation Notes
The channel should be trusted more when fit quality is stronger and the slope is clear.
Core travel is generally more normal than outer-band travel.
Stress states are especially useful when they coincide with separate structural or participation warnings.
The projection should be read as a continuation of the current best-fit model, not as a forecast guarantee.
Publication Notes
This script is intended to be published with a clean chart where the corridor, the active slope, and at least one reclaim or extension state are obvious.
The example chart should help the viewer understand how the band hierarchy works.
Avoid combining it with unrelated overlays in the publication image.
-Made with passion by jackofalltrades
Indicator

[ A L P H A X ] Slope Spectrum ProAlphaX Slope Spectrum Pro — Multi-Period Regression Oscillator, Adaptive Signal Line, Momentum Acceleration, Statistical Regime Detection, Classic & Hidden Divergence & Conviction Dashboard
AlphaX Slope Spectrum Pro is a professional-grade trend momentum oscillator built on a proprietary multi-period linear regression engine that scans across an entire range of lookback periods simultaneously and synthesizes them into a single adaptive oscillator value per bar. Rather than relying on a fixed-period momentum calculation, Slope Spectrum Pro measures the statistical slope of price across every period in the scan range and combines them using inverse-variance weighting — giving more influence to periods whose regression fits are more consistent, and less to those where price has been noisy. The result is a momentum oscillator that is simultaneously responsive and robust. On top of this engine sits a complete analytical layer: an adaptive signal line that changes speed with market conditions, a momentum acceleration histogram, statistical regime detection bands, classic and hidden divergence detection, regime-filtered entry signals with main chart overlay, and a live 10-row conviction dashboard.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📸 Visual Overview
AlphaX Slope Spectrum Pro in the oscillator pane — gradient-colored slope line with gradient fill, acceleration histogram in the background, adaptive signal line, regime threshold bands, divergence markers, bull/bear signal dots, main chart triangles, and the conviction dashboard
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔬 The Slope Engine — Multi-Period Regression Core
At the foundation of Slope Spectrum Pro is a multi-period linear regression scanner . On every bar, the engine runs a complete set of linear regressions across every period from your configured minimum to maximum, stepping at your chosen interval. With default settings of Min Period 10, Max Period 100, and Step Size 5, this means 19 independent regressions are computed and synthesized per bar.
Each regression fits a straight line to the logarithm of price over the lookback window and extracts the slope of that fit — a dimensionless measure of directional momentum at that timescale. Positive slope means upward momentum. Negative slope means downward momentum. Steeper slope means stronger momentum.
Inverse-Variance Weighting:
When Inverse-Variance Weighting is enabled, each regression period's slope is weighted by the inverse of its residual variance — how consistently price tracked the regression line over that lookback. A period where price followed its regression cleanly gets high weight. A period where price bounced erratically around the fitted line gets low weight. The result is that cleaner, more consistent trend periods contribute more to the final oscillator value than noisy, choppy periods — the oscillator becomes naturally less sensitive to random price fluctuations and more responsive to genuine directional momentum.
What the oscillator value means:
A value above zero means the weighted regression slope is net positive — more periods are trending upward than downward across the scanned range.
A value below zero means the weighted slope is net negative — dominant downward trend momentum.
The magnitude reflects how steep the consensus slope is. A large positive value means strong, consistent upward momentum. A value near zero means flat or contested momentum.
The oscillator is plotted as a gradient-colored line that transitions dynamically from bear red to bull green based on its rolling 200-bar min/max range — the stronger the current momentum relative to recent history, the brighter the color. A gradient fill between the oscillator line and the zero line reinforces the directional bias visually.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
〰 Adaptive Signal Line
The signal line tracks the slope oscillator — but instead of a fixed-period EMA, Slope Spectrum Pro uses an adaptive alpha-based EMA that changes its effective length based on current market conditions.
How it adapts:
The adaptation measures trend strength as how many standard deviations the current oscillator value is from its recent mean. When the oscillator is far from its mean — a clear, developing trend — the signal line shortens and reacts faster, following the oscillator closely. When the oscillator is near its mean — a ranging or choppy condition — the signal line lengthens, smoothing out minor oscillations and reducing false crossovers.
In a strong trend: the signal is tight. Crossovers happen quickly and reflect real momentum shifts.
In chop or range: the signal is loose. It takes a more significant oscillator move to produce a crossover, filtering out noise automatically.
The current effective signal length is shown live on the dashboard as EMA~N — you can see exactly how tight or loose the signal is at any moment. Adaptive speed can be toggled off for a consistent fixed-length signal.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡ Momentum Acceleration Histogram
Behind the oscillator line, a background acceleration histogram plots the rate of change of the slope oscillator — how fast momentum is building or fading right now.
Green columns — acceleration is positive. The slope oscillator is increasing. Momentum is building in the bullish direction.
Red columns — acceleration is negative. The slope oscillator is decreasing. Momentum is fading or building in the bearish direction.
Reading the acceleration alongside the main oscillator gives you a two-layer picture:
Oscillator above zero + green acceleration = strengthening bull momentum . The best time to enter or hold long.
Oscillator above zero + red acceleration = bull momentum peaking and fading . Consider reducing exposure or preparing to exit.
Oscillator below zero + red acceleration = strengthening bear momentum . Best time to hold or enter short.
Oscillator below zero + green acceleration = bear momentum fading . Watch for a potential reversal or crossover signal.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Statistical Regime Detection
Slope Spectrum Pro automatically classifies the current market environment into one of three regimes using a rolling statistical framework built from the oscillator's own mean and standard deviation:
Bull Regime — the oscillator is above the upper band (mean + N standard deviations). Background tints subtly green. Only bullish signals fire when regime filtering is enabled.
Bear Regime — the oscillator is below the lower band (mean − N standard deviations). Background tints subtly red. Only bearish signals fire when regime filtering is enabled.
Range Regime — the oscillator sits between the two bands. Background is a very faint neutral gray. No directional regime is confirmed. Regime-filtered signals are suppressed entirely.
Thresholds are calculated as oscillator mean ± (standard deviation × sensitivity multiplier) over the configured lookback. Increasing the sensitivity multiplier raises the bar required to enter Bull or Bear regime — only the strongest trend episodes qualify. Lowering it makes transitions more frequent.
This system directly controls signal quality when Regime-Filtered Signals is enabled — crossovers opposing the active regime direction are silently blocked before they ever reach the chart.
Regime bands on the oscillator — Bull threshold above, Bear threshold below, background tint reflecting the current zone
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
◆ Divergence Engine — Classic and Hidden
Slope Spectrum Pro detects four divergence types by comparing confirmed oscillator pivot highs and lows against confirmed price pivot highs and lows. All detections are confirmed on bar close only — no repainting.
Classic Divergences — Reversal Signals:
Classic Bull Divergence (DIV ▲) — price makes a lower low while the slope oscillator makes a higher low. Selling pressure is weakening even though price is still falling. A reversal upward may be building.
Classic Bear Divergence (DIV ▼) — price makes a higher high while the slope oscillator makes a lower high. Buying pressure is weakening even though price is still rising. A reversal downward may be building.
Hidden Divergences — Trend Continuation Signals:
Hidden Bull Divergence (H ▲) — price makes a higher low while the oscillator makes a lower low. Price held higher ground during the pullback — the uptrend is intact and continuation upward is probable.
Hidden Bear Divergence (H ▼) — price makes a lower high while the oscillator makes a higher high. Price failed to rally as high as before even as the oscillator rebounded — the downtrend is intact and continuation downward is probable.
Classic divergences warn of potential reversals. Hidden divergences confirm that pullbacks within a trend are likely to resume. Both are marked on the oscillator at the pivot bar with compact DIV or H labels. The divergence pivot lookback is configurable. Hidden divergence can be toggled independently from classic divergence.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 Entry Signals — Oscillator and Main Chart Overlay
Crossover signals fire when the slope oscillator crosses above or below the adaptive signal line, confirmed on bar close:
Bull Signal (●) — oscillator crossed above signal line. A small green dot appears on the oscillator.
Bear Signal (●) — oscillator crossed below signal line. A small red dot appears on the oscillator.
Regime filtering: When enabled, bull crossovers during a Bear Regime are blocked. Bear crossovers during a Bull Regime are blocked. Only signals aligned with the current statistical regime are displayed — this single filter eliminates a significant category of false signals.
Main chart overlay: When Overlay Candle Color is enabled:
A ▲ green triangle appears below the bar on the main chart at every bull signal.
A ▼ red triangle appears above the bar on the main chart at every bear signal.
Candles on the main chart are colored using the same gradient as the oscillator — chart candles reflect the current slope momentum state at a glance.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 Live Conviction Dashboard
A real-time 10-row readout of the oscillator's full internal state, updating on every bar close:
SAMPLES — number of regression periods computed per bar based on Min, Max, and Step settings.
MODE — INV-VAR WEIGHTED or SIMPLE AVERAGE aggregation.
OSC VALUE — live slope oscillator value to six decimal places, green above zero, red below.
REGIME — ▲ BULL ZONE, ▼ BEAR ZONE, or — RANGING. Row highlighted in the corresponding color.
MOMENTUM — ▲ BUILDING (acceleration positive) or ▼ FADING (acceleration negative). Row highlighted accordingly.
SIGNAL — ▲ BULL CROSS / ▼ BEAR CROSS when a crossover fired this bar, or ▲ ABOVE SIG / ▼ BELOW SIG for ongoing position.
SIG SPEED — current effective signal length as EMA~N, showing how tight or loose the adaptive signal is in real time.
DIVERGENCE — highest-priority active divergence: ▲ BULL DIV, ▼ BEAR DIV, ▲ HIDDEN BULL, ▼ HIDDEN BEAR, or — NONE. Row highlighted when active.
CONVICTION — a 0–4 confluence score. Each of the following adds 1 point: regime and oscillator sign agree; regime and acceleration agree; regime and signal side agree; any divergence is active. Score labels — LOW / MIXED (0–1), MODERATE (2), HIGH CONVICTION (3), MAX — ALL ALIGNED (4).
OSC (sigma) — the oscillator value expressed as standard deviations from its recent mean. Shows statistically how far momentum has moved from neutral — +2.5s means 2.5 standard deviations into bull territory.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡ Key Features
🔬 Multi-period regression engine — 19 independent regressions per bar (default) synthesized into one adaptive oscillator value
⚖ Inverse-variance weighting — consistent regression periods carry more weight; noisy periods are automatically discounted
〰 Adaptive signal line — effective EMA length speeds up in trends, slows in chop; current length shown live as EMA~N
⚡ Momentum acceleration histogram — rate-of-change of the oscillator, showing whether momentum is building or fading right now
📊 Statistical regime detection — three-zone classification (Bull / Bear / Range) using rolling mean ± standard deviation bands
🔒 Regime-filtered signals — crossovers opposing the current statistical regime are automatically suppressed
◆ Classic divergence — bull and bear reversal divergence between price pivots and oscillator pivots, bar-close confirmed
◆ Hidden divergence — trend continuation signals when price and oscillator diverge in the trend direction
🎯 Main chart overlay — bull/bear triangles on price chart and gradient candle coloring reflecting live slope momentum
🎨 Dynamic gradient oscillator color — live transition from bear to bull based on rolling 200-bar normalization
📋 Live 10-row conviction dashboard — samples, mode, osc value, regime, momentum, signal, signal speed, divergence, conviction score, sigma reading
🏆 4-point conviction scoring — real-time confluence count across regime, acceleration, signal, and divergence alignment
🔔 10 alert conditions — crossovers, classic and hidden divergences, confluence long/short, zero line crosses
🎨 14 user-configurable color inputs — every visual element independently themeable with AlphaX brand defaults
✅ Confirmed on bar close — no repainting on any signal, divergence, or regime transition
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙ Settings Reference
Slope Engine
Max Period — upper bound of the regression scan range (default: 100)
Min Period — lower bound of the scan range (default: 10)
Step Size — increment between scanned periods (default: 5). Smaller = more samples, smoother oscillator.
Inverse-Variance Weighting — weight each period by its regression consistency (default: on)
Source — price input for all regressions (default: close)
Adaptive Signal Line
Base Signal Length — signal EMA length in neutral conditions (default: 7)
Adaptive Speed — toggle adaptive EMA alpha on or off
Momentum Acceleration
Show Acceleration Histogram — toggle the background column histogram
Acceleration Smoothing — EMA smoothing period for acceleration (default: 3)
Regime Detection
Show Regime Bands — toggle threshold lines and background tinting
Regime Lookback — rolling window for mean and standard deviation (default: 200)
Regime Sensitivity (σ×) — standard deviation multiplier for thresholds (default: 0.5)
Divergence Engine
Show Divergences — toggle all divergence detection
Divergence Pivot Length — bars on each side to confirm a divergence pivot (default: 5)
Show Hidden Divergences — toggle hidden divergence independently
Entry Signals
Show Crossover Signals — toggle oscillator signal dots
Regime-Filtered Signals — suppress signals opposing the current regime
Overlay Candle Color — toggle main chart triangles and gradient candle coloring
Dashboard
Show Dashboard — toggle the dashboard panel
Position — Top Right, Top Left, Bottom Right, Bottom Left
Theme
Bull Primary / Bright / Dim — three shades of the bullish color family
Bear Primary / Bright / Dim — three shades of the bearish color family
Neutral / Neutral Light — neutral and secondary text colors
Accel Bull / Accel Bear — acceleration histogram column colors
Divergence Bull / Divergence Bear — classic divergence marker colors
Hidden Div Bull / Hidden Div Bear — hidden divergence marker colors
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 How to Trade with AlphaX Slope Spectrum Pro — Step by Step
Step 1 — Establish the regime and directional bias
Check the REGIME row. ▲ BULL ZONE = the market is in a statistically confirmed trend upward. ▼ BEAR ZONE = confirmed trend downward. — RANGING = no directional edge. Only trade in the direction of the active regime.
Check OSC (sigma). A reading above +2s means deep bull territory. Below −2s means deep bear territory. Near zero = flat momentum, no edge.
Step 2 — Read acceleration for entry timing
In a Bull Regime, wait for the acceleration histogram to turn green (▲ BUILDING on the dashboard). This means the slope oscillator is accelerating — momentum is growing, not just present.
The ideal entry timing: Bull Regime + oscillator above zero + acceleration building + oscillator above signal line.
Entering while acceleration is red (▼ FADING) in a bull regime risks entering as the current wave is losing steam.
Step 3 — Enter on a signal crossover
A bull signal dot (oscillator crosses above signal line) with regime filtering enabled is your entry trigger — counter-trend crossovers are already blocked automatically.
If Overlay is enabled, the ▲ triangle on the main chart confirms the exact entry bar.
The faster the adaptive signal (lower EMA~N), the tighter the crossover timing. In strong trends the signal shortens and reacts more quickly.
Step 4 — Upgrade conviction with divergence
A bull signal crossover occurring simultaneously with or just after a Classic Bull Divergence (DIV ▲) = high-probability reversal setup.
A bull signal crossover during an uptrend following a Hidden Bull Divergence (H ▲) = high-probability trend continuation setup.
Check CONVICTION. Score of HIGH CONVICTION (3) or MAX — ALL ALIGNED (4) means multiple independent factors agree. These are the setups to prioritize.
Step 5 — Exit when momentum confirms the move is ending
Acceleration histogram turning red (▼ FADING) while you are long = first sign the current wave is losing force. Begin monitoring for exit.
A bear signal crossover (oscillator crosses below signal line) = exit trigger.
A regime shift from Bull Zone to Ranging or Bear Zone = structural move is over. Exit and reset.
A Classic Bear Divergence appearing while you are in a long position = warning. Price is printing new highs the oscillator is not confirming. Reduce size or prepare to close.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔔 Alert Conditions
SSP — Bull Crossover — oscillator crossed above the adaptive signal line
SSP — Bear Crossover — oscillator crossed below the adaptive signal line
SSP — Classic Bull Divergence — price lower low, oscillator higher low confirmed
SSP — Classic Bear Divergence — price higher high, oscillator lower high confirmed
SSP — Hidden Bull Divergence — price higher low, oscillator lower low (trend continuation)
SSP — Hidden Bear Divergence — price lower high, oscillator higher high (trend continuation)
SSP — CONFLUENCE LONG — bull crossover occurring with bull or hidden bull divergence simultaneously
SSP — CONFLUENCE SHORT — bear crossover occurring with bear or hidden bear divergence simultaneously
SSP — Zero Line Cross Up — oscillator crossed above zero (macro bull momentum shift)
SSP — Zero Line Cross Down — oscillator crossed below zero (macro bear momentum shift)
All alert messages include {{ticker}} and {{interval}} for webhook integration.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
👥 Who This Is For
🧠 Systematic and quantitative traders — the regression engine, inverse-variance weighting, and statistical regime framework provide a mathematically grounded, objective momentum reading with no arbitrary indicator parameters to tune
📈 Trend traders on any instrument and timeframe — the multi-period scan adapts naturally to any market's momentum characteristics without manual recalibration
🔍 Divergence traders — four divergence types covering both reversals and trend continuations, all confirmed on bar close
⚡ Momentum traders — the acceleration histogram adds a layer no standard oscillator provides: not just where momentum is, but whether it is growing or shrinking right now
🎯 Precision entry traders — regime filtering, adaptive signal speed, and the conviction score ensure signals are only shown when multiple independent conditions agree simultaneously
🎨 Traders who customize their charts — 14 fully user-configurable color inputs, compatible with any chart theme
🔔 Alert-driven traders and bot operators — 10 alert conditions including a dedicated confluence alert for maximum-conviction setups
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📝 Notes
All signals are confirmed on bar close only. Slope Spectrum Pro does not repaint.
The oscillator value is in units of log-price per bar. The absolute value is very small (typically 0.000001 to 0.001 range) — what matters is the sign, the direction of change, and where it sits relative to regime thresholds and zero.
Wider Min–Max scan ranges produce a smoother oscillator capturing broader trend consensus. Narrower ranges are more reactive to short-term changes. Smaller Step Size = more periods sampled per bar = smoother result.
Regime Sensitivity is the most impactful setting after the scan range. At 0.5σ (default) the regime bands trigger relatively frequently. At 1.0–1.5σ, only very strong trend episodes qualify — signals become rarer but higher quality.
On very low timeframes the nested regression loop may be computationally intensive. Default settings are optimized for timeframes from 1 minute upward on standard instruments.
All theme color defaults are designed for dark chart backgrounds. Adjust Theme inputs if using a light background.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Disclaimer
This indicator is a technical analysis and visualization tool intended for educational and informational purposes only. It does not constitute financial advice or a recommendation to buy or sell any financial instrument. All signals are generated from historical and real-time price data using mathematical calculations — their accuracy or profitability is not guaranteed. Past performance does not guarantee future results. Always conduct your own analysis, use proper risk management, and consult a licensed financial advisor before making any trading decisions. The author accepts no responsibility for any losses incurred from the use of this indicator.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Built for traders who want to know not just where momentum is — but how it got there, how strong it is, and whether it is still building. Indicator

Bitcoin RSI Channel (2W, M)Bitcoin RSI Channel (2W, M)
The Bitcoin RSI Channel is a macro-analytical tool designed to identify long-term cyclical tops and bottoms of Bitcoin by applying linear regression modeling to the Relative Strength Index (RSI).
Traditionally, RSI levels like 70 and 30 are used as static markers for overbought and oversold conditions. However, as Bitcoin matures and its volatility dampens, its cyclical RSI peaks and troughs have historically followed a descending trajectory. This script accounts for that "fading" volatility by using mathematically fitted trendlines that track the actual historical extremes of Bitcoin’s momentum.
Main Objectives
Curve Fitting: Plots mathematically modeled linear regression lines through historical RSI peaks and bottoms, ensuring the channel remains as close as possible to the actual turning points of previous cycles.
Normalized View: Provides an optional "Normalized" mode where the dynamic channel is flattened into a 0-1 "Risk Metric" for easier comparison between cycles.
Main Chart Visualization: Directly projects overbought and oversold zones onto the price chart via plot coloring, allowing for a seamless confluence of price action and momentum analysis.
Cycle Forecasting: Designed as a high-timeframe tool to assist in predicting global market tops and generational buying opportunities.
IMPORTANT: Timeframe & Methodology
Please note that the regression lines in this script are specifically modeled for the 2-Week (2W) and Monthly (1M) timeframes.
These high timeframes were chosen because they significantly reduce market noise, making them superior for identifying global cycle shifts. The coefficients used in the code were derived from an approximation (fitting) of data points from 2011 through 2023.
Recommendation: Always wait for the candle to close on the 2W or Monthly timeframe to confirm a signal. Intra-candle fluctuations can be volatile and may provide premature signals before the period is finalized.
How to Use
Identifying Extremes: When the RSI enters the green "Buy Zone" or the red "Sell Zone," it historically indicates that Bitcoin has reached extreme oversold or overbought levels. These periods suggest the proximity of a potential cyclical bottom or top.
Visualizing on Price: These macro shifts are intuitively reflected through the price overlay on the main chart, providing immediate visual feedback on the current stage of the market cycle.
Strategic Caution: These zones have not been infallible in the past, and this indicator should not be used in isolation. Always seek confluence with other technical or fundamental analysis before making trading decisions.
User Tips
Clean View: You can hide the Bitcoin price bars on your main chart (via the Chart Settings) to focus entirely on the risk-based coloring provided by the indicator overlay.
Overlay Toggle: If you prefer to keep the indicator purely in its own pane, you can disable the "Plot on Main Pane" option in the script settings.
Settings & Parameters
View Mode: Switch between "Fit Lines" (standard RSI inside a diagonal channel) and "Normalized" (RSI converted into a Risk Metric).
Sell/Buy Zone Levels: Adjustable thresholds (default 0.90 and 0.10) to define your personal risk appetite for overbought and oversold conditions.
Plot on Main Pane: Toggle to enable/disable price bar colorization based on the current Risk Metric.
Limitations & Disclaimer
BTC Specificity: This indicator is purpose-built for Bitcoin. While you can load it on other symbols, the indicator pane will always calculate based on INDEX:BTCUSD data to maintain its cyclical logic. The main chart overlay, however, will color the plot of whatever instrument you are currently viewing.
Fixed RSI Optimization: The regression model is strictly optimized using the default RSI settings (14-period, Source: Close). The linear regression lines were fitted specifically to these values; therefore, the ability to modify the RSI length or source has been intentionally omitted from the settings. Changing these parameters would render the channel irrelevant, as the trendlines would no longer align with historical market extremes.
Static Modeling: The regression coefficients are "hardcoded" based on historical peaks and troughs up to 2023. As the market evolves, future cycles may require new approximations to account for shifting volatility.
No Guarantees: Mathematical models describe the past but do not guarantee the future. There is no guarantee that Bitcoin will reach the upper or lower boundaries in any given cycle, or that it will stay within them. Use this tool as one part of a comprehensive trading strategy.
Indicator

Regression Deviation Channel [JOAT]Regression Deviation Channel
Introduction
The Regression Deviation Channel is an institutional-style statistical trend and execution framework built around segmented regression, deviation envelopes, premium/discount zoning, breakout qualification, and risk mapping. Instead of acting like a plain moving-average channel, it models price through a best-fit regression path, measures dispersion with RMSE, then classifies where price is trading inside that structure: discount, equilibrium, or premium.
This version is designed to feel more like a desk-grade directional map than a simple overlay. It combines a frozen regression segment, internal band hierarchy, confidence scoring, Supertrend stack alignment, breakout detection, and ATR-based trade mapping into one visual structure. The goal is not just to show where price is, but whether the current move is balanced, compressed, expanding, or resolving.
Why This Indicator Exists
Most channels are too simple. They show boundaries but do not explain what price is doing inside those boundaries. This indicator was built to solve that by combining:
Segmented Regression: Tracks the current directional price path with a proper best-fit slope
Deviation Architecture: Uses RMSE to define statistically meaningful channel width
Premium / Discount Zoning: Splits the channel into expensive, fair value, and cheap territory
Breakout Qualification: Scores breakout quality using slope, participation, structure, and location
Trend Stack Context: Adds Supertrend alignment to distinguish strong directional pressure from noise
Trade Mapping: Builds clean ATR-based stop and multi-target projections after confirmed breaks
The result is a regression channel that does more than draw lines. It gives context, bias, execution framing, and visual hierarchy.
Core Components Explained
1. Segmented Regression Engine
= f_ols(winLen)
basisVal = intercept + slope * float(barsInSeg - 1)
upperVal = basisVal + rmse * multiplier
lowerVal = basisVal - rmse * multiplier
The core engine uses manual ordinary least squares regression to calculate the channel basis. Once the segment matures, the regression values are frozen and projected forward until price resolves beyond the envelope.
This “freeze and resolve” behavior keeps the channel visually stable instead of constantly shifting every bar.
2. RMSE Deviation Structure
Root mean squared error defines channel width, making the envelope responsive to how tightly price is hugging the trend.
Tight RMSE = cleaner trend structure
Wide RMSE = unstable or volatile structure
Internal bands split the envelope into inner, quarter, and outer zones
These nested bands create a true structure ladder instead of a single upper/lower shell.
3. Premium / Discount Channel Arrays
The channel is separated into three value areas:
Premium: Upper edge territory where price is extended and expensive relative to the current regression path
Equilibrium: The center band around fair value and neutral orderflow balance
Discount: Lower edge territory where price is cheap relative to the active path
This makes the indicator more useful for directional context:
Bull channels pressing premium signal strong continuation pressure
Bear channels pressing discount signal strong downside control
Repeated failure to hold premium/discount can signal exhaustion or rebalancing
4. Breakout Confidence Model
Breakouts are not treated equally. The indicator scores breakout quality using four ingredients:
Participation: Distance from the regression basis normalized by ATR
Slope Force: Strength of the normalized regression slope
Location: Whether price is already pressing the outer structure
Alignment: Whether price direction and Supertrend stack agree with the channel
breakoutConfidence = participation + slopeForce + location + alignment
This helps separate lazy drifts from high-quality channel resolution.
5. Supertrend Ribbon Stack
The Supertrend layer is not there as a generic add-on. It acts as a second-order directional filter.
Bull channel + bull Supertrend = higher-quality directional stack
Bear channel + bear Supertrend = stronger downside stack
When regression and Supertrend disagree, price is more likely in transition
The fill between regression basis and Supertrend visually shows whether pressure is aligned or conflicted.
6. ATR Risk Map
After a confirmed breakout, the indicator projects:
1 ATR-based stop level
3 reward targets using configurable risk-reward multiples
Auto-expiring lines so stale trade maps are removed
This gives the channel direct execution value instead of leaving the user to manually measure every move.
Visual Elements
Metallic Basis Line: Gold-toned centerline for the active regression basis
Outer Deviation Shell: Main channel boundaries with glow
Inner Structure Bands: Internal ladder for pressure staging
Premium / Discount Fills: Separate upper and lower value zones inside the channel
Equilibrium Fill: Neutral fair-value region
Supertrend Ribbon: Context layer showing secondary directional alignment
Iridescent Candles: Candle coloring that intensifies as control and confidence improve
Breakout Markers: Compact signals for confirmed resolves
Readiness Diamonds: Pre-break alignment markers when channel conditions are strong
The visual hierarchy is designed so you can read the channel at a glance without relying on heavy objects or clutter.
Dashboard
The dashboard is intentionally compact and fixed to the right side. It shows only the highest-signal metrics:
Bias
Regime
Flow
Channel Position
Confidence
Compression
Trend Stack
Trade Map
How to Use This Indicator
Step 1: Identify Channel Bias
Check whether the regression slope is bullish or bearish. That defines the primary directional path.
Step 2: Read Value Location
See whether price is trading in premium, equilibrium, or discount. This tells you whether price is extended or balanced inside the channel.
Step 3: Watch Trend Stack Alignment
When Supertrend and regression agree, directional pressure is cleaner. When they disagree, reduce conviction.
Step 4: Monitor Confidence
Use the breakout confidence score to judge whether price is merely drifting or building a meaningful resolution.
Step 5: Trade the Resolve, Not the Noise
Use breakout markers and ATR map levels when price exits the frozen envelope with qualified pressure.
Best Practices
Use higher timeframes for cleaner channel geometry
Treat equilibrium as fair value, not a signal by itself
Bull channels work best when premium holds and pullbacks respect the inner bands
Bear channels work best when discount holds and rallies fail at internal structure
High compression followed by rising confidence often precedes expansion
Use the risk map for framing, not blind automation
Indicator Limitations
Regression is still a model of recent price, not a guarantee of future direction
Sudden event-driven moves can invalidate the frozen segment quickly
Premium and discount are relative to the current channel, not absolute market value
High breakout confidence can still fail in thin or news-driven markets
Short segments increase responsiveness but also increase noise
Technical Implementation
Built in Pine Script v6 using:
Manual OLS regression
RMSE deviation envelopes
Segment freeze-and-resolve logic
Internal quarter and inner bands
Premium/discount channel zoning
Supertrend stack integration
Breakout confidence scoring
ATR-based stop and target map
Compact institutional dashboard
Originality Statement
This indicator is original in how it treats a regression channel as a full market-state framework instead of a static overlay. The value is not just in plotting upper and lower lines, but in combining:
Segment freezing
Internal value zoning
Directional stack confirmation
Breakout qualification
Execution mapping
Each layer contributes different information: regression defines path, RMSE defines structure, premium/discount defines value, Supertrend defines stack, and confidence defines quality.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Regression channels, premium/discount zones, and breakout scores are analytical tools, not guarantees of market outcome. All trading decisions remain the responsibility of the user.
-Made with passion by officialjackofalltrades
Indicator

Artemis Regression Bands🟦 Artemis Regression Bands is a kernel-driven volatility envelope indicator built on the KernelLens Nadaraya–Watson regression library (a_jabbaroff/KernelLens/1). A single kernel estimate — selectable from eight classical kernel families — anchors the Fair Value line. Around it, three residual-standard-deviation bands (±1σ, ±2σ, ±3σ) fan outward with either Linear or Exponential spacing, producing a statistically grounded envelope far cleaner than the classical close-stdev approach used by legacy Bollinger-style indicators. A four-gate Romb signal engine overlays buy / sell diamond markers when price pokes through the outermost enabled σ boundary and reverses back inside.
🟦 HOW IT WORKS
Artemis calls the KernelLens library's unified dispatcher once per bar to build the Fair Value line, then queries three additional library exports to derive the band widths, slope direction, and residual σ:
```
fair = kl.estimate (type, src, ℓ, α, period, phase, filter)
sigma = kl.confidenceBand(src, fair, window)
slopeVal = kl.slope (fair, 1)
trendSt = kl.trendState (fair, 1)
dev = baseMult · sigma
upper1 = fair + 1·dev lower1 = fair − 1·dev
upper2 = fair + 2·dev lower2 = fair − 2·dev
upper3 = fair + k3·dev lower3 = fair − k3·dev (k3 = 3 Linear | 4 Exp)
```
The library handles all weighted-sum computation, loop-depth selection, NA-safe iteration, division-by-zero guards, and input validation internally. Artemis contains zero kernel math — every bug fix or optimization in the library automatically propagates to this indicator.
🟦 KERNEL LIBRARY INTEGRATION
Artemis imports the published KernelLens library and uses the following exports:
| Library Export | Used For |
|---|---|
| `kl.estimate()` | Unified dispatcher — routes to the correct kernel based on the user's Kernel Type dropdown. Called once per bar to produce the Fair Value line. |
| `kl.confidenceBand()` | Rolling standard deviation of the (source − Fair Value) residual. Drives the band half-widths on every bar. |
| `kl.slope()` | Discrete first derivative of the Fair Value line. Feeds trend flip alerts. |
| `kl.trendState()` | Ternary classifier (+1 rising / −1 falling / 0 flat) of the Fair Value line. Drives the slope-adaptive color, the kernel trend confluence filter, and the dashboard Trend row. |
Every regression computation — kernel weight evaluation, NA-safe summation, bandwidth-aware loop termination, residual stdev, finite-difference slope — is delegated to the library. The indicator itself only orchestrates the four library calls and layers the visual pipeline on top.
🟦 EIGHT KERNEL FAMILIES
A single Kernel Type dropdown selects any of the eight kernels shipped with the KernelLens library. Each is a different mathematical smoother with its own statistical character:
| Kernel | Formula | Best For |
|---|---|---|
| Rational Quadratic | (1 + d² / (2·α·ℓ²))^(−α) | Multi-scale mixer; α controls stretch. Recommended default. |
| Gaussian / RBF | exp(−d² / (2·ℓ²)) | Canonical smoother; infinitely differentiable. |
| Periodic | exp(−2·sin²(π·d/p) / ℓ²) | Resonates with a known repetition distance p. |
| Locally Periodic | Periodic × Gaussian | Seasonal patterns with slow trend drift. |
| Epanechnikov | (3/4)·(1 − u²), \|u\| ≤ 1 | MSE-optimal; compact support, no tail contamination. |
| Tricube | (70/81)·(1 − \|u\|³)³, \|u\| ≤ 1 | LOWESS standard; near-Gaussian compact profile. |
| Triangular | (1 − \|u\|), \|u\| ≤ 1 | Simplest compact kernel; cheapest to compute. |
| Cosine | (π/4)·cos(π·u/2), \|u\| ≤ 1 | Raised-cosine; smooth boundary transition. |
Because the dropdown feeds the library's `kl.estimate()` dispatcher directly, every kernel inherits the same three-mode filter layer (No Filter / Smooth / Zero Lag) and the same non-repainting guarantees — there is no special case per kernel in Artemis.
🟦 FILTER LAYER
A second dropdown applies an optional post-processing layer on top of the raw Nadaraya–Watson estimate:
| Filter | Formula | Trade-off |
|---|---|---|
| No Filter | ŷ = ŷ_raw | Single-pass kernel. Rawest output, most reactive. |
| Smooth | ŷ = K(ŷ_raw) | Double-pass — kernel applied to its own output. Cleaner line, slightly more lag. |
| Zero Lag | ŷ = 2·ŷ_raw − K(ŷ_raw) | Ehlers de-lagging identity — sharpens edges without adding lag. |
The filter is resolved entirely inside `kl.estimate()`, so switching modes incurs no runtime cost beyond the extra kernel pass.
🟦 RESIDUAL-σ BAND ENGINE
Artemis bands are statistically grounded on the residual standard deviation — not on raw close stdev as in classical Bollinger indicators. The residual is computed as:
```
residual = src − fair
sigma = ta.stdev(residual, window) // via kl.confidenceBand()
```
Because Fair Value is already an unbiased local estimate of the source, the residual is a zero-mean noise series and its stdev captures **only the portion of price variance that the kernel could not explain**. This produces three benefits over the classical approach:
1. **Tighter bands in trending regimes** — close-stdev widens during strong trends because the trend itself inflates the variance; residual-σ does not, because the kernel absorbs the trend.
2. **Faster reaction to volatility regime changes** — residual-σ tightens as soon as the kernel fits well, and widens the instant the market breaks out of the kernel's neighborhood.
3. **True statistical interpretation** — under the assumption of locally Gaussian residuals, ±1σ / ±2σ / ±3σ enclose approximately 68 % / 95 % / 99.7 % of near-term price variation. The traditional close-stdev envelope carries no such interpretation.
A dedicated Residual σ Window input controls the lookback; typical values range from 50 (reactive, scalping) to 300 (stable, position trading).
🟦 BAND SPACING MODES
Two spacing presets shape the outward fan of the three σ bands:
| Mode | Multipliers | Character |
|---|---|---|
| Linear | 1·, 2·, 3· | Classical Bollinger-style uniform steps. Predictable, symmetric. |
| Exponential | 1·, 2·, 4· | Fibonacci-flavored — outer band (4σ) is reserved for genuine blow-off excursions. |
Base Multiplier scales all three bands uniformly (default 1.0). The formula is:
```
band_level = fair ± (baseMult · k · sigma) k ∈ {1, 2, k3}
```
where k3 resolves to 3 in Linear mode and 4 in Exponential mode. Every band has an independent visibility toggle, so minimalist users can run ±1σ only, swing traders ±3σ only, or any combination.
🟦 FOUR-GATE ROMB SIGNAL ENGINE
The Romb engine prints buy / sell diamond markers when price pokes through the outermost enabled σ band and reverses back inside. Four sequential gates protect against false entries:
| Gate | Logic | Purpose |
|---|---|---|
| 1 — Crossover | `ta.crossunder(high, triggerUp)` / `ta.crossover(low, triggerDn)` | Detects the reversal back through the outer band. |
| 2 — Warm-up | Residual σ computable for N consecutive bars | Blocks signals during the early kernel-settlement window. |
| 3 — Confluence | Fair Value slope aligns with the reversal direction | Optional PRO filter — Sell Romb requires falling kernel, Buy Romb requires rising kernel. |
| 4 — Cooldown | Minimum bar gap since the last same-side Romb | Prevents signal clustering on a single extended poke-and-reverse sequence. |
A Signal Mode toggle layers on top:
- **Confirmed** — signals fire only on `barstate.isconfirmed`; zero repaint on closed bars.
- **Realtime** — signals fire live on the current open bar; faster reaction, may vanish if price reverses before close.
Each confirmed signal is rendered as a two-layer neon diamond:
- **Halo** — `size.small`, 40 % transparent theme hue (glow layer).
- **Core** — `size.tiny`, fully opaque theme hue (bright center).
The halo renders first so the core sits cleanly on top, producing a sharp luminous marker that reads instantly even on dense price charts.
🟦 ADAPTIVE OUTER-BAND TRIGGER
The Romb engine does not hard-code the ±3σ band as the signal trigger. Instead, it resolves the outermost currently-enabled band on every bar:
```
triggerUp = show3 ? upper3 : show2 ? upper2 : show1 ? upper1 : na
triggerDn = show3 ? lower3 : show2 ? lower2 : show1 ? lower1 : na
```
The result is an envelope that respects the user's visibility choices:
| Visible Bands | Romb Fires At |
|---|---|
| ±1σ + ±2σ + ±3σ | ±3σ (default) |
| ±1σ + ±2σ | ±2σ |
| ±1σ only | ±1σ |
| All off | no signals |
Diamond positioning follows the same trigger, so the glyph always floats ~0.3σ outside whatever envelope is actually drawn on the chart. The behavior matches user intent: the band I can see is the band that fires signals.
🟦 NON-REPAINTING BEHAVIOR
Artemis inherits non-repainting behavior directly from the KernelLens library's `_phase` parameter. A single Phase input (default 2) shifts the kernel center into the past by that many bars:
- **Phase = 0** — live estimate, flickers on the current bar (real-time only; history is immutable).
- **Phase = 1** — 1-bar lag, non-repainting once the bar is confirmed.
- **Phase = 2** — recommended balance between freshness and stability (default).
- **Phase = 3+** — extra margin against erratic ticks, higher lag.
Historical repainting never occurs at any phase value. The library contains no `request.security` calls, no lookahead, and no array rotation that could leak future data. Every historical bar's plotted Fair Value, band, and Romb signal is final once confirmed.
🟦 VISUAL PIPELINE
**σ Band Outlines** — Three upper bands (±1σ / ±2σ / ±3σ) in progressively lighter `thBear` hues, three lower bands in progressively lighter `thBull` hues. Hidden bands collapse to na via their individual visibility toggles; the outline widths share a single Band Line Width input.
**Tapered Gradient Fills** — Six fills drawn between the Fair Value line and each σ band. Opacity scales progressively from ±1σ (densest, most opaque) to ±3σ (lightest, most transparent), creating a halo that mirrors the statistical density of price residuals under normality. Master Fill Opacity input (0 = invisible, 100 = fully opaque) scales all three fills uniformly.
**Fair Value Line** — Slope-adaptive color resolver swaps between `thBull` (rising kernel) and `thBear` (falling kernel). Flat bars retain the previous color so the line never flashes neutral on a perfectly horizontal tick. Width is user-controlled (1–5 px).
**Romb Diamonds** — Two-layer neon glow at the adaptive trigger band; halo + core rendering described above.
**Bar Coloring** — Optional theme-aware candle coloring driven by the Fair Value slope. Off by default; when enabled it paints every bar with the active theme's bull / bear hue based on the current trend state.
🟦 THEME SYSTEM
Twelve cohesive color palettes drive every visual component — Fair Value line, σ band outlines, gradient fills, Romb diamonds, bar coloring, and dashboard accents — all sharing the same four color axes (`thBull`, `thBear`, `thNeutral`, `thSignal`):
| Theme | Bull | Bear |
|---|---|---|
| Tropic | Cyan steel | Deep orange |
| Amber | Warm amber | Indigo blue |
| Pastel | Sky blue | Soft lavender |
| Cyber | Neon lime | Hot crimson |
| Helios | Bright gold | Scarlet |
| Electric | Electric aqua | Magenta |
| Candy | Neon green | Hot pink |
| Bloomberg | Terminal orange | Cyan |
| Solar | Solarized olive | Crimson |
| Royal | Imperial gold | Deep purple |
| Midnight | Deep navy | Dark crimson |
| Graphite | Near-black | Silver grey |
A separate Display Mode toggle (Dark / Light) controls the dashboard palette independently of the chart theme — so a Bloomberg chart theme with a Light dashboard is a valid configuration, as is Midnight chart + Dark dashboard.
🟦 DASHBOARD
A 2-column, 12-row theme-aware status panel that updates only on the last bar (zero historical overhead). Supports Dark and Light display modes, six docking positions, and four text sizes. Renders via `force_overlay = true` on the main price chart.
| Row | Label | Content |
|---|---|---|
| Header | ARTEMIS | DARK / LIGHT |
| Theme | Theme | Active palette name |
| Kernel | Kernel | Selected kernel type |
| Divider | REGRESSION | — |
| Bandwidth | Bandwidth ℓ | Bandwidth value / Phase offset φ |
| Filter | Filter | No Filter / Smooth / Zero Lag |
| Fair Value | Fair Value | Current Fair Value in chart mintick format |
| Divider | BANDS | — |
| Spacing | Spacing | Linear 1·/2·/3· or Exp 1·/2·/4· |
| Residual σ | Band σ | Rolling residual standard deviation |
| Trend | Trend | ▲ BULL / ▼ BEAR / ━ FLAT (bull/bear colored) |
| Last Romb | Last Romb | ▲ BUY (N ago) / ▼ SELL (N ago) — bull/bear colored |
**Zebra-stripe layout** — alternating `dashBg` / `dashBgAlt` row backgrounds improve scan-ability on narrow cells. Section dividers (REGRESSION, BANDS) use a third background tone (`dashSection`) with the theme's bull accent as the header color — preserving brand identity across both Display Modes.
🟦 ALERT CONDITIONS
Six opt-in alert conditions, each gated by its own toggle:
| Alert | Fires When |
|---|---|
| Bullish Trend Flip | Fair Value slope crosses from ≤ 0 into positive territory |
| Bearish Trend Flip | Fair Value slope crosses from ≥ 0 into negative territory |
| Buy Romb | Confirmed Buy Romb fires — all four signal gates passing |
| Sell Romb | Confirmed Sell Romb fires — all four signal gates passing |
| Upper Band Touch | Price touches or exceeds the outermost enabled upper band |
| Lower Band Touch | Price touches or falls below the outermost enabled lower band |
All alerts use `alertcondition()` for maximum compatibility with PulseWire's alert system including webhooks. Messages are structured as `"Artemis Regression Bands: "` for easy parsing in downstream automation. Touch alerts are off by default (can be noisy in trending markets); the four core alerts are on by default.
🟦 RECOMMENDED PRESETS
| Style | Bandwidth ℓ | Filter | Phase | Spacing | σ Window | Chart |
|---|---|---|---|---|---|---|
| Scalper | 10–20 | No Filter | 1 | Linear | 50–80 | 1m–5m |
| Day Trader | 20–40 | Smooth | 2 | Linear | 80–120 | 15m–1h |
| Swing | 30–60 | Smooth | 2 | Linear or Exp | 100–200 | 4h–1D |
| Position | 60–120 | Smooth or Zero Lag | 3 | Exp | 200–300 | 1D–1W |
**Kernel type tuning**
- **Trending instruments** — Rational Quadratic (α = 1–3) or Gaussian. Smooth multi-scale response.
- **Mean-reverting instruments** — Epanechnikov or Tricube. Compact support keeps the band envelope tight.
- **Session-cyclic patterns** — Periodic (with p = session length in bars) or Locally Periodic. Resonates with known cycles.
**Romb filter tuning** — Keep Kernel Trend Confluence ON for high-conviction setups only. Switch OFF on range-bound instruments to capture both sides of the oscillation.
🟦 COMPATIBILITY
- Pine Script v6
- All exchanges, all asset classes (crypto, forex, equities, commodities, indices)
- All timeframes (1 minute through Monthly)
- Both Dark and Light chart themes — the Display Mode toggle controls dashboard palette independently
- No exchange-specific logic — fully deterministic
🟦 TECHNICAL NOTES
- **Library dependency** — `import a_jabbaroff/KernelLens/1` — all kernel regression, residual σ, slope, and trend-state math is delegated to the published library.
- **Plot budget** — 6 band plots + 1 Fair Value anchor + 1 Fair Value visible + 6 gradient fills + 4 Romb plotshapes + 1 barcolor = well under Pine's plot limits.
- **Table** — Single `var table` rebuilt on `barstate.islast` with `force_overlay = true`; zero historical overhead.
- **Signal state** — Two `var int` cooldown anchors (`lastSellBar`, `lastBuyBar`) seeded at −10000 so the very first bar always passes the gap test. A `var int stabCount` warm-up counter blocks signals during early kernel settlement.
- **No persistent drawing objects** — no `box.new`, `line.new`, no array rotations; every visual is either a plot or a single-bar plotshape.
- **Adaptive trigger resolver** — Romb crossover detection, touch alerts, and diamond positioning all read from the same `triggerUp` / `triggerDn` resolver, so band visibility toggles stay semantically coherent across every layer of the indicator.
- **Non-repainting** — inherits from the library's `_phase` parameter; no `request.security`, no lookahead, no future-bar leakage at any phase value.
🟦 DISCLAIMER
Artemis Regression Bands is a technical analysis indicator built on the KernelLens Nadaraya–Watson regression library. It is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output. The residual-σ envelope describes past dispersion around the kernel estimate — not a forecast of future range — and should always be combined with broader context: higher-timeframe structure, volatility regime, liquidity, news, and risk management.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor. Responsibility for any trading decisions rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of Artemis Regression Bands or the underlying KernelLens library. Indicator

Iterative Locally Periodic EnvelopeThe Iterative Locally Periodic Envelope is a phase-conditioned kernel estimator with temporal locality and endogenous dispersion modeling, implemented as a Nadaraya–Watson estimator under a locally periodic kernel.
The locally periodic kernel defines similarity through cyclical phase alignment modulated by temporal proximity. Observations contribute to the estimator based on both their position within a repeating cycle structure and their recency, emphasizing structural recurrence with sensitivity to local regime conditions.
The indicator computes a latent equilibrium using a kernel-weighted mean and a dispersion measure using kernel-weighted variance under the same weighting structure. The resulting envelope reflects cycle-consistent deviation with temporal locality, rather than a conventional volatility band. All values are computed exclusively on closed historical bars using a bounded lookback window to ensure non-repainting behavior.
This indicator belongs to a broader class of iterative kernel-based envelopes that includes Gaussian, Rational Quadratic, and Periodic variants. All share a common Nadaraya–Watson estimation framework, differentiated by their kernel.
TRADING USES
The Iterative Locally Periodic Envelope is best interpreted as a cycle-aware structural estimator with adaptive temporal sensitivity, rather than a volatility-based band. The temporal locality component allows the estimator to adapt more readily to emerging regime shifts than the pure periodic variant.
Equilibrium Tracking
The latent equilibrium represents the phase-conditioned central tendency of price under locally periodic similarity weighting. Oscillations around this level reflect movement within a repeating structural cycle, with more recent phase-aligned observations contributing more strongly than temporally distant ones.
Cycle Regime Structure
The envelope emphasizes repeating structural behavior through phase recurrence weighting, modulated by temporal decay. Changes in symmetry, amplitude, or persistence of oscillation around the latent equilibrium may indicate transitions between cyclical regimes.
Mean Reversion Within Cycles
When a stable periodic structure is present, deviations from the latent equilibrium may revert toward phase-consistent levels. Mean-reversion behavior is conditioned on both cycle structure and temporal proximity.
Structural Extremes
Extreme deviations relative to the envelope correspond to phase-inconsistent states where cyclical structure becomes stretched or destabilized. Because the kernel incorporates temporal decay, these conditions are identified with greater sensitivity to recent price behavior.
State Estimation
The system defines a latent equilibrium as the inferred central cyclical state under joint phase and temporal weighting, with dispersion derived from kernel-weighted variance under identical constraints. This produces a structurally consistent representation of the market state that is sensitive to both cyclical position and local regime conditions.
LOCALLY PERIODIC ENVELOPE CONSTRUCTION
The envelope is constructed using kernel-weighted variance under the same locally periodic similarity measure used to estimate the latent equilibrium. The latent equilibrium defines the central state estimate and kernel-weighted variance defines dispersion under identical weighting, producing an endogenously determined envelope. The band width is fixed at ±1 kernel standard deviation with no multiplier, ensuring dispersion remains an intrinsic property of the locally periodic similarity structure rather than an externally imposed scaling parameter.
THEORY
The locally periodic kernel defines similarity in terms of cyclical phase recurrence modulated by temporal proximity. Observations contribute to the estimator based on alignment within a repeating cycle structure, with influence attenuated by temporal distance from the estimation point.
The estimator is formulated as a Nadaraya–Watson kernel regression under a locally periodic kernel, where weights are defined as:
k(i) = exp( -2 · sin²(πi / p) / L² ) · exp( -i² / 2L² )
Where:
p = period (cycle length)
L = lookback window (shared bandwidth parameter; effective smoothing scales with L²)
In this MacKay consistent formulation, the lookback window acts as a unified bandwidth parameter governing periodic phase selectivity and the Radial Basis Function (RBF) temporal decay envelope. The two components are coupled through L, producing a kernel that simultaneously emphasizes phase-aligned and temporally proximate observations.
As L increases, both the periodic and RBF components broaden, producing stronger smoothing across phase and time. As L decreases, phase selectivity and temporal locality both increase, making the estimator more sensitive to recent cycle-consistent observations.
This induces a similarity structure in which influence concentrates at phase-aligned intervals within a temporally bounded neighborhood. The resulting estimator defines a latent equilibrium governed by phase alignment and temporal proximity that can be interpreted as a locally stationary periodic extension of kernel regression on a circular phase manifold.
The key distinction from the pure periodic kernel is that phase-aligned observations at distant lags are progressively suppressed by the RBF decay term, allowing the estimator to adapt to structural drift while preserving cycle-aware weighting. During stable cyclical regimes the two estimators converge; during structural transitions the locally periodic variant adapts faster by downweighting older phase information.
CALIBRATION
As established in Gaussian Processes for Machine Learning (Rasmussen & Williams, 2006), the period should reflect the recurrence interval of the dominant cycle in the data, while the bandwidth parameter L controls how quickly similarity decays away from perfect phase alignment. For daily charts, common cycle anchors include the trading week (~5 bars), trading month (~21 bars), trading quarter (~63 bars), and trading year (~252 bars).
Length (Lookback / Bandwidth)
Controls structural depth of the estimator and acts as the unified bandwidth parameter for the periodic and RBF components; as L governs phase selectivity and temporal decay simultaneously, its effect is stronger than in the pure periodic variant. The default of 100 reflects the locally periodic kernel's temporal decay component; at longer lengths the RBF term weakens and behavior converges toward the pure periodic estimator.
- 50–100: high responsiveness, strong temporal locality, short-cycle sensitivity
- 150–250: balanced regime stability with moderate temporal decay
- 300+: broad structural smoothing, weak temporal decay, behavior converges toward pure periodic envelopes
Period (Cycle Length)
Defines the recurrence interval of the kernel and governs phase alignment and cyclical structure. Shorter periods increase phase resolution and cycle sensitivity, while longer periods emphasize broader structural recurrence. The period should reflect the dominant cycle present in the data, aligned with the anchor scales defined above.
Start At Bar
Offsets the kernel window backward from the most recent bars and excludes newer observations from the estimator. This ensures all calculations are based strictly on closed historical data and preserves non-repainting behavior.
MARKET USAGE
Stock, Forex, Crypto, Commodities, and Indices.
Performance is dependent on the presence of stable cyclical structure; in regimes lacking periodic coherence, the estimator converges toward a local smoother with reduced phase discrimination. Indicator

Indicator

Iterative Periodic EnvelopeThe Iterative Periodic Envelope is a phase-conditioned kernel estimator with endogenous dispersion modeling, implemented as a Nadaraya–Watson estimator under a canonical periodic kernel.
The periodic kernel defines similarity through cyclical phase alignment rather than temporal proximity or multi-scale distance decay. Observations contribute to the estimator based on their position within a repeating cycle structure, emphasizing structural recurrence over linear time dependence.
The indicator computes a latent equilibrium using a kernel-weighted mean and a dispersion measure using kernel-weighted variance under the same weighting structure. The resulting envelope reflects cycle-consistent deviation, rather than a conventional volatility band. All values are computed exclusively on closed historical bars using a bounded lookback window, ensuring non-repainting behavior.
This indicator belongs to a broader class of iterative kernel-based envelopes that includes Gaussian and Rational Quadratic variants. All share a common Nadaraya–Watson estimation framework, differentiated by their kernel.
TRADING USES
The Iterative Periodic Envelope is best interpreted as a cycle-aware structural estimator rather than a volatility-based band.
Equilibrium Tracking
The latent equilibrium represents the phase-conditioned central tendency of price under periodic similarity weighting. Oscillations around this level reflect movement within a repeating structural cycle rather than directional drift.
Cycle Regime Structure
The envelope emphasizes repeating structural behavior through phase recurrence weighting. Changes in symmetry, amplitude, or persistence of oscillation around the latent equilibrium may indicate transitions between cyclical regimes.
Mean Reversion Within Cycles
When a stable periodic structure is present, deviations from the latent equilibrium may revert toward phase-consistent levels. This supports mean-reversion behavior that is conditioned on cycle structure rather than purely statistical dispersion.
Structural Extremes
Extreme deviations relative to the envelope correspond to phase-inconsistent states where cyclical structure becomes stretched or destabilized. These conditions often precede transitions such as cycle inversion, expansion, or compression.
State Estimation
The system defines a latent equilibrium as the inferred central cyclical state, with dispersion derived from kernel-weighted variance under identical periodic similarity constraints. This produces a structurally consistent representation of market state.
PERIODIC ENVELOPE CONSTRUCTION
The envelope is constructed using kernel-weighted variance under the same periodic similarity measure used to estimate the latent equilibrium. The latent equilibrium defines the central state estimate and kernel-weighted variance defines dispersion under identical weighting, producing an endogenously determined envelope. The band width is fixed at ±1 kernel standard deviation with no multiplier, ensuring dispersion remains an intrinsic property of the periodic similarity structure rather than an externally imposed scaling parameter.
THEORY
The periodic kernel defines similarity in terms of cyclical phase recurrence rather than linear temporal distance. Observations contribute to the estimator based on alignment within a repeating cycle structure.
The estimator is formulated as a Nadaraya–Watson kernel regression under a canonical periodic kernel, where weights are defined as:
k(i) = exp( -2 · sin²(πi / p) / L² )
Where:
p = period (cycle length)
L = lookback window (bandwidth parameter; effective smoothing scales with L²)
In this MacKay consistent formulation, the lookback window acts as a bandwidth control parameter, governing phase selectivity and structural smoothing. As L increases, the kernel becomes broader, producing stronger smoothing and reduced phase sensitivity. As L decreases, phase selectivity increases and the estimator becomes more locally sensitive to cyclical alignment.
This induces a cyclical similarity structure in which influence concentrates at recurring phase intervals. The resulting estimator defines a latent equilibrium governed by phase alignment rather than temporal proximity. This formulation can be interpreted as a periodic extension of kernel regression on a circular phase manifold.
CALIBRATION
Length (Lookback / Bandwidth)
Controls structural depth of the estimator and acts as the primary kernel bandwidth parameter.
- 50–100: high responsiveness, short-cycle sensitivity
- 150–250: balanced regime stability
- 300+: strong structural smoothing, reduced sensitivity to phase noise
Period (Cycle Length)
Defines the recurrence interval of the kernel and governs phase alignment and cyclical structure. Commonly aligns with dominant market rhythms such as intraday or macro-cycle structure.
- Lower values: faster cycle sensitivity
- Higher values: slower, broader structural cycles
Start At Bar
Offsets the kernel window backward from the most recent bars and excludes newer observations from the estimator. This ensures all calculations are based strictly on closed historical data and preserves non-repainting behavior.
MARKET USAGE
Stock, Forex, Crypto, Commodities, and Indices.
Performance is dependent on the presence of stable cyclical structure; in regimes lacking periodic coherence, the estimator converges toward a smoother, low-information state. Indicator

Meridian Lens PRO🟦 Meridian Lens PRO is a multi-kernel trend indicator built on the KernelLens Nadaraya–Watson regression library (a_jabbaroff/KernelLens/1). Three independently configurable kernel lines — Fast, Medium, and Slow — cover the full reactivity spectrum from scalping to position trading, each accepting any of the eight kernel families and three filter modes exposed by the library. The visual layer applies volume-intensity-adaptive coloring, gradient-filled trailing bands, 3-layer neon glow signal arrows, and a theme-aware dashboard — all driven by a single theme selection from ten optical-brand palettes.
🟦 HOW IT WORKS
Meridian Lens PRO calls the KernelLens library's unified dispatcher (`kl.estimate`) three times per bar — once for each kernel line:
```
Fast = kl.estimate(type, src, bw=8, α, period, phase, filter)
Medium = kl.estimate(type, src, bw=16, α, period, phase, filter)
Slow = kl.estimate(type, src, bw=32, α, period, phase, filter)
```
Each line independently selects its kernel family (Rational Quadratic, Gaussian, Periodic, Locally Periodic, Epanechnikov, Tricube, Triangular, Cosine), its filter mode (No Filter / Smooth / Zero Lag), its bandwidth, shape α, period, phase, and line width. The library handles all weighted-sum computation, loop-depth selection, NA-safe iteration, and input validation internally.
The Medium line is the primary trend reference — it drives the trailing bands, the main signal arrows, the dashboard trend cell, and the direction variable that colors every visual component. The Fast line provides early-warning reactivity for short-term entry timing. The Slow line anchors the macro trend for crossover logic and confluence scoring.
🟦 KERNEL LIBRARY INTEGRATION
Meridian Lens imports the published KernelLens library and uses the following exports:
| Library Export | Used For |
|---|---|
| `kl.estimate()` | Unified dispatcher — routes to the correct kernel based on user's dropdown selection |
| `kl.trendState()` | Returns +1 / −1 / 0 for each kernel's slope — drives dashboard arrows and signal triggers |
| `kl.crossSignal()` | Detects Fast × Slow crossovers — drives the Cross row in the dashboard and crossover alerts |
The indicator does not reimplement any kernel math — all regression computation is delegated to the library, ensuring that every bug fix or optimization in the library automatically propagates to this indicator.
🟦 THREE KERNEL LINES
**Fast Kernel** — The most reactive line. Default bandwidth 8, No Filter. Designed for scalping and short-term entry timing. Flips direction frequently on noisy charts — its signal markers are OFF by default to avoid visual clutter.
**Medium Kernel** — The primary trend reference. Default bandwidth 16, Smooth filter. Drives the trailing bands, the main 3-layer glow signal arrows, the dashboard Trend cell, and the direction variable that colors every visual component. This is the indicator's core signal.
**Slow Kernel** — The macro trend anchor. Default bandwidth 32, Smooth filter. Provides structural support for crossover logic (Fast × Slow) and triple-line confluence scoring. Its signal markers are ON by default because Slow flips are rare and meaningful.
Each kernel group exposes: Show toggle, Kernel Type dropdown (8 families), Bandwidth, Shape α (RQ only), Period (Periodic / Locally Periodic only), Phase (non-repainting offset), Filter (None / Smooth / Zero Lag), and Line Width.
🟦 NON-REPAINTING BEHAVIOR
Meridian Lens inherits non-repainting behavior directly from the KernelLens library's `_phase` parameter. Each kernel line has its own Phase input (default: 2), which shifts the kernel center into the past by that many bars.
- Phase = 0 — live estimate, flickers on the current bar (real-time only; history is immutable)
- Phase = 1 — 1-bar lag, non-repainting once the bar is confirmed
- Phase = 2 — recommended balance between freshness and stability (default)
- Phase = 3+ — extra stability for swing and position trading
Historical repainting never occurs at any phase value. The library contains no `request.security` calls, no lookahead, and no array rotation that could leak future data. Every historical bar's plotted value is final once confirmed.
🟦 SIGNAL SYSTEM
The indicator produces three tiers of trend-flip signals, each visually distinct:
**Medium Signals (Primary)** — 3-layer neon glow arrows rendered when the Medium kernel's direction flips. The outer halo is large and 80% transparent, the middle layer is normal-sized and 50% transparent, and the core arrow is small and fully opaque — creating a luminous halo effect on dark charts. Controlled by the "Glow Effect" toggle.
**Slow Signals** — Minimal tiny arrows (40% transparent) that fire when the Slow kernel flips direction. ON by default — these mark rare, meaningful macro trend changes.
**Fast Signals** — Minimal tiny arrows (40% transparent) that fire when the Fast kernel flips direction. OFF by default — enable for early-warning entry timing on lower timeframes.
🟦 VISUAL PIPELINE
**Volume-Intensity Adaptive Color** — The Medium line's transparency responds to the current volume reading. High volume = bright line (volume-confirmed trend), low volume = dim line (low-conviction drift). Uses a 33-bar HMA-smoothed normalized volume metric. Disable for a fixed 50% transparency.
**Trailing Bands** — Gradient-filled bands on the bullish/bearish side of the Medium line. Band width is driven by the rolling 100-bar average candle body size multiplied by a configurable distance factor (default: 2.0×). Bull bands fill below the Medium line during uptrends, bear bands fill above during downtrends.
**Theme System** — Ten cohesive palettes drive every visual component:
| Theme | Bull | Bear |
|---|---|---|
| Prism | Forest green | Crimson red |
| Focus | Cyan steel | Deep orange |
| Solar | Warm amber | Indigo red |
| Frost | Sky blue | Soft lavender |
| Laser | Neon lime | Hot crimson |
| Aurora | Bright gold | Scarlet |
| Plasma | Electric aqua | Magenta |
| Bloom | Mint green | Hot pink |
| Eclipse | Deep navy | Dark crimson |
| Carbon | Near-black | Silver grey |
🟦 PRO DASHBOARD
A 2-column, 11-row theme-aware status panel that updates only on the last bar (zero historical overhead). Supports Dark and Light display modes with configurable position and text size.
| Row | Label | Content |
|---|---|---|
| Header | MERIDIAN LENS | DARK / LIGHT |
| Theme | Theme | Active palette name |
| Kernel | Kernel | Medium kernel type |
| Divider | KERNELS | — |
| Fast | Fast | ▲/▼ + price value (bull/bear colored) |
| Medium | Medium | ▲/▼ + price value (bull/bear colored) |
| Slow | Slow | ▲/▼ + price value (bull/bear colored) |
| Divider | SIGNALS | — |
| Trend | Trend | ▲ BULL / ▼ BEAR |
| Cross | Cross | ↑ UP / ↓ DOWN / — |
| Strength | Strength | ▰▰▰ TRIPLE / ▰▰▱ STRONG / ▰▱▱ WEAK / ▱▱▱ NEUTRAL |
**Confluence Strength** — Counts how many of the three kernels (Fast, Medium, Slow) have their trend aligned with the Medium's direction. Score 3 = TRIPLE BULL/BEAR, 2 = STRONG, 1 = WEAK, 0 = NEUTRAL.
🟦 ALERT CONDITIONS
Six opt-in alert conditions, each gated by its own toggle:
| Alert | Fires When |
|---|---|
| Bull Crossover | Fast line crosses above Slow line |
| Bear Crossover | Fast line crosses below Slow line |
| Trend Up | Medium kernel trend flips to rising |
| Trend Down | Medium kernel trend flips to falling |
| Triple Bullish | Fast > Medium > Slow AND Medium rising |
| Triple Bearish | Fast < Medium < Slow AND Medium falling |
All alerts use `alertcondition()` for maximum compatibility with PulseWire's alert system including webhooks.
🟦 RECOMMENDED PRESETS
| Style | Fast bw | Med bw | Slow bw | Phase | Med Filter | Chart |
|---|---|---|---|---|---|---|
| Scalper | 4–8 | 8–16 | 16–32 | 1 | No Filter | 1m–5m |
| Day Trader | 8–12 | 14–24 | 24–48 | 2 | Smooth | 15m–1h |
| Swing | 16–24 | 24–40 | 48–80 | 2 | Smooth | 4h–1D |
| Position | 24–48 | 40–80 | 80–200 | 3 | Smooth | 1D–1W |
🟦 COMPATIBILITY
- Pine Script v6
- All exchanges, all asset classes (crypto, forex, equities, commodities)
- All timeframes (1 minute through Monthly)
- No exchange-specific logic — fully deterministic
🟦 TECHNICAL NOTES
- **Library dependency** — `import a_jabbaroff/KernelLens/1` — all kernel regression math is delegated to the library
- **Plot budget** — 5 plots + 2 fills + 10 plotshapes = well under Pine's 64-plot limit
- **Table** — Single `var table` created once on `barstate.islast`, zero historical overhead
- **No persistent drawing objects** — no `box.new`, `label.new`, `line.new` — no garbage collection needed
- **Non-repainting** — inherits from the library's `_phase` parameter; no `request.security`, no lookahead
- **Volume-intensity** — uses HMA-smoothed normalized volume (33-bar window) for adaptive transparency
🟦 DISCLAIMER
Meridian Lens PRO is a technical analysis overlay indicator built on the KernelLens Nadaraya–Watson regression library. It is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor. Responsibility for any trading decisions rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of Meridian Lens or the underlying KernelLens library.
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

KernelLens🟦 KernelLens is a professional kernel regression library for Pine Script v6, providing eight mathematically rigorous Nadaraya–Watson estimators, a three-mode filter layer, a unified string dispatcher, and a suite of trading utilities — all built from the ground up on correct non-parametric statistics. Unlike existing Pine smoothing libraries — which inherit a decade-old loop-bound bug that silently reduces every kernel window to a handful of bars, regardless of the bandwidth parameter — KernelLens is built with auditable math, NA-safe iteration, input validation at every entry point, and academic references cited inline next to the formulas they describe.
The library integrates eight independent kernel families — Rational Quadratic, Gaussian, Periodic, Locally Periodic, Epanechnikov, Tricube, Triangular, and Cosine — behind a consistent API, with every raw estimator wrapped in a filter layer (None / Smooth / Zero Lag), a unified dispatcher for dropdown-driven kernel selection, and five utility exports covering slope detection, trend state, crossover signaling, residual confidence bands, and Silverman's rule-of-thumb bandwidth recommendation. Every public function validates its inputs, raises descriptive runtime errors on misuse, and returns `na` only when there is genuinely no data — never as a silent fallback.
🟦 MATHEMATICAL FOUNDATION
**The Nadaraya–Watson Estimator**
Given a source series `y_t` and a symmetric kernel `K` with scale parameter `ℓ` (the "bandwidth"), the Nadaraya–Watson estimator of the regression function `m(x) = E ` evaluated at the current bar is:
```
Σᵢ K(dᵢ / ℓ) · y_{t−i}
ŷ(t) = ───────────────────────
Σᵢ K(dᵢ / ℓ)
```
where `dᵢ` is the bar-distance from the kernel center and the sum runs over a finite window determined by the effective support of `K`.
The estimator is a locally weighted average: bars close to the kernel center contribute heavily, distant bars contribute proportionally less, and bars outside the support contribute nothing. It is asymptotically unbiased up to `O(ℓ²)` for twice-differentiable `m`, with variance of order `(n·ℓ)⁻¹` — the classical bias–variance trade-off that defines all non-parametric smoothers.
**Why Kernel Regression Beats Rolling Means**
A simple moving average gives every bar in the window the same weight. Kernel regression gives each bar a weight that decays smoothly with distance, producing:
- **Smoother output** — no step artifacts when bars enter / leave the window
- **Better bias control** — the peak of the kernel sits exactly on the point being estimated
- **Kernel-specific behavior** — compact-support kernels eliminate tail contamination entirely; Rational Quadratic's `α` parameter exposes multi-scale mixing; Periodic kernels resonate with known cycle lengths
The math has been the academic standard for non-parametric regression since Nadaraya (1964) and Watson (1964). KernelLens brings it to Pine Script v6 in its correct, bug-free form.
🟦 THE EIGHT KERNELS
All eight kernels implement the Nadaraya–Watson weighting scheme. They differ in support (compact versus infinite), smoothness (how many times differentiable), and how weight decays with distance.
| # | Kernel | Formula | Support | Smoothness | Character |
|---|---|---|---|---|---|
| 1 | **Rational Quadratic** | `(1 + d² / (2·α·ℓ²))^(−α)` | ℝ | C∞ | Multi-scale mixer — `α` controls stretch versus wiggle |
| 2 | **Gaussian (RBF)** | `exp(−d² / (2·ℓ²))` | ℝ | C∞ | The canonical smoother — smoothest possible with L² optimality |
| 3 | **Periodic** | `exp(−2·sin²(π·d/p) / ℓ²)` | ℝ | C∞ | Resonates with repetition distance `p` — ideal for cycles |
| 4 | **Locally Periodic** | Periodic · Gaussian | ℝ | C∞ | Seasonal patterns that slowly drift with trend |
| 5 | **Epanechnikov** | `(3/4)(1 − u²) · 𝟙{|u|≤1}` | | C⁰ | Asymptotically MSE-optimal (Watson 1964) — no tail contamination |
| 6 | **Tricube** | `(70/81)(1 − \|u\|³)³ · 𝟙{|u|≤1}` | | C² | The LOWESS standard — near-Gaussian with compact support |
| 7 | **Triangular** | `(1 − \|u\|) · 𝟙{|u|≤1}` | | C⁰ | Simplest non-uniform kernel — fastest to compute |
| 8 | **Cosine** | `(π/4)·cos(π·u/2) · 𝟙{|u|≤1}` | | C¹ | Raised-cosine taper — smoother boundary than Epanechnikov |
where `u = d/ℓ` and `𝟙` is the indicator function.
**Infinite-Support vs Compact-Support — Why Both Matter**
| | Infinite Support (RQ, Gauss, Periodic, LocPeriodic) | Compact Support (Epa, Tricube, Triangular, Cosine) |
|---|---|---|
| **Tail weight** | Never exactly zero | Exactly zero beyond ±ℓ |
| **Loop depth** | `3·ℓ` (3-σ cutoff, ≈99.7% mass) | Exactly `ℓ` |
| **Bar contamination** | Distant bars still pull the estimate a tiny amount | Distant bars cannot affect the estimate at all |
| **Best for** | Smooth trends, Gaussian-process intuition | Robust regression, outlier resistance |
KernelLens picks the correct loop depth automatically based on kernel family: `_depthInfinite` for Gaussian-family kernels, `_depthCompact` for bounded kernels, `_depthPeriodic` for Periodic (which must span enough cycles to reach stable weights).
**Why Eight, Not Four**
Most Pine kernel libraries ship only the four kernels from MacKay's Gaussian process tutorial. KernelLens adds the four compact-support classical kernels because:
- **Epanechnikov** minimises asymptotic mean squared error among all non-negative kernels of bounded support (Watson 1964) — it is the MSE-optimal baseline against which all other kernels are measured
- **Tricube** is the kernel used by LOWESS (Cleveland 1979), the de-facto standard for robust locally weighted scatterplot smoothing
- **Triangular** is the cheapest non-uniform compact kernel — useful when loop-budget matters on intraday charts with huge dataset size
- **Cosine** is C¹-continuous at the support boundary, unlike Epanechnikov's C⁰ discontinuity, producing visibly smoother transitions at kernel edges
Adding them makes the library an academically complete toolkit, not just a Pine port of one tutorial.
🟦 FILTER LAYER — NONE / SMOOTH / ZERO LAG
Every kernel export accepts a `_filter` parameter with three valid values. The filter layer is implemented identically across all eight kernels, so switching kernel families does not change filter behavior.
**"No Filter" — Single-Pass Raw Estimate**
```
ŷ = K(y)
```
One Nadaraya–Watson pass over the source. Cheapest mode, most reactive, fully represents the underlying kernel. Use this when you want the kernel's raw behavior with no additional smoothing or lag correction.
**"Smooth" — Double-Pass Estimate**
```
ŷ = K(K(y))
```
The kernel is applied once to the source, then applied again to its own output using the same bandwidth and the same parameters. The result is a more strongly smoothed curve at the cost of one extra loop pass per bar.
This is mathematically equivalent to convolving the kernel with itself — the effective kernel is wider and flatter, pulling longer-range context into each estimate without requiring the user to double the bandwidth.
**"Zero Lag" — Ehlers De-Lagged Estimate**
```
ŷ = 2·K(y) − K(K(y))
```
The ZLEMA identity from Ehlers (*Rocket Science for Traders*, 2000): subtract the smoothing lag from the raw estimate, effectively shifting the output back in time to match the source more closely.
The intuition: `K(y)` lags `y` by some amount; `K(K(y))` lags `K(y)` by the same amount; so `K(y) − K(K(y))` is an estimate of the lag itself, and adding it back to `K(y)` cancels out. The result tracks the source more tightly than either pass alone, at the cost of slightly noisier turning points.
**Lazy Evaluation — No Wasted Cycles**
In `"No Filter"` mode, the second pass is skipped entirely — it never runs. The filter branch uses an `if` block (not a ternary), so Pine's short-circuit semantics prevent the unused computation. A single kernel call costs one pass; `"Smooth"` or `"Zero Lag"` costs two. You only pay for what you use.
🟦 KERNEL CENTER OFFSET — THE `_phase` PARAMETER
Every KernelLens kernel takes a `_phase` parameter that shifts the kernel center into the past by `_phase` bars. It is the library's non-repainting knob.
**_phase = 0 — Live Estimate**
The kernel is centered on the current bar. The most recent price has maximum weight, and the estimate is as fresh as possible. Suitable for live signal generation, but the most recent bar can re-evaluate as it develops within its interval — standard Pine real-time behavior.
**_phase > 0 — Non-Repainting Historical Estimate**
The kernel center is moved `_phase` bars into the past. The estimate becomes the smoothed value *at that historical bar*, not the current bar. Once the bar at `bar_index − _phase` is fully confirmed (`barstate.isconfirmed`), its estimate cannot change again.
This is the standard trick for publishing kernel indicators that do not repaint: you get a stable, historically accurate curve at the cost of shifting the entire output `_phase` bars to the right on the chart. A `_phase = 25` call gives a curve that lags live price by 25 bars but is guaranteed stable for every past bar.
**Why It Belongs in the Library, Not the Caller**
Pushing `_phase` into the kernel's own loop is not the same as evaluating the kernel at a shifted source (`K(src )`). Shifting the source just uses a stale input with a current-bar-centered kernel, which still produces a fresh estimate of a stale series. KernelLens's `_phase` genuinely moves the kernel center, producing a historical-bar estimate that computes over the correct surrounding window.
🟦 NON-REPAINTING BEHAVIOR
Repainting is the single most-asked question about any Pine indicator, and the single most common source of silent failure when a retail trader moves from backtest to live. A strategy that looks flawless on historical bars and then bleeds money the moment it is deployed is almost always suffering from some form of repainting. KernelLens is engineered from first principles to eliminate every class of repainting by construction — not by patching symptoms, but by removing the dependencies that cause repainting in the first place.
**The Two Forms of Repainting**
| Form | Symptom | Typical Cause |
|---|---|---|
| **Historical repainting** | A bar that was closed days or weeks ago silently changes its plotted value when the chart is refreshed or scrolled | `request.security()` with `lookahead = barmerge.lookahead_on`, un-gated higher-timeframe data, or incorrect array rotation that reads into future bars |
| **Real-time repainting** | The plotted value on the live (current developing) bar flickers tick-by-tick as new price ticks arrive, then freezes at a final value when the bar closes | The indicator reads `close ` (or any current-bar value) inside a weighted sum — the current-bar weight changes every tick |
KernelLens avoids the first kind **entirely and unconditionally**: the library contains no `request.security` calls, no higher-timeframe lookups, no `lookahead_on` usage, and no array rotation that could leak future bars into the window. Every historical bar plotted by any KernelLens kernel is computed exclusively from bars that existed at the time that bar was closed. The plotted history is immutable.
Real-time repainting is controlled explicitly by the `_phase` parameter — it is the user's choice whether to accept tick-by-tick flicker on the live bar in exchange for zero lag (`_phase = 0`) or to eliminate the flicker entirely at the cost of a small fixed lag (`_phase ≥ 1`).
**Why Kernel Regression Normally Repaints (And How KernelLens Stops It)**
A traditional Nadaraya–Watson call centered on the current bar evaluates:
```
ŷ(t) = Σᵢ K(dᵢ/ℓ) · y_{t−i} for i = 0 … depth
```
On the live bar, the term `y_{t−0} = close ` is the current real-time price — which changes on every tick. Every tick moves the weighted sum, every tick moves the estimate, and the trader watching the chart sees the kernel plot flicker as the bar develops. The historical bars (where `close ` for that past bar is now fixed) are stable, but the live plot is unstable.
KernelLens's `_phase` parameter shifts the loop so the kernel runs over `i = _phase … _phase + depth`. With `_phase = 2`:
```
ŷ(t) = Σᵢ K((i−2)/ℓ) · y_{t−i} for i = 2 … 2 + depth
```
The sum no longer touches `close ` or `close ` — every bar it reads is already confirmed and cannot change. The live-bar kernel output is therefore identical from the first tick of the bar to the last tick of the bar, and identical again when the bar finally closes. There is no flicker and nothing to repaint.
**The Lag / Stability Trade-Off**
| `_phase` | Lag on Live Bar | Live-Bar Flicker | Historical Repainting | Best For |
|---|---|---|---|---|
| **0** | 0 bars | Yes (real-time only; history is stable) | None | Scalping, academic research, calibration |
| **1** | 1 bar | None | None | Fast day-trading; minimum acceptable lag for a live trading desk |
| **2** | 2 bars | None | None | Default for most users — the sweet spot between freshness and stability |
| **3** | 3 bars | None | None | Swing trading — extra margin against false flickers from erratic ticks |
| **5+** | 5+ bars | None | None | Position trading, long-term chart analysis, published signal marks |
Even at `_phase = 0`, **historical repainting never occurs** — only the live bar flickers during its own development. Once a bar closes, its plotted value is final; scrolling away and back, refreshing the chart, or re-opening PulseWire will never change that historical plot. The flicker is exclusively a live-bar tick-by-tick phenomenon.
**KernelLens as a Non-Repainting Primitive**
KernelLens exposes real-time flicker as an explicit, user-controlled trade-off rather than a hidden behavior. The caller picks any point on the spectrum from "fully live" (`_phase = 0`, maximum reactivity with tick-by-tick flicker) to "fully confirmed" (`_phase ≥ 1`, one or more bars of lag in exchange for a curve that never redraws) with a single integer parameter. Historical repainting — the dangerous form that silently rewrites past plots — is eliminated unconditionally regardless of `_phase`.
**How to Verify Non-Repainting Yourself**
Do not trust the word "non-repainting" from any library — always verify. KernelLens can be verified in about thirty seconds:
1. Load a chart with KernelLens on it using `_phase = 2` (or any value > 0).
2. Take a screenshot at any specific historical bar.
3. Scroll far to the left, refresh the chart, or reload the indicator.
4. Return to the same bar. The plotted value at that bar must be pixel-identical to the screenshot — because the computation on that bar used only the bars before it, which have not changed.
5. Repeat with `_phase = 0`. The historical bars must still be pixel-identical — only the live bar's plot can differ between observations, and only because the live bar's `close` is now a different number than it was when you took the screenshot.
For a stricter test, use PulseWire's **Bar Replay** mode. Enable Bar Replay, step forward one bar at a time, and watch the kernel plot on each newly-closed bar. With `_phase ≥ 1`, the value plotted on each newly-closed bar will exactly match what the indicator shows after you exit replay mode and view the same bar normally. This is the gold-standard test — Bar Replay reproduces live-bar tick arrival in a controlled way.
**Common Misconceptions**
> *"Any Pine indicator that uses `close` repaints."*
False. Using `close` on a confirmed bar does not repaint — the confirmed bar's close is locked. What can repaint is using `close` on the live bar, and only within that live bar's interval. KernelLens with `_phase > 0` never reads the live-bar close at all.
> *"`lookahead = barmerge.lookahead_on` is always wrong."*
Context-dependent. `lookahead_on` is used correctly in some multi-timeframe indicators to request a higher-TF value that is already settled on the lower TF. KernelLens does not use `request.security` at all, so this question does not apply — but for libraries that do, `lookahead_on` is only problematic when it leaks values from bars that were not yet closed at the lower-TF time of evaluation.
> *"Non-repainting means zero lag."*
False. Zero lag and non-repainting are orthogonal properties. KernelLens `_phase = 0` is zero lag with real-time flicker; `_phase = 2` is two-bar lag with no flicker. You can have any combination of the two, and the right choice depends on the trading style.
> *"The `FILTER_ZEROLAG` mode makes the indicator non-repainting."*
False. `FILTER_ZEROLAG` is an Ehlers-style de-lagging filter applied to the kernel output; it reduces the perceived lag of the estimate, but it does not affect whether the live bar flickers. Non-repainting is controlled exclusively by `_phase`. Choose `_phase` for repainting behavior, and `_filter` for smoothness / lag shape — they are independent knobs.
**When to Accept Real-Time Flicker (`_phase = 0`)**
Despite everything above, there are legitimate reasons to deliberately use `_phase = 0`:
- **Academic research and backtesting** — you want the kernel mathematics in its classical form, centered on the point being estimated, with no phase adjustment
- **Scalping on very short timeframes** — a 2-bar lag on a 1-minute chart is a 2-minute delay, which can matter when you are exiting within a 4-minute window
- **Visual calibration** — when you are choosing a bandwidth by eye, the live-bar flicker actually helps: you see how sensitive the curve is to each incoming tick, which is diagnostic information
- **Indicators that read the kernel output only on `barstate.isconfirmed`** — if your signal logic is gated by `if barstate.isconfirmed`, then live-bar flicker is invisible to your signal (it sees only the frozen close-of-bar value), and you can safely use `_phase = 0` with no practical consequence
For every other case — and especially for any live alert or automated trading system — use `_phase ≥ 1`. Two bars of lag on a clean, stable curve is almost always worth more than zero lag on a curve that redraws itself several times per bar.
🟦 UNIFIED DISPATCHER — `estimate()`
For indicators where the user picks a kernel from a dropdown, writing eight separate ternary branches is tedious and error-prone. KernelLens ships with a unified dispatcher that routes to the correct kernel based on a string argument:
```pine
import a_jabbaroff/KernelLens/1 as kl
line = kl.estimate(
kernelType = kl.KERNEL_GAUSS,
src = close,
bandwidth = 32,
shapeAlpha = 1.0,
period = 1,
phase = 2,
filter = kl.FILTER_SMOOTH)
```
The dispatcher forwards to the matching typed export, so there is no performance penalty versus calling the kernel directly — it is a compile-time routing pass. Unknown kernel names raise a descriptive `runtime.error` naming every valid alternative, so typos fail loudly instead of silently returning `na`.
**Public Constants**
KernelLens exposes its string constants so callers never type the magic values by hand:
| Constant | Value |
|---|---|
| `FILTER_NONE` | `"No Filter"` |
| `FILTER_SMOOTH` | `"Smooth"` |
| `FILTER_ZEROLAG` | `"Zero Lag"` |
| `KERNEL_RQ` | `"Rational Quadratic"` |
| `KERNEL_GAUSS` | `"Gaussian"` |
| `KERNEL_PERIODIC` | `"Periodic"` |
| `KERNEL_LOCPER` | `"Locally Periodic"` |
| `KERNEL_EPA` | `"Epanechnikov"` |
| `KERNEL_TRICUBE` | `"Tricube"` |
| `KERNEL_TRIANG` | `"Triangular"` |
| `KERNEL_COSINE` | `"Cosine"` |
Using the constants in your caller code means the Pine compiler — not a runtime string compare — catches typos at edit time.
🟦 UTILITY LAYER — FIVE PROFESSIONAL HELPERS
KernelLens ships with five utility exports that complement the core estimators. They are the functions you almost always write immediately after getting a smoothed line, factored out so you don't rewrite them in every indicator.
**`slope(estimate, step)` — Discrete First Derivative**
Returns `(y_t − y_{t−step}) / step`, the normalized rate of change over `step` bars. Use it to detect whether a kernel output is trending up, flat, or down — the foundation for any trend-following signal built on top of KernelLens.
```pine
rising = kl.slope(line, 3) > 0.0
```
**`trendState(estimate, step)` — Ternary Trend Indicator**
Returns `+1` if the estimate is rising, `−1` if falling, `0` if exactly flat over the window. A single-call replacement for hand-rolled `line > line ? 1 : line < line ? -1 : 0` ladders.
**`crossSignal(fast, slow)` — Bi-directional Crossover**
Returns `+1` on the bar where `fast` crosses above `slow` (bullish), `−1` on a bearish cross, and `0` otherwise. Built on `ta.crossover` / `ta.crossunder`, so the signal is non-repainting once the bar is confirmed.
**`confidenceBand(src, estimate, window)` — Residual Standard Deviation**
Computes the rolling standard deviation of `(src − estimate)` over a user-defined window. Use the return value as the half-width of a confidence band around the estimate:
```pine
est = kl.gaussian(close, 32, 2, kl.FILTER_SMOOTH)
sigma = kl.confidenceBand(close, est, 50)
upper = est + 1.96 * sigma
lower = est - 1.96 * sigma
```
This is a computationally cheap proxy for the full kernel-weighted local variance — ideal when you need visual bands without paying for a second weighted pass.
**`silvermanBandwidth(src, window)` — Optimal ℓ Suggestion**
Returns the Silverman rule-of-thumb bandwidth:
```
h ≈ 1.06 · σ · n^(−1/5)
```
where `σ` is the rolling standard deviation of the source and `n` is the window size. This is the classical starting point for Gaussian-family bandwidths in academic texts (Silverman 1986). Because Pine requires `simple int` for kernel bandwidth, the returned value is intended for diagnostic display — plot it, read it off the chart, then hard-code the rounded integer into the kernel call.
🟦 INPUT VALIDATION — FAIL LOUDLY, FAIL EARLY
Every public function in KernelLens validates its inputs through a set of internal `_assert*` helpers. Invalid arguments never produce silent `na` fallbacks or buried zero-divisions — they raise `runtime.error` with a descriptive message identifying the function, the parameter, and the expected range.
| Helper | Checks | Raises On |
|---|---|---|
| `_assertFilter` | Filter string is `FILTER_NONE`, `FILTER_SMOOTH`, or `FILTER_ZEROLAG` | Typos like `"No FIlter"` (capital I) — a bug that exists in at least one published kernel indicator |
| `_assertBandwidth` | Bandwidth is a strictly positive integer | Negative or zero bandwidth, which would cause division by zero or infinite loops |
| `_assertPeriod` | Period is a strictly positive integer | Zero period, which would cause `sin(π·d/0)` in Periodic kernels |
| `_assertAlpha` | Rational Quadratic shape parameter is strictly positive | Zero or negative `α`, which would invert the RQ formula |
Error messages are prefixed `KernelLens:` (or `KernelLens.:`) so they are easy to spot in the PulseWire runtime log. Every message names the parameter that failed, the value that was passed, and the set of valid alternatives — so a misconfigured chart tells you exactly what to fix.
🟦 LOOP DEPTH — THE BUG FIX THAT MOTIVATED KERNELLENS
The two most popular Pine kernel libraries on PulseWire share the same fatal bug: both compute their loop depth as
```pine
_size = array.size(array.from(_src))
```
where `array.from(_src)` creates a **one-element array containing the current value of `_src`**, so `_size` is always `1`. The loop then runs `for i = 0 to 1 + startAtBar`, effectively using only `startAtBar + 2` bars — completely ignoring the user's bandwidth. Every published kernel indicator built on those libraries inherits this silent miscalculation.
KernelLens replaces the broken helper with three explicit depth selectors:
| Helper | Depth | Used By |
|---|---|---|
| `_depthInfinite(bw)` | `max(bw · 3, 4)` | Gaussian, Rational Quadratic, Locally Periodic |
| `_depthCompact(bw)` | `max(bw, 4)` | Epanechnikov, Tricube, Triangular, Cosine |
| `_depthPeriodic(bw, p)` | `max(bw · 3, p · 10, 4)` | Periodic |
For Gaussian-family kernels, the `3·ℓ` cutoff captures approximately 99.7% of the kernel mass (the three-sigma rule). For compact-support kernels, the depth equals the bandwidth exactly — the loop terminates at the kernel's natural zero point. For Periodic kernels, the depth is the larger of the scale-based and cycle-based minima, so the loop always spans enough periods to produce a stable weighted average.
The loop counter `i` runs over bar offsets starting at `_phase`, every bar lookup is NA-checked before being incorporated into the sum, and the final `num / den` division is guarded against zero denominators. On a fresh chart, the kernel gracefully returns `na` for bars where the window extends past available history, rather than producing poisoned sums from implicit NA arithmetic.
🟦 API REFERENCE
**Core Kernel Estimators — Eight Exports**
| Export | Signature |
|---|---|
| `rationalQuadratic` | `(src, bandwidth, shapeAlpha, phase, filter) → float` |
| `gaussian` | `(src, bandwidth, phase, filter) → float` |
| `periodic` | `(src, bandwidth, period, phase, filter) → float` |
| `locallyPeriodic` | `(src, bandwidth, period, phase, filter) → float` |
| `epanechnikov` | `(src, bandwidth, phase, filter) → float` |
| `tricube` | `(src, bandwidth, phase, filter) → float` |
| `triangular` | `(src, bandwidth, phase, filter) → float` |
| `cosineKernel` | `(src, bandwidth, phase, filter) → float` |
**Unified Dispatcher**
| Export | Signature |
|---|---|
| `estimate` | `(kernelType, src, bandwidth, shapeAlpha, period, phase, filter) → float` |
**Utility Layer — Five Exports**
| Export | Signature |
|---|---|
| `slope` | `(estimate, step) → float` |
| `trendState` | `(estimate, step) → int` |
| `crossSignal` | `(fast, slow) → int` |
| `confidenceBand` | `(src, estimate, window) → float` |
| `silvermanBandwidth` | `(src, window) → float` |
**Parameter Types**
| Name | Pine Type | Description |
|---|---|---|
| `src` | `series float` | Source series (close, hl2, ohlc4, or any other price-derived series) |
| `bandwidth` | `simple int` | Kernel scale `ℓ`, must be `> 0` |
| `shapeAlpha` | `simple float` | Rational Quadratic shape parameter, must be `> 0` |
| `period` | `simple int` | Periodic repetition distance, must be `> 0` |
| `phase` | `simple int` | Kernel center offset in bars, must be `≥ 0` |
| `filter` | `simple string` | One of `FILTER_NONE`, `FILTER_SMOOTH`, `FILTER_ZEROLAG` |
| `kernelType` | `simple string` | One of the eight `KERNEL_*` constants |
| `step` | `simple int` | Finite-difference step for `slope` / `trendState`, must be `≥ 1` |
| `window` | `simple int` | Rolling window for `confidenceBand` / `silvermanBandwidth`, must be `≥ 2` |
🟦 USAGE EXAMPLES
**Minimal — One Gaussian Curve**
```pine
//@version=6
indicator("KernelLens — Gaussian Demo", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
line = kl.gaussian(close, 32, 2, kl.FILTER_SMOOTH)
plot(line, "Gaussian", color = color.orange, linewidth = 2)
```
**Fast / Slow Crossover System**
```pine
//@version=6
indicator("KernelLens — RQ Crossover", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
fast = kl.rationalQuadratic(close, 8, 1.0, 2, kl.FILTER_NONE)
slow = kl.rationalQuadratic(close, 32, 1.0, 2, kl.FILTER_SMOOTH)
cross = kl.crossSignal(fast, slow)
plot(fast, "Fast", color = color.aqua, linewidth = 2)
plot(slow, "Slow", color = color.orange, linewidth = 2)
plotshape(cross == 1, "Bull", location = location.belowbar,
color = color.lime, style = shape.triangleup, size = size.tiny)
plotshape(cross == -1, "Bear", location = location.abovebar,
color = color.red, style = shape.triangledown, size = size.tiny)
```
**Confidence Band Envelope**
```pine
//@version=6
indicator("KernelLens — Confidence Band", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
est = kl.tricube(close, 48, 2, kl.FILTER_SMOOTH)
sigma = kl.confidenceBand(close, est, 50)
k = 1.96
upper = est + k * sigma
lower = est - k * sigma
plot(est, "Estimate", color = color.orange, linewidth = 2)
p1 = plot(upper, "+1.96σ", color = color.new(color.aqua, 70))
p2 = plot(lower, "−1.96σ", color = color.new(color.aqua, 70))
fill(p1, p2, color = color.new(color.aqua, 92))
```
**Dropdown-Driven Kernel Selection**
```pine
//@version=6
indicator("KernelLens — Dropdown", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
kernelType = input.string(kl.KERNEL_GAUSS, "Kernel",
options = )
bandwidth = input.int(32, "Bandwidth", minval = 2)
alphaRQ = input.float(1.0,"RQ Alpha", minval = 0.01, step = 0.25)
period = input.int(20, "Period", minval = 1)
phase = input.int(2, "Phase", minval = 0)
filter = input.string(kl.FILTER_SMOOTH, "Filter",
options = )
line = kl.estimate(kernelType, close, bandwidth, alphaRQ, period, phase, filter)
plot(line, "KernelLens", color = color.orange, linewidth = 2)
```
🟦 TIMEFRAME PRESETS — BANDWIDTH BY STYLE
Kernel bandwidth is the single most important parameter. It controls the trade-off between reactivity (small `ℓ`, tight fit, noisier) and stability (large `ℓ`, smooth curve, slower to react). The presets below are tested starting points — adjust by ±25 % to taste.
---
**SCALPER — 1m / 3m / 5m**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 8 |
| Phase | 1 |
| Filter | `FILTER_NONE` |
| Best Kernel | Rational Quadratic or Gaussian |
| RQ shapeAlpha | 1.0 |
**Why:** Short bandwidth means the kernel reacts within a handful of bars. `FILTER_NONE` removes the double-pass lag, so the estimate tracks price as tightly as possible. Phase 1 keeps the estimate nearly live while still avoiding the current-bar tick noise.
---
**DAY TRADER — 15m / 30m / 1H**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 16 |
| Phase | 2 |
| Filter | `FILTER_SMOOTH` |
| Best Kernel | Gaussian or Tricube |
| RQ shapeAlpha | 1.0 |
**Why:** Balanced reactivity — the 16-bar Gaussian is the default Silverman range for intraday price data, and `FILTER_SMOOTH` removes most of the bar-to-bar chop without significantly increasing lag. Tricube provides near-identical behaviour with strict compact support and is preferred on noisy assets where outlier bars should not influence the curve.
---
**SWING TRADER — 4H / 1D**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 32 |
| Phase | 3 |
| Filter | `FILTER_SMOOTH` |
| Best Kernel | Rational Quadratic |
| RQ shapeAlpha | 2.0 |
**Why:** Swing trades need structural signals, not intraday noise. Rational Quadratic with `α = 2.0` mixes medium and long length scales, producing a curve that ignores transient spikes but catches genuine regime shifts. Phase 3 shifts the estimate three bars back so each swing decision is made against a fully confirmed kernel output.
---
**POSITION / LONG-TERM — 1D / 1W / 1M**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 64 |
| Phase | 5 |
| Filter | `FILTER_SMOOTH` or `FILTER_ZEROLAG` |
| Best Kernel | Gaussian or Locally Periodic |
| Period (if LP) | 52 (weekly cycle) |
**Why:** Position traders care about the macro trajectory. A Gaussian with ℓ = 64 produces a curve that only turns on genuine multi-month inflections. Locally Periodic with `period = 52` is the ideal choice when a clear seasonal cycle is present — it uses both the long-range Gaussian envelope and the 52-bar periodicity to highlight cycle turns that align with trend.
---
**RESEARCH — Academic / Backtest**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | Compute via `silvermanBandwidth(src, 200)` |
| Phase | 0 |
| Filter | `FILTER_NONE` |
| Best Kernel | Epanechnikov |
**Why:** Epanechnikov is the MSE-optimal kernel; `FILTER_NONE` keeps the estimator in its classical single-pass form; `phase = 0` centers the kernel on the bar being evaluated. This is the configuration that matches the statistical literature exactly — use it when publishing research, running Monte-Carlo studies, or calibrating against reference implementations.
🟦 BANDWIDTH SELECTION
Bandwidth `ℓ` is the single most consequential choice in kernel regression. Too small and the estimate overfits local noise; too large and it flattens real structure. KernelLens exposes two helpers to support both manual and semi-automated bandwidth selection.
**Manual — Start with ℓ ≈ √n**
A practical starting point for financial time series: set `ℓ ≈ √window_of_interest`. If you care about 100-bar structure, try `ℓ = 10`. If you care about 400-bar structure, try `ℓ = 20`. Adjust by ±25 % based on how noisy the result looks.
**Silverman's Rule of Thumb**
The closed-form optimal bandwidth for Gaussian-family kernels under Gaussian source assumptions:
```
h ≈ 1.06 · σ · n^(−1/5)
```
Call `silvermanBandwidth(src, window)` to compute this value live. Because Pine requires `simple int` bandwidth at compile time, the returned value is for diagnostic use — plot it, read the stable value off the chart, then hard-code the rounded integer into your kernel calls.
**Leave-One-Out Cross-Validation (Manual)**
For academic rigor, compute the leave-one-out mean squared error for a range of bandwidths and pick the minimum. KernelLens does not automate this (it would require `series int` bandwidth, which Pine does not support inside kernel loops), but the formula is straightforward:
```
LOOCV(ℓ) = (1/n) · Σᵢ (yᵢ − ŷᵢ⁻ⁱ(ℓ))²
```
where `ŷᵢ⁻ⁱ` is the kernel estimate at bar `i` computed without including bar `i` in the sum. Evaluate offline, pick the minimum, hard-code the result.
🟦 FILTER SELECTION — WHEN TO USE EACH
| Filter | Best For | Avoid When |
|---|---|---|
| `FILTER_NONE` | Live signal generation, research / calibration, compact-support kernels on noisy data | Choppy markets where you need extra smoothing |
| `FILTER_SMOOTH` | Swing and position trades, confidence band midlines, most day-trading setups | Scalping — the double pass adds measurable lag |
| `FILTER_ZEROLAG` | Regime detection, crossover systems that need the curve to track price tightly | Low-volume assets — Zero Lag amplifies high-frequency noise |
The three filters use the same underlying kernel with the same bandwidth, so switching between them does not require re-tuning. Default to `FILTER_SMOOTH` when in doubt — it is the best-behaved option across the widest range of assets and timeframes.
🟦 COMPATIBILITY
KernelLens targets Pine Script v6 and runs on every PulseWire chart — no exchange, asset class, or timeframe restriction.
- **Crypto** — Spot, futures, perpetual contracts
- **Forex** — All majors, minors, and exotics
- **Equities** — Stocks, ETFs, indices
- **Commodities** — Metals, energy, agriculture
- **Timeframes** — 1 minute through Monthly
The library is deterministic — given the same source and parameters, every bar of every symbol produces the same estimate. No calibration is needed across assets; the bandwidth parameter alone controls smoothness, and the kernel formulas are scale-free in the source dimension. Silverman's bandwidth helper automatically adapts to each asset's volatility.
🟦 TECHNICAL NOTES
- **Pine Script v6** — uses the modern type system, strict type checking, and the `switch` expression in the unified dispatcher
- **Non-repainting** — kernel outputs for any confirmed bar depend only on that bar's history; there is no look-ahead, no `request.security` with lookahead, and no dependency on the unconfirmed current bar unless `_phase = 0` is deliberately chosen
- **NA-safe iteration** — every bar lookup inside a kernel loop is guarded by `if not na(y)`, so chart history gaps and warm-up bars cannot poison the weighted sum
- **Division-by-zero protection** — every kernel's final division checks `den > 0.0` and returns `na` if the denominator collapses (which can only happen on truly empty windows)
- **Input validation** — every public function asserts its preconditions up front via `_assertFilter`, `_assertBandwidth`, `_assertPeriod`, `_assertAlpha`, and raises `runtime.error` with a descriptive message on misuse — no silent `na` fallbacks
- **Lazy filter evaluation** — the `"No Filter"` path never executes the second kernel pass; the `if`-branch check short-circuits, so single-pass mode is as cheap as a raw kernel call
- **Correct loop bounds** — `_depthInfinite`, `_depthCompact`, and `_depthPeriodic` compute the correct window size per kernel family, fixing the silent `_size = 1` bug that plagues every other published Pine kernel library
- **No persistent state** — the library is purely functional: no `var`, no arrays, no history buffers that grow over time; every export is a pure expression of `(inputs) → output`, so Pine's `max_*_count` limits cannot be exceeded and the library cannot leak memory
- **O(bandwidth) per bar per kernel call** — the loop depth is bounded by the constants in Section 0; there is no hidden quadratic behavior and the cost scales linearly with the user-chosen bandwidth
- **Unicode-safe comments** — the source uses academic notation (`σ`, `ℓ`, `α`, `ŷ`, `ℝ`) where it improves readability; all strings are plain ASCII for runtime compatibility
🟦 ACADEMIC REFERENCES
Every kernel and every formula in KernelLens is cited inline in the source. The combined bibliography:
- **Nadaraya, E. A. (1964).** On estimating regression. *Theory of Probability & Its Applications*, 9(1), 141–142.
- **Watson, G. S. (1964).** Smooth regression analysis. *Sankhyā: The Indian Journal of Statistics, Series A*, 26(4), 359–372.
- **Cleveland, W. S. (1979).** Robust locally weighted regression and smoothing scatterplots. *Journal of the American Statistical Association*, 74(368), 829–836. *(Tricube kernel, LOWESS.)*
- **Silverman, B. W. (1986).** *Density Estimation for Statistics and Data Analysis*. Chapman & Hall, London. *(Bandwidth rule of thumb.)*
- **Wand, M. P. & Jones, M. C. (1995).** *Kernel Smoothing*. Chapman & Hall. *(Unified treatment of all eight kernels.)*
- **MacKay, D. J. C. (1998).** Introduction to Gaussian Processes. *NIPS Tutorial*. *(Periodic and Rational Quadratic kernels.)*
- **Ehlers, J. F. (2000).** *Rocket Science for Traders*. John Wiley & Sons. *(Zero-lag smoothing trick.)*
- **Rasmussen, C. E. & Williams, C. K. I. (2006).** *Gaussian Processes for Machine Learning*. MIT Press. *(Locally Periodic and Rational Quadratic kernels.)*
🟦 VERSIONING & LICENSE
- **Version** — 1.0.0
- **Pine Script** — v6
- **License** — Mozilla Public License 2.0
- **Status** — Production-ready
KernelLens follows semantic versioning. Minor versions add new exports without breaking existing ones; patch versions fix bugs; major versions may change function signatures and will be announced in the changelog.
🟦 DISCLAIMER
KernelLens is a mathematical library for non-parametric regression on financial time series using the Nadaraya–Watson method. The library is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor in the kernel itself. Responsibility for any trading decisions made using this library rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of KernelLens or any indicator built on top of it. Library

Iterative Rational Quadratic ChannelThe Iterative Rational Quadratic Channel is a kernel-based smoothing and state estimation framework that applies a Rational Quadratic kernel regression to price data, combined with a rolling standard deviation envelope to construct adaptive dynamic channel boundaries.
Unlike exponential kernel methods that prioritize recent data at the expense of historical context, the rational quadratic kernel introduces a heavy-tailed weighting structure that preserves multi-scale memory in price dynamics. This enables the channel to reflect not only short-term fluctuations, but also broader structural regime context.
The resulting channel is less reactive to micro-noise and more representative of persistent market structure, making it particularly effective for trend continuity analysis, regime modeling, and reducing sensitivity to false reversals.
Its primary utility is as a state estimation and regime-filtering tool for price behavior, rather than a pure high-frequency signal isolation tool.
TRADING USES
The Rational Quadratic Channel is best interpreted as a regime-aware structural filter rather than a purely reactive trading band.
Trend Continuity
The channel basis line (RQ smoothed price) provides a stable representation of underlying market direction. Sustained movement above or below the basis reflects trend persistence rather than short-lived fluctuations, making it useful for maintaining directional bias.
Regime Persistence
Due to the heavy-tailed memory of the rational quadratic kernel, historical price structure continues to influence current valuation. This produces smoother transitions between market phases and reduces sensitivity to short-term reversals, improving regime stability.
False Reversal Filtering
Compared to exponentially weighted kernels, the RQ channel reduces overreaction to transient volatility spikes. This helps filter out low-quality reversals driven by noise rather than structural change.
State Estimation
The channel functions as a continuous estimator of market state:
- The basis represents the inferred latent price state
- The envelope represents dynamic volatility dispersion around that state
This makes it well-suited for manual, semi-automated, and automated trading systems requiring a stable structural representation of price rather than raw responsiveness. Gradual shifts in the basis line and channel position can also serve as a framework for monitoring changes in trend direction and regime transitions over time.
Volatility & Risk Context
The rolling standard deviation envelope expands and contracts based on realized volatility, providing a contextual risk framework. Wider channels indicate increased uncertainty and dispersion, while tighter channels indicate compression and lower variance conditions.
THEORY
The rational quadratic kernel is a member of the scale-mixture family of Gaussian kernels and can be interpreted as a superposition of Gaussian processes operating at multiple length scales. This allows it to capture both local and global structure in time series data.
It is defined as:
k(i)=(1+i22αℓ2)−αk(i) = \left(1 + \frac{i^2}{2\alpha \ell^2}\right)^{-\alpha}k(i)=(1+2αℓ2i2)−α
Where:
---> α\alphaα controls tail heaviness (relativeWeight)
---> ℓ\ellℓ defines the characteristic scale (lookback)
Unlike Gaussian kernels, which enforce exponential decay and emphasize locality, the rational quadratic kernel follows a power-law decay. This allows older observations to retain influence over the estimator for longer periods, producing a smoothing effect that is inherently multi-scale and well-suited for modeling persistent structural behavior.
The rolling standard deviation complements this by measuring dispersion around the estimated state, forming a volatility-adaptive envelope. Rather than acting as a strict statistical confidence interval, it provides a dynamic representation of market expansion and contraction.
The iterative implementation processes data sequentially (bar-by-bar), ensuring computational efficiency and making the indicator suitable for real-time use without repainting.
CALIBRATION
Calibration determines the balance between responsiveness, structural memory, and regime stability.
Length (Lookback)
Lower (50–100): More responsive, increased sensitivity to short-term structure
Medium (150–250): Balanced for swing trading and intermediate regimes
Higher (300+): Strong regime persistence, reduced sensitivity to noise
Relative Weight (Tail Sensitivity)
Controls how quickly historical influence decays:
Lower values (≈ 0.5 – 1.0):
- Behavior approaches Gaussian
- More responsive to recent price action
- Faster detection of trend changes
- Slightly more sensitive to noise
Higher values (≈ 2.0+):
- Stronger heavy-tail behavior
- Increased influence of older price data
- Smoother output and stronger regime anchoring
- Improved false reversal filtering
Start At Bar (Lag / Structural Anchoring)
Controls how much recent price data is excluded from the kernel calculation:
Lower values (0–10):
- Uses most recent data
- Faster reaction to price changes
- More sensitive to short-term volatility
Moderate values (10–30):
- Balanced responsiveness and stability
- Reduces noise without excessive lag
- Suitable for most trading environments
Higher values (30+):
- Strong structural anchoring
- Significantly reduced sensitivity to recent fluctuations
- Enhanced regime persistence
- Slower response to turning points
This parameter effectively introduces a controlled lag, allowing users to tune the tradeoff between responsiveness and regime stability.
MARKET USAGE
Stock, Forex, Crypto, Commodities, and Indices. Indicator

Dynamic Support & Resistance V3Dynamic SRT V3 by Anonycryptous inspired by Ilja V.
Compared to the previous version, a completely new and accelerated concept.
Dynamic SRT V3 is a professional structural mapping suite that identifies high-density liquidity zones through a dual-engine calculation process. By merging a 6-Tiered Pivot Architecture with a Validated Diagonal Scoring Engine, it provides a surgical view of market boundaries, allowing traders to distinguish between minor price fluctuations and major institutional walls.
*How the Engine Operates
This indicator functions as a mathematical filter for price action, operating on two distinct layers:
-1. Tiered Institutional Anchors (Horizontal)
Instead of looking at a single fractal period, V3 tracks six different "memory depths" simultaneously (ranging from 5 to 200 bars).
The Concept: Markets move in cycles. Small cycles (Pivot 1-2) represent retail positioning, while large cycles (Pivot 5-6) represent institutional buy/sell walls.
State-Aware Logic: Each level uses an ATR-Volatility Buffer to determine its current state. If price is above the level, it acts as Support (Green); if below, it is Resistance (Red). If price is currently slicing through it, the level turns Grey (Neutral), signaling a "No-Trade Zone" or a consolidation phase.
-2. Slope-Intercept Validation Engine (Diagonal)
The dynamic trendlines are not just simple "peak-to-peak" connectors. They are calculated using a Linear Regression Scoring System.
*The Concept: A trendline's strength is defined by its "cleanliness."
-The Filter: Unlike standard tools, V3 uses a Price-Action Scan. It calculates the path of a potential trendline and automatically discards it if it cuts through the bodies of intermediate candles. This ensures that the wedges and channels you see are statistically valid structural boundaries.
-Strategic Application: LTF vs. HTF
*Performance & User Manual
-Optimized Execution: V3 utilizes Last-Bar Offloading. It scans 1000+ bars of history in milliseconds by executing the heavy diagonal math only on the most recent candle, ensuring zero chart lag.
-Price Tags: Dynamic labels are pinned professionally above the levels. Use these as your Take-Profit (TP) or Stop-Loss (SL) targets.
-Customization: Adjust the Touch Tolerance in the settings to make the trendlines more or less strict depending on the asset's "wickiness" (e.g., higher for BTC, lower for Forex).
*Lower Timeframes (1m – 15m): Scalping & Intraday
-LTF Focus: Prioritize Pivot Levels 1, 2, and 3. These are highly reactive and will map the micro-pullbacks of the current session.
-Early Signal: Look for price to reject a Dynamic Trendline while a micro-pivot (Level 1) is acting as support. This provides an aggressive "Early Entry" with a very tight risk-to-reward ratio.
-The Trap: Avoid trading when the LTF candles are consistently Grey, as this indicates the market is trapped inside a static pivot zone.
-Higher Timeframes (1H – Daily): Swing & Position Trading
*HTF Focus: Prioritize Pivot Levels 5 and 6. These represent the "Major Floors and Ceilings" of the weekly or monthly trend.
-The Macro Wall: If price hits a Level 6 Pivot (200-bar lookback), expect a significant reaction. Institutional orders are often clustered at these depths.
-Structural Confluence: The most powerful HTF setup is "The Confluence Cross." This occurs when a diagonal Resistance Trendline and a horizontal Level 5/6 Resistance meet at the same price point. This is the mathematical "End of Trend" zone where heavy reversals typically begin.
! Notice: This tool is for institutional-grade structural mapping and educational purposes only. It is not financial advice. Structural levels are areas of high probability, not guaranteed reversal points. Always trade with a stop-loss.
Indicator

Multi-Timeframe EMA SMA HMA LR Proximity & Alerts [HYPR-run]DESCRIPTION:
Nine moving averages from Weekly down to chart timeframe on one chart.
Weekly 10 SMA, Daily 50/100/200 EMA/SMA, 4hr 200 SMA, plus chart-TF
10 EMA, 200 SMA, Hull MA, and Linear Regression. See where price sits
relative to every meaningful institutional level without switching
timeframes.
The proximity filter is the key feature. Enable all nine MAs, set a
threshold, and only lines near current price appear. The Daily 200 SMA
at 20% away? Hidden. When price drops toward it, the line shows up
automatically. Your chart stays clean and the levels that matter are
always visible.
DISCOVERING EDGE
We have found that managing risk in mature assets with the 50d, 100d,
200d, and 10w is highly effective, simple and a methodology shared
amongst experienced investors and traders. This indicator interprets
that positioning across 16 configurations with a 7-tier color gradient,
so you see structural health at a glance. "Oh, it's bouncing on the
50dma right now, there may be a set-up in play..."
POSITIONAL CONTEXT vs STATIC MA OVERLAY
Static overlays show every MA with no interpretation of what the
positioning means. This indicator color-codes 16 above/below
configurations weighted by MA significance (200d and 10w are
heavyweights), surfaces bounce/reject events ranked by importance,
and shows % distance to each curve so you know exactly how much of a
move is needed for price to converge.
- Events fire independently of display toggles; a hidden 200d SMA
that price just bounced off still shows "Bouncing 200d" in the
dashboard.
- 7-tier positioning gradient weighted by MA significance (200d and
10w are heavyweights) shows structural health in one glance.
- Webhook alerts on configurable MA cross (9 options from 10w to
linear regression) with full bar filter.
FEATURES
- 9 moving averages from Weekly down to chart timeframe
- Proximity filter: hides irrelevant MAs far from price
- Bounce/reject detection at each MA level
- Two alert systems: XO/XU cross + bounce/reject on selected MA
- Bounce/reject alerts fire when price wicks into selected MA (support/resistance hold)
- Dashboard: row 1 positioning context (above/below each MA), row 2 live events (bouncing, rejecting, XO, XU)
- Dashboard dark/light theme toggle for any chart background
- Polyline rendering (smooth lines, no staircase artifacts)
- End-of-line labels with % distance from price
- Toggle each MA independently
HOW IT WORKS
Higher timeframe MAs are pulled via request.security and rendered as
polylines for smooth display on any chart timeframe. The proximity check
runs on every bar: if the distance between price and a given MA exceeds
the threshold %, the polyline is not drawn. When price approaches, the
line appears. Alerts fire independently of display toggles.
DASHBOARD
Two-row dynamic dashboard that updates every bar.
- Row 1 (positioning): which MAs price is above or below, grouped with
"&" separators. The Weekly 10 SMA is separated as the anchor by a
pipe. 7-tier color gradient based on how many of the four key MAs
(50d, 100d, 200d, 10w) price is above, with heavyweight distinction
(200d and 10w carry more weight than 50d/100d): bright green (all
four), green (3/4 with both heavyweights), dark green (3/4 missing a
heavyweight), yellow (2/4), dark red (1/4 with a heavyweight), red
(1/4 only lightweight), bright red (none)
- Row 2 (events): up to 3 simultaneous events, most significant MA first
(w10 → d200 → d100 → d50 → 4h200). Bouncing (support holding),
rejecting (resistance holding), XO (crossover), XU (crossunder). Color
intensity uses a 2D significance matrix: MA weight x event type.
Brightgreen for a w10 bounce; yellow for a d200 cross; darkgreen for
idle above d50. Dark gray when idle
- Runs independently of display toggles; events fire for all MAs even if
the line is hidden by the proximity filter
DEFAULT CONFIGURATION
Weekly 10 SMA (white), Daily 50 EMA (yellow), and Daily 200 SMA (purple)
are on by default. Proximity filter on at 5%. These three levels are the
most commonly watched institutional reference points.
POSITIONING TABLE (row 1, all 16 configurations)
BADGE COLOR (header, positioning x event combination)
ALERTS
Two alert systems. XO/XU fires when price crosses the selected MA with a
full bar filter (body >= 66.6% of range, rejects doji/wick-heavy bars).
Bounce/Reject fires when price wicks into the selected MA from the correct
side and closes confirming support (bounce) or resistance (reject). Both
fire JSON payloads; works with any webhook receiver.
CREDITS
No external libraries or third-party code used. Indicator

Adaptive Trend ChannelAdaptive Trend Channel is designed to find the most reliable short-term and long-term trend channels automatically, instead of forcing the user to work with one arbitrary lookback length. The script scans a broad range of candidate periods, builds a regression-based channel for each one, and then compares them through a multi-factor selection process. The goal is not just to find a channel that looks clean, but one that is statistically solid and structurally meaningful. To do that, the indicator favors channels with strong linearity, efficient trend behavior, sufficient directional strength, good price containment inside the bands, controlled width, and stable quality across nearby lengths. This helps avoid weak or accidental fits and gives priority to channels that are more robust in practice.
For best results, it is strongly recommended to use a logarithmic chart and to enable the option "Enable for logarithmic price scale" in the indicator settings. This is especially important on assets with large percentage moves over time, because the channel geometry then reflects percentage-based price movement more accurately.
Color is also important and very simple to read:
if a very robust channel is found, it is displayed in blue by default. This means the selected channel passed the eligibility filters and qualified as a strong structure. If no channel is robust enough, the script can still display the best available candidate, but it will appear in gray by default.
OVERVIEW
Adaptive Trend Channel helps identify the best short-term and long-term trend channels without manually testing many different lengths. Instead of relying on fixed settings, it adapts to the market structure by selecting the channels that best balance fit, strength, consistency, and usability.
The indicator can display:
- the best short-term channel
- the best long-term channel
- an optional midline
- an optional data table with channel diagnostics
HOW IT WORKS
For each tested lookback period, the script builds a regression-based trend channel and measures its quality.
Two selection modes are available:
1. Pearson r
This mode focuses mainly on linear fit quality.
2. Robust Composite
This mode uses a broader decision framework and combines several factors to favor channels that are not only well fitted, but also more reliable as usable trend structures.
In Robust Composite mode, the selection can include:
- Pearson correlation
- trend efficiency
- ADX trend strength
- price containment inside the channel
- channel width control
- local stability across neighboring tested lengths
A channel is considered eligible only if it passes the minimum filters defined by the user, such as:
- minimum absolute Pearson r
- minimum ADX
- minimum containment ratio
- maximum allowed channel width
If at least one eligible channel is found, the strongest one is selected and displayed in blue by default.
If none qualifies, the script still displays the best available fallback channel, but in gray by default.
WHY THIS APPROACH
A fixed-length channel can work well in one market condition and fail badly in another. This script addresses that problem by testing multiple candidate lengths and ranking them with a more complete selection logic.
The method is designed to reduce three common issues:
- choosing an arbitrary lookback period
- overvaluing channels that only look good visually
- accepting channels that fit price poorly or are too unstable
By combining fit quality, structure, strength, containment, and stability, the indicator aims to produce channels that are more trustworthy and easier to interpret.
HOW TO READ IT
- The short-term channel helps track the active market structure.
- The long-term channel helps frame the broader trend.
- Blue by default means a robust eligible channel was found.
- Gray by default means the displayed channel is the best available one, but it did not pass the eligibility filters.
- The position of price inside the channel helps show whether price is near the upper band, lower band, or midline.
FEATURES
- Automatic search for the best short-term and long-term channels
- Adaptive selection across multiple lookback lengths
- Robust eligibility filtering
- Blue default color for robust eligible channels
- Gray default color for fallback non-eligible channels
- Support for linear and logarithmic mode
- Optional midline display
- Optional table with channel metrics
- Two detection methods: Pearson r or Robust Composite
TABLE METRICS
Depending on your settings, the table can display:
- best length
- selection metric
- stability
- trend efficiency
- Pearson r
- ADX
- annualized channel return
- annualized channel price return
MAIN INPUTS
- Show Best Short-Term Channel
- Show Best Long-Term Channel
- Enable for logarithmic price scale
- Display Deviation Multiplier
- Best Channel Detection
- minimum eligibility filters for Pearson r, ADX, containment, and width
- optional table settings
NOTES
- For best interpretation, use logarithmic mode on a logarithmic chart.
- Blue by default means the channel passed the eligibility filters and was considered robust.
- Gray by default means the script is showing the best fallback channel, but it is not eligible.
- Annualized return metrics are intended for daily, weekly, and monthly timeframes.
Adaptive Trend Channel is built for traders who want a more objective, adaptive, and robust way to identify high-quality trend channels. Indicator

Indicator

[ A L P H A X ] Bollinger/Keltner Volatility Pressure SystemAlphaX Volatility Pressure System — Bollinger/Keltner Squeeze Detection, Linear Regression Forecast, Multi-Confluence Band Touch Signals, Volatility Regime Classification & Institutional Dashboard
AlphaX Volatility Pressure System (VPS) is a professional-grade volatility analysis and signal system built on the interaction between Bollinger Bands and Keltner Channels — the foundation of squeeze-based trading. It combines a proprietary multi-layer squeeze engine, linear regression band forecasting, a six-factor confluence scoring system, and a comprehensive real-time dashboard into a single cohesive overlay. Designed and default-tuned for XAUUSD (Gold) on the 1-minute timeframe, fully adaptable to any instrument or timeframe.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📸 Visual Overview
The indicator displays Bollinger Bands as a gradient cloud, Keltner Channel boundaries as dotted lines, squeeze status dots on the basis line, a projected forecast envelope extending into the future, confidence-scored entry signals at band touches, mean reversion exit markers, and a full diagnostic dashboard — all in a clean, non-cluttered layout with a consistent yellow-green / red / gray color theme.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔬 The Volatility Pressure Architecture — How It Works
At the core of AlphaX VPS is the principle that volatility is cyclical — periods of compression (low volatility) are followed by periods of expansion (high volatility), and vice versa. The system detects exactly where you are in this cycle and provides actionable intelligence at every stage.
The system operates through seven integrated layers:
Layer 1 — Bollinger Bands (Volatility Envelope)
A Simple Moving Average (SMA) basis line with standard deviation bands above and below
Default: 30-period SMA with 2.2x multiplier — tuned for gold's micro-noise on 1-minute charts
The bands expand during volatile moves and contract during consolidation
Price touching or piercing the outer bands represents statistical extremes — potential reversal zones
The space between upper and lower bands is rendered as a gradient cloud that shifts color based on price position relative to the basis — yellow-green when price is above basis (bullish pressure), red when below (bearish pressure)
Layer 2 — Keltner Channels (ATR Volatility Wrapper)
An Exponential Moving Average (EMA) center line with Average True Range (ATR) bands
Default: 30-period EMA with 1.8x ATR multiplier using 20-period ATR — calibrated for gold
Keltner Channels represent the "normal" volatility range based on true range, while Bollinger Bands represent statistical deviation — the relationship between them reveals compression and expansion states
Plotted as subtle dotted lines at the channel boundaries for clean visual reference without chart clutter
Layer 3 — Squeeze Engine
Squeeze ON — detected when Bollinger Bands contract inside the Keltner Channel (BB upper < KC upper AND BB lower > KC lower). This means volatility has compressed below normal levels — a spring is being loaded
Squeeze Release — the first bar where BB breaks back outside KC after a squeeze period. This is the explosive moment where the compressed energy releases into a directional move
Squeeze status is displayed as colored dots on the BB basis line: red dots during active squeeze, yellow-green dots on squeeze release, gray dots during normal conditions
Squeeze Momentum — a John Carter-style linear regression calculation determines the direction of the squeeze release: bullish momentum (price likely to break upward) or bearish momentum (price likely to break downward)
Squeeze release events generate flash markers on the chart: "⚡ SQ↑" for bullish releases, "⚡ SQ↓" for bearish releases
The dashboard tracks how many of the last 20 bars were in squeeze state — prolonged squeezes (12+ bars) tend to produce the most explosive releases
Layer 4 — Linear Regression Forecast
A forward-looking projection of the Bollinger Band envelope using linear regression slopes
The system calculates the current slope of both the BB basis and the BB deviation, then projects them forward by the configured number of bars (default: 20 bars = 20 minutes on 1-minute chart)
The projection is smoothed using a weighted blend from current values to forecasted values, preventing jarring visual jumps
Displayed as a projected envelope with upper, basis, and lower forecast lines, plus a filled forecast cloud
Forecast color reflects projected direction: yellow-green if the basis is projected to rise, red if projected to fall
Price labels at the forecast endpoints show the projected upper and lower band values — giving you concrete target levels
A minimum bandwidth floor prevents the forecast from collapsing to zero during extreme compression
Layer 5 — Trend EMA
A 100-period Exponential Moving Average provides macro trend context
Color-coded: yellow-green when price is above (bullish structure), red when below (bearish structure)
The EMA slope direction (rising vs. falling over 3 bars) is factored into the confluence scoring system
Acts as a structural filter — signals aligned with the EMA trend receive bonus confidence, signals against it receive penalties
Layer 6 — RSI Filter
A 14-period Relative Strength Index provides momentum confirmation
Oversold threshold at 30, overbought at 70 — stricter than typical settings to filter gold noise
RSI must be in a supportive zone for signals to fire: below 45 for bullish signals, above 55 for bearish signals
Deeply oversold or overbought RSI readings contribute up to 15 points to the confluence score
Layer 7 — Volatility Regime Classification
The system continuously classifies the current market state into one of five regimes:
SQUEEZE 🔴 — BB inside KC, volatility compressed, spring loading
RELEASE ⚡ — first bar after squeeze ends, explosive move initiating
EXPANSION 📈 — bandwidth increasing and price trending directionally
COMPRESSION — bandwidth decreasing, volatility contracting
RANGING — no clear volatility trend, sideways movement
The current regime is displayed prominently in the dashboard and influences signal generation — signals during active squeeze are blocked entirely
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Signal System — Band Touch Signals
AlphaX VPS generates two types of chart signals: Entry Signals at band extremes and Exit Markers at mean reversion.
Entry Signals ( ⬆ / ⬇ )
Entry signals appear when price touches or pierces a Bollinger Band while multiple confluence factors align to confirm a high-probability reversal setup.
Bullish Entry (⬆) — a yellow-green label below the bar indicating a potential long opportunity:
Price touches or pierces the lower Bollinger Band
Confluence score meets the minimum confidence threshold (default: 60%)
RSI is below 45 (supportive of oversold bounce)
Volume is above average (institutional participation confirmed)
A swing low structure is present near the band (not just a random wick)
Candle shows bullish rejection — either a bullish close or a long lower wick (>50% of candle range)
Market is NOT in active squeeze (signals blocked during compression)
Cooldown period has elapsed since last bullish signal (default: 15 bars)
Bearish Entry (⬇) — a red label above the bar indicating a potential short opportunity:
Price touches or pierces the upper Bollinger Band
Confluence score meets the minimum confidence threshold
RSI is above 55 (supportive of overbought reversal)
Volume is above average
A swing high structure is present near the band
Candle shows bearish rejection — either a bearish close or a long upper wick
Market is NOT in active squeeze
Cooldown period has elapsed since last bearish signal
Each signal label displays the tier rating and confidence percentage :
S-Tier (80%+) — exceptional setup, maximum confluence — highest probability
A-Tier (70–79%) — strong setup, most factors aligned
B-Tier (60–69%) — decent setup, adequate confluence for a trade with proper risk management
Signals below B-Tier are automatically filtered out and never displayed.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Exit Markers ( ✕ )
After an entry signal fires, the system tracks position direction and monitors for mean reversion to the BB basis line :
Long Exit ✕ — appears when price crosses back above the BB basis after a bullish entry, indicating the mean reversion target has been reached
Short Exit ✕ — appears when price crosses back below the BB basis after a bearish entry, indicating the mean reversion target has been reached
Exit markers serve as profit-taking signals — the statistical edge of a band touch trade is the reversion to the mean (basis line). Once price reaches the basis:
Take partial or full profit
Tighten stop loss to breakeven
Wait for the next band touch signal before re-entering
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🧠 Multi-Confluence Confidence Scoring System
Every entry signal is evaluated by a real-time scoring engine that produces a confidence percentage from 0% to 100%. This is not a simple threshold check — it is a weighted multi-factor assessment that rewards alignment and penalizes contradiction.
Scoring Factors — Bullish Signals:
Band Touch Quality (up to 20 points)
How deeply price pierced the lower Bollinger Band
Pierce depth >5% of band width = 20 points (strong penetration)
Any pierce = 15 points
Near-touch (within 0.1%) = 10 points
%B Position (up to 10 points)
Bollinger %B measures where price sits within the band range (0 = lower band, 1 = upper band)
%B below 0 (outside lower band) = 10 points
%B below 0.05 = 8 points
%B below 0.15 = 5 points
RSI Depth (up to 15 points)
RSI below 20 = 15 points (deeply oversold)
RSI below 25 = 12 points
RSI below 30 = 10 points
RSI below 40 = 3 points
EMA Trend Alignment (up to 10 points)
Price above 100 EMA AND EMA slope rising = 10 points (full alignment)
Price above 100 EMA only = 5 points
Squeeze Release Confluence (up to 10 points)
Squeeze just released with bullish momentum = 10 points (explosive setup)
Bullish squeeze momentum without active squeeze = 5 points
Candle Rejection Pattern (up to 10 points)
Long lower wick (>50% of range) + bullish close = 10 points (textbook rejection)
Long lower wick only = 7 points
Bullish close only = 3 points
Volume Confirmation (up to 10 points)
Above-average volume + bullish close = 10 points (institutional buying)
Above-average volume only = 5 points
MACD Momentum (up to 8 points)
MACD line above signal line OR histogram rising for 2+ bars = 8 points
200 SMA Structure (up to 7 points)
Price above 200 SMA = 7 points (macro trend support)
Penalty Deductions:
Price BELOW EMA trend = -15 points (counter-trend signal)
RSI above 55 = -12 points (momentum doesn't support reversal)
Active squeeze = -8 points (wait for release)
Expanding but directionless = -5 points
No volume spike when volume filter enabled = -5 points
Bearish candle rejection present = -10 points (wrong candle structure)
The same structure applies to bearish signals with inverted logic — upper band touch, overbought RSI, price below EMA, bearish rejection candles, etc.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🛡 Signal Quality Gates — Why This Indicator Produces Clean Signals
Beyond the confidence score, every signal must pass through six independent quality gates before it can appear on the chart. If any single gate fails, the signal is blocked entirely — regardless of the confidence score:
Gate 1 — Band Touch Gate
Price must actually reach or pierce the Bollinger Band (within 0.1%)
Signals near the middle of the bands are impossible — only statistical extremes qualify
Gate 2 — RSI Zone Gate
Bullish signals require RSI below 45
Bearish signals require RSI above 55
This prevents signals when momentum is neutral or contradictory
Gate 3 — Volume Gate
Volume must exceed the 20-period volume moving average multiplied by 1.2x
Low-volume band touches are often noise — this gate requires institutional participation
Can be toggled off for instruments with unreliable volume data
Gate 4 — Swing Structure Gate
A swing low must be present within the last 3 bars for bullish signals (price formed a local bottom)
A swing high must be present within the last 3 bars for bearish signals (price formed a local top)
This prevents signals on through-band breakdowns where price is accelerating through the band, not bouncing off it
Can be toggled off for faster signal generation
Gate 5 — Candle Confirmation Gate
Bullish signals require either a bullish candle close (close > open) or a bullish rejection wick (lower wick > 50% of total range)
Bearish signals require either a bearish candle close or a bearish rejection wick
This confirms that price is actually rejecting the band level, not just touching it on the way through
Gate 6 — Squeeze Block Gate
No signals fire during active squeeze (BB inside KC)
During squeeze, volatility is compressed and band touches are unreliable — the bands themselves are artificially narrow
Signals resume after squeeze releases
Gate 7 — Cooldown Gate
A minimum of 15 bars (15 minutes on 1-minute chart) must elapse between signals of the same direction
Prevents signal spam during choppy band-walking conditions
This seven-gate architecture is why AlphaX VPS produces significantly fewer but higher-quality signals compared to basic Bollinger Band indicators.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Identifying Choppy / Ranging Markets — When NOT to Trade
Knowing when to stay out is just as important as knowing when to enter. AlphaX VPS provides multiple visual cues for choppy, range-bound conditions:
How to identify choppy conditions:
BB Cloud is extremely narrow — when the Bollinger Bands contract tightly, the cloud between upper and lower bands becomes paper-thin. Narrow bands = low volatility = no clean directional moves.
Squeeze dots are RED for extended periods — prolonged red dots on the basis line mean BB is trapped inside KC. While this predicts an eventual explosive move, trading during the squeeze is a losing strategy. Wait for the yellow-green release dot.
Forecast cloud is flat and narrow — if the projected envelope shows no significant expansion or directional slope, the system expects continued compression. No expansion forecast = no trade.
Regime dashboard shows "COMPRESSION" or "RANGING" — the volatility regime classifier explicitly tells you the current state. These regimes have the lowest signal quality.
No signals appearing despite price touching bands — this means the quality gates are doing their job. If you see band touches but no labels, the confluence score is too low or a gate is blocking. Trust the filter.
EMA (100) is flat and price is oscillating around it — no trend, no edge.
Basis distance in dashboard shows very small percentage — price is hugging the basis line, meaning there is no stretched rubber band to snap back. Mean reversion trades need extension first.
What to do during choppy markets:
Do not force trades — wait for squeeze release (yellow-green dot + ⚡ marker)
Watch for the forecast cloud to start expanding and tilting directionally
Monitor the regime dashboard — wait for "RELEASE ⚡" or "EXPANSION 📈" to appear
Consider moving to a higher timeframe where structure may be clearer
Use the squeeze bar counter in the dashboard — once squeeze bars reach 12+/20, the release is likely imminent
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 How to Trade with AlphaX VPS — Step by Step
Step 1 — Assess Market Regime
Check the dashboard REGIME field: Is it EXPANSION, COMPRESSION, SQUEEZE, or RANGING?
Check the Bollinger Band cloud width: Is it expanded or collapsed?
Check squeeze dots: Red = stay out. Gray = normal. Yellow-green = just released.
If the regime is SQUEEZE or COMPRESSION → do not trade. Wait for RELEASE or EXPANSION.
Step 2 — Monitor the Forecast
Look at the projected envelope ahead of current price
Is the forecast expanding or narrowing? What direction is the basis slope?
A widening forecast with a clear directional slope tells you where the bands are heading
The forecast upper and lower price labels give you concrete projected targets
Step 3 — Wait for a Band Touch Signal
Do not chase price in the middle of the bands — wait for price to reach an extreme
A ⬆ or ⬇ label will appear only when all seven quality gates pass and the confidence score meets your threshold
The label shows the tier (S/A/B) and exact confidence percentage — use this to size your position (higher confidence = larger size)
Step 4 — Enter the Trade
Enter on the signal bar's close (signals are confirmed on bar close, non-repainting)
Place your stop loss beyond the Bollinger Band that was touched (for bullish: below the lower band, for bearish: above the upper band)
Your profit target is the BB basis line (mean reversion target) — the system will mark this with a ✕ when reached
Step 5 — Manage and Exit
Watch for the ✕ exit marker — this appears when price crosses back to the BB basis
Take partial or full profit at the basis line
If price continues past the basis toward the opposite band, you can trail your stop using the basis line as your new stop level
If a new signal appears in the same direction before the exit triggers, it can be used to add to the position
Step 6 — Squeeze Release Trades (Advanced)
When you see the "⚡ SQ↑" or "⚡ SQ↓" release marker, this is a momentum breakout setup
The squeeze release direction (bull/bear) is determined by the squeeze momentum calculation
Enter in the direction of the release
These moves tend to be explosive — use wider stops and larger targets than mean reversion trades
The forecast projection will often show an expanding envelope in the direction of the release — use the forecast band endpoints as extended targets
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 Real-Time Dashboard — Complete Market Intelligence
The dashboard provides a comprehensive snapshot of every metric the system monitors, organized into five sections:
─── VOLATILITY ───
REGIME — Current volatility state (Squeeze / Release / Expansion / Compression / Ranging) with color-coded background
BANDWIDTH — Current BB width as percentage of basis, colored relative to its 50-period average (narrow = green/opportunity, wide = red/extended)
BB %B — Where price sits within the bands (0% = lower band, 100% = upper band). Extreme readings are color-highlighted
SQUEEZE BARS — How many of the last 20 bars were in squeeze (higher = more compressed = bigger expected release)
KC RELATION — Whether BB is inside KC (squeeze), above KC (expansion), or near KC (transition)
─── MOMENTUM ───
RSI — Current RSI value with zone label (OB/OS/HIGH/LOW/MID) and appropriate coloring
EMA — Trend direction based on price vs. 100 EMA and EMA slope (▲ BULL / ▲ RISING / ▼ BEAR / ▼ FALLING)
SQ MOMENTUM — Squeeze momentum direction and strength (▲▲ STRONG UP / ▲ RISING / ▼▼ STRONG DOWN / ▼ FALLING / — FLAT)
MACD — MACD momentum status (▲ BULLISH / ▼ BEARISH / — NEUTRAL)
VOLUME — Whether current volume exceeds the moving average threshold (▲ ABOVE AVG / — NORMAL)
─── CONFIDENCE ───
BULL CONF — Current bullish confluence score with tier rating (S-TIER / A-TIER / B-TIER / C-TIER / LOW)
BEAR CONF — Current bearish confluence score with tier rating
These update in real-time so you can see confluence building before a signal fires
─── FORECAST ───
BASIS SLOPE — Direction the BB basis is heading (▲ RISING / ▼ FALLING / — FLAT)
BAND FORECAST — Whether bands are projected to widen (▲ WIDENING) or narrow (▼ NARROWING) or remain stable
─── STRUCTURE ───
SMA 200 — Price position relative to 200 SMA (▲ ABOVE / ▼ BELOW) — macro trend context
─── TRADE STATE ───
POSITION — Current tracked position direction (▲ LONG / ▼ SHORT / — FLAT) with color-coded background
BASIS DISTANCE — How far price is from the BB basis as a percentage — measures extension and mean reversion potential
Dashboard position (Top Left / Top Right / Bottom Left / Bottom Right) and text size (Tiny / Small / Normal) are configurable.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡ Key Features
📊 Bollinger Bands with gradient trend cloud — instant visual of price position within the volatility envelope
🔷 Keltner Channels with ATR-based boundaries — the volatility reference for squeeze detection
🔴 BB/KC Squeeze Engine — detects compression, tracks squeeze duration, classifies release direction
⚡ Squeeze Release Flash Markers — "⚡ SQ↑" and "⚡ SQ↓" labels mark the explosive moment
🔭 Linear Regression Forecast — projects the band envelope forward with directional slope and price targets
🎯 Multi-confluence band touch signals — six-factor scoring with seven independent quality gates
📐 Volume filter — requires above-average volume for signal confirmation (toggleable)
🏗 Swing structure filter — requires local swing formation near bands (toggleable)
🕯 Candle rejection analysis — wick ratio and close direction confirmation
📈 MACD momentum integration — histogram trend confirmation within the scoring system
📏 200 SMA macro structure — long-term trend context for scoring
📐 100 EMA trend filter — intermediate trend direction and slope analysis
✕ Mean reversion exit markers — automatic profit target detection at the BB basis
🏷 Tiered signal labels — S / A / B tier with confidence percentage for position sizing decisions
📋 22-row real-time dashboard — complete market intelligence across volatility, momentum, confidence, forecast, structure, and trade state
🎨 Cohesive dual-tone color theme — yellow-green for bullish, red for bearish, orange for neutral, gray for inactive
🔔 11 alert conditions — S-Tier, A-Tier, and any-tier for both bull and bear, plus squeeze releases and exits
⚙ Fully configurable — all periods, multipliers, thresholds, colors, gates, and dashboard settings adjustable from the settings panel
🚫 No candle coloring — clean chart by default, your candles remain untouched
📏 Non-repainting — all signals confirmed on bar close
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙ Settings Reference
📊 Bollinger Bands
BB Length — SMA period for the basis line (default: 30)
BB Multiplier — standard deviation multiplier for band width (default: 2.2)
Source — price source for calculations (default: close)
Show BB Cloud — toggle the gradient band fill
🔷 Keltner Channel
KC Length — EMA period for the center line (default: 30)
KC ATR Multiplier — ATR multiplier for channel width (default: 1.8)
KC ATR Length — ATR calculation period (default: 20)
Show KC Lines — toggle Keltner boundary display
⚡ Squeeze
Show Squeeze Dots — toggle colored dots on the basis line
Alert on Squeeze Release — enable squeeze release alerts
🔭 Forecast
Show Regression Forecast — toggle the projected envelope
Forecast Bars — how many bars forward to project (default: 20)
🎯 Signals
Show Band Touch Signals — master toggle for entry labels
Min Confidence % — minimum confluence score required (default: 60%)
Signal Cooldown — minimum bars between same-direction signals (default: 15)
Show Mean Reversion Exits — toggle ✕ exit markers
📈 RSI Filter
RSI Length — calculation period (default: 14)
RSI Oversold — threshold for oversold scoring bonus (default: 30)
RSI Overbought — threshold for overbought scoring bonus (default: 70)
📐 EMA Trend Filter
Show Trend EMA — toggle the 100 EMA display
EMA Length — EMA period (default: 100)
📊 Volume Filter
Use Volume Confirmation — enable/disable volume gate (default: ON)
Volume Threshold Multiplier — how far above average volume must be (default: 1.2x)
Volume MA Length — period for volume moving average (default: 20)
🏗 Structure Filter
Use Swing Structure Filter — enable/disable swing gate (default: ON)
Swing Lookback — bars to check for swing formation (default: 3)
🎨 Colors
Bull Primary — yellow-green family for all bullish elements
Bear Primary — red family for all bearish elements
Basis / Neutral — orange for basis and neutral elements
Squeeze ON / OFF / Neutral — dot colors for squeeze states
Forecast Bull / Bear — projection envelope colors
Dashboard BG / Text / Neutral — dashboard styling
📋 Dashboard
Show Dashboard — master toggle
Position — corner placement (default: Top Right)
Text Size — Tiny / Small / Normal (default: Small)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔔 Alert Conditions
S-Tier Bull Band Touch — fires when a bullish signal with 80%+ confidence appears
A-Tier Bull Band Touch — fires when a bullish signal with 70–79% confidence appears
Any Bull Band Touch — fires on any bullish signal meeting minimum threshold
S-Tier Bear Band Touch — fires when a bearish signal with 80%+ confidence appears
A-Tier Bear Band Touch — fires when a bearish signal with 70–79% confidence appears
Any Bear Band Touch — fires on any bearish signal meeting minimum threshold
Any Band Touch Signal — fires on any entry signal regardless of direction
Squeeze Release — Bullish — fires on bullish squeeze release
Squeeze Release — Bearish — fires on bearish squeeze release
Any Squeeze Release — fires on any squeeze release
Long Exit — Mean Reversion — fires when a long position reaches the BB basis
Short Exit — Mean Reversion — fires when a short position reaches the BB basis
All alert messages include {{ticker}}, {{interval}}, and {{close}} placeholders for webhook integration.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 Default Settings — Optimized For
The default configuration is specifically tuned for XAUUSD (Gold) on the 1-minute timeframe :
BB Length 30 and Multiplier 2.2 — smooths gold's micro-noise and widens bands to reduce false touches
KC Length 30 and ATR Multiplier 1.8 — matched to BB for proper squeeze detection on gold
Confidence threshold at 30% — aggressively filters low-quality signals while keeping genuine setups
Cooldown at 4 bars (4 minutes) — prevents signal spam during volatile gold transitions
Volume filter enabled with 1.2x threshold — confirms institutional participation
Swing structure filter enabled — requires actual price structure, not random wicks
100 EMA provides ~1.5 hours of trend context on 1-minute
20-bar forecast projects 20 minutes ahead — practical for scalping decisions
For other instruments or timeframes, adjust:
Higher timeframes (5m, 15m, 1H) — reduce BB Length to 20–25, reduce confidence to 45–55%, increase forecast bars to 30–50
Forex majors (EURUSD, GBPUSD) — reduce BB Multiplier to 2.0, reduce KC ATR Multiplier to 1.5, keep confidence at 50–60%
Indices (NAS100, US30, SPX500) — use defaults or increase BB Length to 35–40 for broader structure
Crypto (BTCUSD, ETHUSD) — increase BB Multiplier to 2.5, increase cooldown to 20–25 bars due to higher volatility
Less noise / fewer signals — increase Min Confidence to 70%+, increase Cooldown, enable all gates
More signals / aggressive scalping — decrease Min Confidence to 40–50%, reduce Cooldown to 8–10, disable Swing Structure gate
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
👥 Who This Is For
🥇 Gold (XAUUSD) scalpers and intraday traders — built and default-tuned specifically for gold's volatility, noise profile, and session structure
📊 Bollinger Band traders — if you trade band touches and mean reversion, this system adds institutional-grade filtering to your existing strategy
⚡ Squeeze traders — the BB/KC squeeze engine with momentum direction and release markers provides a complete squeeze trading system
📉 Forex and index traders — applicable to all major instruments with minor setting adjustments
🧠 Systematic traders — the confidence scoring system provides a quantitative framework for position sizing and trade selection
📈 Traders who value clean charts — no indicator clutter, no candle painting, no overlapping signals. One cohesive system with consistent color coding
⚠ Traders who struggle with overtrading — the seven quality gates physically prevent low-quality signals from appearing. You cannot overtrade what you cannot see
🔭 Forward-looking traders — the regression forecast gives you a projected roadmap that most indicators do not provide
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📝 Notes
All calculations are non-repainting — signals are confirmed on bar close only
The linear regression forecast updates on each new bar — the projection is a mathematical estimate, not a guarantee of future price action
Volume filter uses the volume data provided by your broker/data feed — for instruments or exchanges with unreliable volume, consider disabling the volume gate
The 200 SMA used in scoring requires 200 bars of history to calculate — on very short chart histories, this factor may not contribute to early signals
Maximum 500 labels per chart are supported by PulseWire — on very low timeframes with extended history, oldest labels may be automatically removed
The forecast polyline uses PulseWire's polyline drawing objects — a maximum of 100 polylines are allocated
Dashboard uses a table object that updates on the last bar — it reflects real-time values on live charts
Squeeze momentum calculation uses the John Carter method — linear regression of the midline-basis deviation over the BB length
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Disclaimer
This indicator is a technical analysis and visualization tool intended for educational and informational purposes only. It does not constitute financial advice or a recommendation to buy or sell any financial instrument. All signals are generated from historical and real-time price data using mathematical calculations — their accuracy or profitability is not guaranteed. Past performance of any signal type does not guarantee future results. Always conduct your own analysis, use proper risk management, and consult a licensed financial advisor before making any trading decisions. The author accepts no responsibility for any losses incurred from the use of this indicator.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Built for traders who demand clarity, precision, and institutional-grade filtering from their volatility analysis. 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

Spline Quantile Regression Channel [LuxAlgo]The Spline Quantile Regression Channel indicator implements an advanced non-linear regression model to fit a flexible, multi-level channel over recent price action. Unlike standard linear regression which identifies the mean trend, this tool fits specific price percentiles (quantiles) using cubic splines, providing robust support and resistance zones that adapt to market volatility and non-linear structures.
🔶 USAGE
The indicator is designed to provide a sophisticated view of the current trend and its extremes. By fitting cubic splines to specific quantiles, the script offers a "bendable" channel that can follow complex price movements more accurately than traditional straight-line regressions.
🔹 Trend Identification
The median line (default 0.5 quantile) represents the central tendency of the price action. When the spline is sloping upward, it indicates a non-linear bullish regime; a downward slope indicates a bearish regime.
🔹 Support and Resistance
The upper and lower bands represent the specified extremes (e.g., the 90th and 10th percentiles). These act as dynamic boundaries:
Prices reaching the upper band often indicate overextended conditions within the current lookback period.
Prices reaching the lower band suggest the asset is trading at the lower end of its recent distribution.
🔹 Forecasting
The indicator projects the calculated spline into the future using a dashed line. This forecast is a mathematical extrapolation of the current non-linear trend, helping traders visualize where the price distribution is headed if the current momentum and curvature persist.
🔶 DETAILS
The script employs several advanced mathematical concepts to ensure accuracy and stability:
Cubic Spline Basis: The model uses a piecewise polynomial basis ($1, x, x^2, x^3$) combined with truncated power functions at "knots." This allows the curve to change its curvature locally, adapting to swings that a simple polynomial cannot capture.
Quantile Optimization: Instead of minimizing squared errors (OLS), the script uses an Iteratively Reweighted Least Squares (IRLS) solver to minimize the "check function." This allows the script to target specific percentiles of the price data.
Numerical Stability: To prevent matrix overflows common in high-degree polynomial calculations, the script standardizes price data (Z-score) and scales time coordinates between 0 and 1 before performing matrix inversion.
🔶 SETTINGS
🔹 Spline Configuration
Lookback Period: The number of historical bars used to fit the spline regression. Larger windows result in a more "macro" trend, while smaller windows react quickly to recent changes.
Internal Knots: Determines the "flexibility" of the spline. More knots allow the curve to follow price swings more tightly, while fewer knots yield a smoother, more rigid curve.
🔹 Optimization
IRLS Iterations: The number of optimization passes for the solver. Higher values improve the accuracy of the quantile fit, especially in volatile markets.
Forecast Length: The number of bars to project the calculated spline into the future.
🔹 Quantile Levels
Upper Quantile: The specific percentile for the upper band (e.g., 0.95 for the top 5%).
Median Quantile: The central percentile (typically 0.5 for the median).
Lower Quantile: The specific percentile for the lower band (e.g., 0.05 for the bottom 5%).
🔹 Visuals
Colors: Individual color settings for the upper, median, and lower bands.
Line Width: Controls the thickness of the polylines rendered on the chart.
Indicator

Exponential Nadaraya Watson kernel regression [Jamallo](2025)
Intro
Nadaraya-Watson (N-W) kernel regression is a non-parametric smoothing technique that estimates the underlying trend of a price series without assuming any fixed model shape (like a straight line or curve). Unlike a simple moving average which weights bars equally, or an EMA which applies a fixed exponential decay, N-W regression derives its curve by computing a weighted average of all prices within a lookback window — where the weights are determined by a kernel function.
The most common kernel used is the Gaussian kernel, which assigns weights in a bell-curve shape — prices closer to the center of the window receive higher weight, prices at the edges receive lower weight. Most N-W implementations use a pure symmetric Gaussian kernel, meaning every bar within the lookback window is weighted purely by its distance from the center, with no preference for recency.
This indicator uses a hybrid Exponential Nadaraya-Watson (ENW) kernel that combines two weighting forces simultaneously:
Gaussian spatial weight — bell-curve weighting centered on the window, same as standard N-W
Exponential time-decay weight — progressively heavier weighting on recent bars, similar to how an EMA behaves
Both weights are multiplied together for each bar, meaning a price bar must be both spatially central and recent to receive maximum influence. In practice this shifts the effective weight peak toward the recent end of the window, making the K Line more responsive to current price action than standard N-W.
Breakdown
K Line — ENW Kernel Regression
The central baseline of the indicator. A smooth adaptive curve derived from the hybrid ENW kernel applied to closing prices. Bandwidth is controlled via the Kernel Length and Alpha inputs — higher alpha increases the recency bias, lower alpha brings behavior closer to standard N-W.
Volatility Bands (Inner & Outer)
Rather than using ATR or standard deviation for band width, this indicator measures the absolute deviation of price from the K Line and smooths that deviation through the same ENW kernel. This means bands are fully adaptive — they expand and contract organically based on how far price has been straying from the regression curve, not a fixed statistical formula. Inner and outer bands are independently scaled via deviation multipliers.
A Line — Vervoort ATR Stop
A trailing stop built on the HLC4 price source with an ATR-based loss distance. Flips direction on a close beyond the stop level. Serves as the primary trend bias line — when above the K Line the fill turns bullish, when below it turns bearish. Cross signals (triangles) are plotted whenever the A Line crosses the K Line, marking potential trend shifts.
Signal Line — Vervoort ATR Stop (Secondary)
A second independent Vervoort trailing stop running on its own ATR period and multiplier settings. Typically configured looser than the A Line — wider multiplier, longer or equal period — so it acts as a slower confirmation layer. Useful for filtering noise on the A Line crosses: an A Line cross that also aligns with the Signal Line's bias carries more weight than one that doesn't.
-------
Nadaraya-Watson kernel regression concept — E. Nadaraya (1964), G.S. Watson (1964)
Vervoort ATR Stop — Sylvain Vervoort
Indicator

Analogue Matcher | GainzAlgoAnalogue Matcher: Dual-Path Regression Projection
What It Is
The Analogue Matcher is a high-performance pattern recognition engine designed to find historical "price twins." Unlike standard fractals that look for raw shape similarity, this tool utilizes Linear Regression Analysis to identify periods in the past where market velocity (slope) and trend consistency ($R^2$) were near-identical to current conditions. It then projects those historical outcomes forward as "Ghost Candles," providing a probabilistic roadmap of where price might go.
How It Works
The indicator operates by scanning a user defined amount of lookback bars of history in real-time (Default 500).
• The Scan: It calculates the current regression slope over a user-defined window.
• The Match: It iterates through the lookback period to find the closest matches based on a strict Slope Tolerance .
• Dual-Path Intelligence: In "Dual Mode," the script identifies the single best Bullish outcome and the single best Bearish outcome simultaneously. This prevents "bias-blindness" by showing you the best-case scenarios for both directions.
Understanding Confidence & R2
The "Conf (R²)" column in your dashboard is the heart of the script's decision-making.
• Slope Similarity: Measures how closely the historical angle matches the current angle.
• R2 (Coefficient of Determination) : Measures the "cleanliness" of the trend. An R2 of 100.0 is a perfect straight line; 0.0 is pure noise.
• The Percentage: Our algorithm combines these two factors. A 90%+ Confidence rating means you have found a historical twin that moved at the same speed and with the same level of trend maturity as the current bar.
How to Use: A Risk Management Approach
This is not a "magic signal" generator—it is a Risk Management and Bias Tool .
• Identify Convergence: If both the Bullish and Bearish paths show high confidence (>80%) and both point in the same direction, you have high-probability confluence.
• Divergence Warning: If the Bullish path has 95% confidence but the Bearish path has only 10%, the historical precedent for a trend reversal is mathematically weak. Your bias in this case would lean bullish. Inverse if it’s flipped with a high bearish confidence and a low bullish confidence.
• Filtering Noise: Use the R2 percentage to ignore "messy" matches. If the confidence is below 50%, the analogue is likely too "noisy" to be used for a high-conviction trade entry.
• Single Mode for Speed: Switch to Single Mode on lower timeframes (1m, 5m) to find the absolute "Best Fit" twin for quick scalping targets.
Master the Engine: Key Inputs
To get the most out of the Analogue Matcher , it’s essential to understand the "knobs" you are turning. Tuning these correctly is the difference between finding a perfect twin and seeing random noise.
• Mode Selection (Single vs. Dual): Single Mode: Focuses the processing power on finding the absolute "Best Fit" regardless of direction. Ideal for high-speed scalping or very large lookbacks. Dual Mode: The full "Risk Management" suite. It forces the script to find both a Bullish and a Bearish path to show you the two most likely outcomes.
• Projection Window: This determines the size of the "Ghost." If set to 50, the script analyzes a 50-bar trend and projects a 50-bar future.
• Lookback Period: This is how far into the past the engine scans. While the script is optimized for performance, keeping this within a reasonable range (500–2000) ensures fast UI response.
• Slope Tolerance: This is your "Sensitivity" setting. Lower Values (0.001 - 0.004): Very strict. The script will only show matches that have a nearly identical angle of attack. Higher Values (>0.01): More lenient. Use this in highly volatile markets (like Crypto) where trends are aggressive and vary in steepness.
Examples
In this image, we can see BTCUSD on the daily. The confidence favours a bullish move, both Bearish and Bullish possible paths are plotted. Let’s see what happens.
The outcome was an initial bullish move though with a bit of a neutral tilt, as it ended relatively flat.
Now let us look at ES1!:
In this case, the indicator is showing 2 possible paths (Dual Mode), with a bullish tilt. Let’s see what happened next:
The move was indeed bullish, and volatility remained intact through the move.
Important Considerations
The indicators true strength stems from its ability to act as a risk management tool and compare the degree of “fit” of each respective path (i.e. bullish vs. bearish). If you are looking to take a bearish position on a ticker, but you see that the R2 skew slightly favours a move to the upside, you may want to hold off on pulling the short trigger until you have a skew that fits your bias.
While the paths are likely not going to be a perfect, identical match, the power comes from understanding the confidence skew of the bullish vs bearish path. This is your saving grace for managing risk in your positions.
Though the matches are not likely to be perfect, they are scaled to the ticker’s ATR and thus can be used to help you gauge potential entries, exits and positioning areas.
For example, if we look at SPY on the hourly timeframe:
We see we have a bearish skew. The bearish path has sizeable upside. We can use this forecasted range to identify potential entry/resistance areas like so:
Now let’s see how it plays out:
You can see that the key forecast areas provided actual levels for support and resistance!
Concluding Remarks
In a market driven by algorithmic repetition, the Analogue Matcher gives you the power to see the "scripts" the market has run before. By quantifying the similarity of price action through regression, traders can move away from "gut feelings" and toward data-driven forecasts.
Indicator
