MAD Adaptive Trend Score [BackQuant]MAD Adaptive Trend Score
Overview
MAD Adaptive Trend Score is a trend oscillator built from a Median Absolute Deviation-based price filter and a multi-lookback relative-position score.
The indicator first calculates a rolling median and MAD from the selected source. Price deviation from the median is then clipped to a configurable MAD envelope, producing the MAD Adaptive Filter.
The current value of that filtered series is then compared with a range of its previous values. Each comparison contributes either +1 or -1 to a Trend Score.
The result is a bounded directional score that can be used with separate bullish and bearish thresholds to create a persistent trend state.
The script includes:
Exact rolling median and MAD calculations.
MAD-based clipping of source movement.
Configurable multi-lookback Trend Score.
Separate long and short regime thresholds.
Optional filter overlay on the main chart.
Trend candle colouring and signals.
Reference levels and alerts.
MAD Adaptive Filter
The first stage calculates the rolling median of the selected Source over the MAD Length.
It then calculates Median Absolute Deviation:
MAD = Median(|X - Median(X)|)
Raw MAD is multiplied by 1.4826:
Scaled MAD = Raw MAD × 1.4826
with a minimum value based on the instrument's minimum tick.
The 1.4826 factor is commonly used to scale MAD to approximately the same scale as standard deviation when the underlying distribution is normal.
The indicator then measures:
Deviation = Source - Rolling Median
and defines the maximum permitted deviation as:
Maximum Deviation = Scaled MAD × MAD Multiplier
The source deviation is clipped to this range before being added back to the median.
Conceptually:
If Source remains inside the MAD envelope, the filter follows Source.
If Source moves above the envelope, the filter is limited to the upper MAD boundary.
If Source moves below the envelope, the filter is limited to the lower MAD boundary.
The MAD Adaptive Filter is therefore not a conventional moving average. It is a source series whose distance from its rolling median is limited by the current MAD-derived envelope.
MAD Multiplier
MAD Multiplier controls the permitted distance between the filtered value and the rolling median.
Lower values:
Create a tighter envelope.
Clip more of the source movement.
Keep the filter closer to the median.
Higher values:
Create a wider envelope.
Allow more source movement through unchanged.
Make the filter follow price more closely.
Trend Score
The second stage scores the current MAD Filter against several previous values of the same filtered series.
For every lookback between Score Lookback Start and End:
+1 if the current MAD Filter is above the historical MAD Filter.
-1 otherwise.
The final Trend Score is the sum of all comparisons.
If N historical values are being compared, the theoretical score range is:
-N to +N
For the default 1-to-45 range, 45 comparisons are made, so the score can range from -45 to +45.
What the score represents
A high positive score means the current MAD-filtered value is above most of the historical filtered values being compared.
A strongly negative score means it is above very few of them.
For example, with 45 comparisons:
A score near +45 means the current filtered value is above nearly the entire comparison range.
A score near 0 means the comparisons are more evenly divided.
A score near -45 means the current filtered value is below, or equal to, nearly all of them.
The score is therefore best understood as a relative position / trend score of the filtered series.
It is not a return forecast or probability of future direction.
Why use several lookbacks?
Comparing the current filter with only one previous value would effectively reduce the calculation to short-term slope.
Using many previous values instead measures where the current filtered level sits relative to a broader section of its history.
A steadily rising filtered series will generally move toward higher positive scores because the current value becomes greater than an increasing number of historical values.
During sustained weakness, the opposite occurs.
Score Lookback Start and End
These settings define which historical MAD Filter values participate in the score.
For example:
Start = 1
End = 45
compares the current filter against each filtered value from 1 through 45 bars ago.
A shorter range:
Responds more quickly to recent changes.
Creates a smaller score range.
A longer range:
Includes more historical comparisons.
Produces a broader measure of relative trend position.
Usually changes more gradually.
Because the score range depends on the number of comparisons, threshold settings should be chosen with the selected score range in mind.
Trend State
The script converts the Trend Score into a persistent bullish or bearish signal state.
The bullish and bearish rules are deliberately separate.
Bullish condition
The signal becomes bullish when:
Trend Score > Long Threshold
Once bullish, the state remains bullish until a valid bearish condition occurs.
Bearish condition
The signal becomes bearish when the score crosses downward through the Short Threshold:
Previous Score >= Short Threshold
Current Score < Short Threshold
The bearish condition therefore requires an actual downward threshold crossing rather than simply remaining below the level.
Why use separate thresholds?
Using different bullish and bearish levels introduces persistence into the regime.
The signal does not need to reverse whenever the score crosses zero.
For example, with:
Long Threshold = 40
Short Threshold = -6
the score must reach a strongly positive state before the model turns bullish, but the bullish state can persist through a substantial amount of score deterioration before a bearish transition occurs.
This creates a form of threshold hysteresis and reduces rapid switching around a single center level.
The thresholds are fully configurable and do not need to be symmetrical.
Initial state
The signal begins neutral.
A bullish state can be established once the Long Threshold condition is satisfied.
A bearish state requires a valid downward crossing of the Short Threshold.
Signal markers are shown only when an established bullish state changes to bearish or an established bearish state changes to bullish.
The initial transition from neutral does not produce a long/short marker.
Reference Lines
The optional dashed reference lines display the Long and Short Thresholds directly in the oscillator pane.
These levels correspond to the actual regime settings and can be useful when visually tracking how the Trend Score approaches a possible state change.
MAD Filter Overlay
The MAD Adaptive Filter can optionally be plotted directly on the main price chart.
This makes it possible to compare:
Raw price.
The rolling-median/MAD envelope response.
The active trend colour.
The overlay uses the same bullish or bearish state colour as the oscillator.
Trend Candles
Optional chart candles are coloured from the stored trend state:
Bullish state = Long Color.
Bearish state = Short Color.
The colour represents the indicator's trend regime rather than the direction of each individual candle.
Background Colour
An optional transparent background can also display the current trend regime on the main chart.
This is purely visual and does not alter the calculation.
How to interpret it
Strong positive score
The current MAD Filter is above most values in the selected historical comparison range.
This typically accompanies a relatively strong upward position in the filtered trend.
Falling score while still bullish
The filtered trend is losing relative strength, but the Short Threshold has not yet been crossed.
The persistent state therefore remains bullish.
Short Threshold crossing
The score has deteriorated far enough to cross below the selected bearish boundary, changing the stored state to bearish.
Rising score while bearish
The score can recover substantially while the trend remains bearish.
A new bullish state is not established until the score exceeds the Long Threshold.
How to use the indicator
The indicator can be used as:
A directional trend filter.
A persistent bullish/bearish regime indicator.
A way to measure the relative position of a MAD-filtered price series.
A confirmation tool alongside other price or market-structure analysis.
The score itself can also provide additional context beyond the binary trend colour.
For example, a bullish regime with a score near its maximum is different from a bullish regime whose score has already fallen substantially toward the bearish threshold.
Input Guide
MAD Length
Controls the rolling sample used to calculate the median and Median Absolute Deviation.
Shorter values adapt more quickly.
Longer values produce a broader statistical reference window.
MAD Multiplier
Controls how far the filtered source may move away from its rolling median.
Lower values produce stronger clipping.
Higher values allow the filter to follow Source more closely.
Score Lookback Start / End
Defines the historical MAD Filter values used in the Trend Score comparisons.
Long Threshold
Score level that must be exceeded to establish a bullish state.
Short Threshold
Level that must be crossed downward to establish a bearish state.
Data Window
The script exposes:
Rolling Median.
Raw MAD.
Scaled MAD.
These values can help show how the underlying MAD filter is being constructed.
Limitations
The indicator is reactive rather than predictive.
The score measures the current filtered value relative to historical filtered values; it does not estimate future returns.
Threshold selection can materially change signal frequency and persistence.
A very tight MAD Multiplier can suppress meaningful movement along with noise.
A very wide MAD Multiplier makes the filter increasingly similar to the original Source.
Long score ranges can improve persistence but also delay changes in regime.
Strong trends can keep the score near an extreme for extended periods.
Alerts
The script includes:
MAD Trend Score Long: stored signal changes from bearish to bullish.
MAD Trend Score Short: stored signal changes from bullish to bearish.
Summary
MAD Adaptive Trend Score combines two simple ideas.
First, the selected Source is constrained around a rolling median using Median Absolute Deviation. Source movement inside the MAD envelope passes through normally, while movement beyond the envelope is clipped to the current boundary.
Second, the current filtered value is compared with a configurable range of its own historical values.
Those comparisons are summed into a Trend Score, with positive values indicating that the current filtered level is above more of the historical comparison range and negative values indicating the opposite.
Separate Long and Short Thresholds then convert the score into a persistent bullish or bearish regime.
The result is a MAD-based filtered series and relative-position trend score for experimenting with trend persistence and threshold behaviour. 지표

Variance-Weighted Regression Trend [BackQuant]Variance-Weighted Regression Trend
Overview
Variance-Weighted Regression Trend is a rolling linear-regression trend indicator that adjusts the influence of observations according to the estimated variance of their regression residuals.
The script first calculates a standard ordinary least-squares regression across the selected window. It then measures the squared residuals around that fit and uses those residuals to estimate how variable the regression error has been through the sample.
Those variance estimates are converted into relative weights. Lower estimated residual variance can receive more influence, while higher estimated residual variance can receive less. A second weighted regression is then calculated using those weights.
The indicator also includes:
EMA, RMA or rolling-average residual variance.
Configurable inverse-variance weighting strength.
Weight regularization and upper/lower weight limits.
Weighted R² and slope-quality diagnostics.
Two regression-channel methods.
Optional trend-flip quality confirmation.
OLS comparison.
Linear regression projection.
Trend colouring and alerts.
Calculation
The basic process is:
Fit an ordinary least-squares regression over the Regression Length.
Calculate the squared residual of every observation around that fit.
Smooth those squared residuals to estimate local residual variance.
Add a regularization floor to reduce unstable extreme weights.
Convert variance into relative observation weights.
Clamp weights between the selected minimum and maximum.
Calculate a second weighted regression.
The weighted line is therefore influenced more by observations receiving larger relative weights and less by those receiving smaller ones.
Variance Weighting
The weighting is based on regression residual variance , not ATR, trading volume or raw price volatility.
For each point:
Residual = Source - OLS fitted value
Squared Residual = Residual²
The squared residuals are then processed using the selected Variance Model.
EMA
Uses exponential smoothing and responds more quickly to recent residual changes.
RMA
Uses a slower recursive smoothing process.
Rolling Mean
Uses a finite moving average of squared residuals.
Weight Power
Weight Power controls how strongly estimated variance affects the regression.
The raw weighting relationship is:
Weight ∝ 1 / Variance^Weight Power
0 gives equal weighting, making the final fit behave like the OLS regression.
1 applies standard inverse-variance-style weighting.
Values above 1 increase the difference between low- and high-variance observations.
Higher settings can make the regression more selective, but can also concentrate too much influence in a small part of the sample.
Variance Regularization
Very small variance estimates can otherwise create extremely large inverse weights.
The script therefore adds a fraction of the window's mean squared residual to each local variance estimate.
Higher regularization makes the weights more uniform.
Lower regularization allows stronger differences between observations.
Minimum and Maximum Relative Weight
Raw weights are normalized relative to their average before being clamped.
A relative weight above 1 means the observation has greater-than-average influence.
A value below 1 means it has less.
The Minimum Relative Weight prevents high-variance observations from effectively disappearing from the regression.
The Maximum Relative Weight prevents very low-variance observations from dominating the entire fit.
Weighted Regression
Once the final weights are calculated, the script solves a weighted linear regression:
Y = Intercept + Slope × X
The displayed line is the current endpoint of that rolling weighted regression.
Each new bar shifts the regression window and recalculates:
OLS.
Residuals.
Variance estimates.
Weights.
Weighted slope and intercept.
OLS Comparison
The optional OLS line shows the endpoint of the initial equal-weight regression.
This makes it easy to see how much the variance weighting is actually changing the result.
If Weight Power is set to 0, the weighted regression and OLS should be effectively aligned.
As the weighting becomes more aggressive, the lines may separate depending on the residual structure inside the window.
Trend State
Trend direction comes from the sign of the weighted regression slope.
Positive slope = bullish.
Negative slope = bearish.
A bullish flip occurs when the stored trend changes from bearish to bullish.
A bearish flip occurs when it changes from bullish to bearish.
Quality Confirmation
Quality Confirmation can be enabled to prevent weak slope changes from immediately flipping the trend state.
When enabled, an opposite slope must also satisfy:
Minimum Weighted R².
Minimum Slope / Standard Error.
If those conditions are not met, the existing trend state remains active even if the current slope temporarily changes sign.
Weighted R²
Weighted R² measures how well the weighted straight-line regression describes the current sample.
Higher values indicate that the weighted observations are more closely aligned with a linear fit.
Lower values indicate a less orderly linear relationship.
R² does not determine trend direction and should not be interpreted as a forecast of future performance.
Slope / Standard Error
The script calculates the absolute weighted slope relative to its estimated standard error:
|Slope| / Slope Standard Error
This is used as a practical slope-quality measure.
Higher values indicate that the fitted slope is larger relative to the estimated regression error.
It is used by the optional Quality Confirmation setting and is not presented as a formal significance test.
Regression Channels
Two channel-width methods are available.
Weighted Residual RMS
Uses the weighted root-mean-square distance of observations from the fitted regression.
This reflects the general amount of scatter around the line.
Regression Standard Error
Uses the calculated standard error of the fitted current regression value.
This normally represents a different and often narrower measure than residual RMS.
The Channel Multiplier scales whichever method is selected.
Expand During Poor Fit
When enabled, the channel becomes wider as Weighted R² decreases.
This is intended to visually reflect greater uncertainty when the current window is poorly described by a straight line.
The expansion affects only the channel width.
It does not alter the regression or trend calculation.
Projection
The Projection extends the current regression slope forward by the selected number of bars.
It is simply:
Current fitted line extended using the current slope.
It is not a separate forecasting model.
As the regression changes on new bars, the projection also changes.
Current Relative Weight
The Data Window shows the final relative weight assigned to the newest observation.
A value:
Above 1 = greater-than-average influence.
Below 1 = less-than-average influence.
This can help show how the current observation is being treated by the variance-weighting model.
Effective Sample Size
The indicator also reports:
Effective N = (Sum of Weights)² / Sum of Squared Weights
This provides a simple measure of weight concentration.
If weights are similar, Effective N remains close to the full Regression Length.
If a smaller group of observations receives most of the weight, Effective N falls.
This is useful when experimenting with aggressive Weight Power or wide weight limits.
Trend Strength
Trend Strength is used only for the regression glow.
It combines:
60% Weighted R².
40% normalized Slope / Standard Error.
It does not affect the regression or signals.
ATR(14) is used only to scale the visual width of the glow and flip bloom to the instrument.
Input Guide
Regression Length
Controls the size of the rolling regression sample.
Projection Bars
Controls how far the current fitted slope is extended visually.
Variance Length
Controls how quickly the residual-variance estimate changes.
Variance Model
Selects EMA, RMA or Rolling Mean smoothing of squared residuals.
Weight Power
Controls the strength of inverse-variance weighting.
Variance Regularization
Reduces extreme differences between weights.
Minimum / Maximum Relative Weight
Limits how little or how much influence any one observation can receive.
Channel Width
Selects Weighted Residual RMS or Regression Standard Error.
Channel Multiplier
Scales the regression channel.
Poor Fit Expansion
Optionally widens the channel as R² deteriorates.
Quality Confirmation
Requires minimum regression fit and slope quality before allowing trend flips.
How to use it
The indicator can be used as:
A regression-based trend filter.
A comparison between ordinary and variance-weighted regression.
A way to study how residual-based weighting changes a rolling trend estimate.
A trend-quality filter using R² and slope strength.
A regression channel for visualizing fit dispersion.
The OLS Comparison and Data Window values are particularly useful when testing the weighting settings, because they show whether the extra weighting is materially changing the regression or simply producing a result close to ordinary least squares.
Limitations
The variance estimates are derived from OLS residuals inside the same rolling window.
The model is a custom two-stage weighted regression rather than a full generalized least-squares procedure.
Higher Weight Power can concentrate the fit in a relatively small part of the sample.
Linear regression cannot represent every type of market structure.
High R² does not imply future trend continuation.
The forward projection is only a linear extrapolation of the current fit.
Quality Confirmation can reduce weak flips but can also delay genuine changes in direction.
Data Window
The script exposes:
Weighted Slope.
Weighted R².
Slope / Standard Error.
Weighted Residual RMS.
Regression Standard Error.
Current Relative Weight.
Effective Sample Size.
Trend Strength.
Alerts
The indicator includes:
Variance-Weighted Regression Bullish: trend changes from bearish to bullish.
Variance-Weighted Regression Bearish: trend changes from bullish to bearish.
Variance-Weighted Regression Flip: either transition occurs.
Summary
Variance-Weighted Regression Trend starts with a normal rolling OLS regression, measures the residual variance around that fit, and uses those estimates to assign relative weights to the observations in a second regression.
The weighting strength, variance smoothing, regularization and weight limits are all configurable, making it possible to move from essentially equal-weight OLS to a much more selective fit.
The final weighted slope controls the trend state, while Weighted R² and the Slope / Standard Error score can optionally be used to filter weak reversals.
Regression channels, OLS comparison, forward projection and the visual strength system provide additional context around the core weighted regression without changing the underlying trend logic.
지표

MAD Volatility Trail [BackQuant]MAD Volatility Trail
Overview
MAD Volatility Trail is a robust trend-following overlay built from a rolling median and Median Absolute Deviation rather than a conventional moving average and standard deviation.
The indicator estimates a central price using the rolling median, measures how widely recent prices are distributed around that median using MAD, converts that dispersion into adaptive upper and lower bands, and then transforms those bands into one-sided trailing boundaries.
The result is a persistent bullish or bearish trend regime with:
A robust median-based center.
MAD-derived volatility bands.
Optional ATR minimum band width.
One-sided trailing support and resistance.
Optional median-slope confirmation.
Bullish and bearish regime flips.
Strength-reactive gradient and glow.
Post-flip bloom visualization.
Trend-coloured candles.
Signal and alert support.
The main distinction is statistical.
Most volatility trails rely on:
Means.
Standard deviation.
ATR.
MAD Volatility Trail instead uses:
Median.
Median Absolute Deviation.
Median-based statistics are substantially less sensitive to isolated extreme observations, making the framework useful when the user wants a trend structure that is less influenced by individual spikes or outliers.
Core concept
The indicator separates the problem into four stages:
Estimate a robust rolling center using the median.
Measure robust dispersion around that center using MAD.
Build upper and lower adaptive deviation bands.
Convert those raw bands into persistent trailing trend boundaries.
The resulting trail behaves conceptually like a volatility-aware regime filter, but its volatility estimate comes primarily from the empirical distribution of price around its median.
Why median instead of mean?
A conventional arithmetic mean is calculated by summing all observations and dividing by their count.
Every value directly affects the result.
This makes the mean sensitive to outliers.
Consider a simplified sample:
100
101
101
102
150
The extreme value at 150 pulls the arithmetic mean upward substantially.
The median is simply the middle observation after sorting:
Median = 101
The single extreme observation has much less influence.
This property is called robustness .
In markets, isolated large candles, gaps, liquidation events and temporary price spikes can distort mean-based statistics. Median-based calculations intentionally reduce the influence of those individual observations.
Rolling median
For each bar, the indicator collects the selected Source values across the MAD Lookback.
It then calculates the exact median of the available observations.
For an odd number of observations, the median is the middle sorted value.
For an even number, the median lies between the two central observations according to the median implementation.
The resulting value becomes the statistical center of the trail.
Unlike an EMA or RMA, the median is not recursively smoothed.
It is recomputed from the actual distribution of values inside the current rolling window.
Early-history behaviour
At the beginning of the chart, the script ignores unavailable historical values.
This means the first valid median calculations may use fewer observations than the full MAD Lookback until sufficient chart history has accumulated.
Once the complete lookback is available, the calculation uses the full selected window.
Median Absolute Deviation
After calculating the rolling median, the script measures the absolute distance of every observation from that median:
Absolute Deviation = |Value - Median|
It then takes the median of those absolute deviations:
MAD = Median(|Xi - Median(X)|)
This is the Median Absolute Deviation .
MAD measures the typical distance of observations from the median.
It serves a role similar to standard deviation, but the mathematics and statistical behaviour are different.
Why MAD is robust
Standard deviation squares deviations from the mean.
Large deviations therefore receive disproportionately large influence.
A single extreme observation can:
Move the mean.
Create a very large squared deviation.
Increase the final standard deviation substantially.
MAD does not square deviations.
It calculates absolute distance and then takes another median.
Extreme values therefore have limited ability to change the result unless enough of the underlying sample shifts.
This gives MAD a high resistance to outliers.
In practical chart terms, one unusual wick or shock candle is less likely to inflate the statistical width as dramatically as it could under a standard-deviation model.
MAD versus standard deviation
The two measures answer related but different questions.
Standard deviation
Measures squared dispersion around the arithmetic mean.
MAD
Measures median absolute dispersion around the median.
Standard deviation is highly useful when a mean-and-variance framework is desired.
MAD is useful when robustness to unusual observations is more important.
The indicator does not claim one is universally superior.
It intentionally uses MAD because the purpose is to construct a robust trend boundary.
MAD Scale
Raw MAD is not numerically identical to standard deviation.
Under a normal distribution, MAD is usually multiplied by a consistency factor of approximately 1.4826 when the goal is to make it comparable to standard deviation.
The indicator exposes this scaling directly:
Robust Deviation = Raw MAD × MAD Scale
The script default is 1.4655.
The input remains fully adjustable, so users who want the conventional normal-consistency approximation can set the factor near 1.4826.
This scale does not change the median itself.
It changes only the size of the deviation estimate used to build the bands.
Deviation Factor
After scaling MAD, the indicator applies the Deviation Factor:
MAD Width = Scaled MAD × Deviation Factor
This acts as the main sensitivity control.
Lower values:
Create narrower raw bands.
Place the trail closer to price.
Produce more frequent regime changes.
Higher values:
Create wider bands.
Require larger movement for reversals.
Produce more persistent trend states.
The MAD Scale and Deviation Factor both affect width, but they represent different concepts.
MAD Scale calibrates the statistical dispersion estimate.
Deviation Factor determines how much of that estimated dispersion is used for the trend envelope.
Raw MAD bands
The raw bands are:
Upper MAD Band = Median + Band Width
Lower MAD Band = Median - Band Width
Before trailing logic is applied, these bands can move freely upward or downward with:
The rolling median.
MAD dispersion.
Any active ATR floor.
These are statistical envelopes around the median.
They are not yet the final trend trail.
ATR Minimum Width
MAD can become extremely small when recent prices are tightly clustered.
In very low-dispersion conditions, this may place the raw bands extremely close to the median.
That can create excessive sensitivity to minor price fluctuations.
The optional ATR Minimum Width provides a secondary floor.
The script calculates:
ATR Floor = ATR(ATR Length) × ATR Floor Multiplier
When enabled:
Band Width = max(MAD Width, ATR Floor)
This means MAD remains the primary volatility model, but the bands cannot contract below the selected ATR-based threshold.
Why use an ATR floor?
MAD and ATR measure different aspects of market behaviour.
MAD measures:
Dispersion of the selected source around its rolling median.
ATR measures:
Bar-to-bar trading range.
Gaps relative to the previous close.
A market can have:
Low median dispersion.
But still produce meaningful intrabar range.
The ATR floor can prevent the trail from becoming unrealistically tight under those conditions.
ATR floor disabled
With ATR Minimum Width disabled, the entire structural width comes from:
MAD × MAD Scale × Deviation Factor
This produces the purest MAD-based version of the indicator.
ATR Length
ATR Length controls the volatility horizon used only for the optional minimum-width calculation.
It does not affect:
The rolling median.
Raw MAD.
Scaled MAD.
Note that the visual glow and bloom later in the script use a fixed ATR(14), separate from this ATR Length input.
Trailing bands
The raw MAD bands are converted into one-sided trails.
This is the stage that turns a statistical envelope into a persistent trend system.
Two independent trails are maintained:
Lower Trail.
Upper Trail.
Lower Trail
When the previous trigger remains above the previous Lower Trail, the new Lower Trail is:
max(Current Raw Lower Band, Previous Lower Trail)
This means the Lower Trail can:
Move upward.
Remain unchanged.
But cannot move downward while the condition remains active.
This creates a ratcheting support structure.
If the trigger falls below the prior Lower Trail, the trail is allowed to reset to the new raw lower band.
Upper Trail
When the previous trigger remains below the previous Upper Trail, the new Upper Trail is:
min(Current Raw Upper Band, Previous Upper Trail)
This means the Upper Trail can:
Move downward.
Remain unchanged.
But cannot move upward while the condition remains active.
This creates a ratcheting resistance structure.
If the trigger rises above the previous Upper Trail, the band can reset to the current raw upper value.
Why trailing the bands matters
A raw median-deviation envelope moves in both directions.
If those raw bands were used directly for trend changes:
The threshold itself could retreat toward price.
Small changes in median or MAD could produce unstable reversals.
The one-sided trail introduces hysteresis .
Hysteresis means that once a trend regime is established, the threshold required to reverse it remains on the opposing side.
This reduces the tendency to flip repeatedly around the rolling median.
Flip Trigger
The user can choose which series is used when evaluating trail breaks:
Close.
Source.
Close
Uses the candle close regardless of which series is used for the MAD calculation.
This is the conventional option.
Source
Uses the selected Source input.
For example, if HLC3 is selected as the Source:
The median is calculated from HLC3.
MAD is calculated from HLC3.
The trail can also be triggered by HLC3.
This keeps the center, dispersion and reversal trigger based on the same source.
Initial trend state
The trend begins in a neutral state.
Once a valid rolling median is available:
Trigger at or above Median = bullish initialization.
Trigger below Median = bearish initialization.
This initial assignment is not treated as a bullish or bearish flip.
Flip signals occur only after the indicator has already established one regime and later transitions into the opposite regime.
Bullish flip
A bullish regime change requires:
Trigger to move above the Upper Trail.
Current trend not already bullish.
Optional bullish median-slope confirmation to pass.
Once confirmed:
Trend becomes bullish.
The Lower Trail becomes the active trend boundary.
A bullish signal can be displayed.
Bearish flip
A bearish regime change requires:
Trigger to move below the Lower Trail.
Current trend not already bearish.
Optional bearish median-slope confirmation to pass.
Once confirmed:
Trend becomes bearish.
The Upper Trail becomes the active boundary.
A bearish signal can be displayed.
Active trend trail
The final displayed trend boundary depends on the regime:
Bullish = Lower Trail.
Bearish = Upper Trail.
This means the line automatically moves to the opposite side of price when a complete regime change occurs.
Median Slope Confirmation
The optional Median Slope Confirmation adds a directional requirement to trend reversals.
For a bullish flip:
Current Median > Median from Slope Lookback bars ago
For a bearish flip:
Current Median < Median from Slope Lookback bars ago
This requires the robust statistical center itself to move in the direction of the proposed new trend.
Why confirm with median slope?
Price can briefly cross a trail while the underlying median remains flat or continues moving in the opposite direction.
Slope confirmation can reject some of these events.
For example:
A bullish trail break with a still-falling median may represent:
A temporary rebound.
A liquidity sweep.
Noise inside a larger bearish structure.
Requiring the median to rise adds another layer of confirmation.
The trade-off is lag.
A genuine reversal may cross the trail before the rolling median has clearly changed direction.
Slope Lookback
Slope Lookback controls how far back the median is compared.
Lower values:
Respond more quickly.
Require only a very local median turn.
Higher values:
Require a broader directional shift.
Produce stronger confirmation.
Can delay reversals.
This same lookback is also used in the visual slope-strength calculation even when slope confirmation itself is disabled.
Break Trail On Flips
When enabled, the displayed trail is temporarily hidden on the actual regime-flip bar.
This creates a visual break between:
The previous regime’s trail.
The new regime’s trail.
Without the break, the plotting engine can draw a connecting segment from one side of the market to the other.
That connection has no analytical meaning.
Break Trail On Flips affects visualization only.
It does not affect:
Trend state.
Raw bands.
Trail calculations.
Signals.
Robust trend structure
The complete structural model can therefore be summarized as:
Rolling Median determines robust center.
MAD determines robust dispersion.
MAD Scale calibrates the dispersion.
Deviation Factor determines band distance.
Optional ATR floor prevents excessive compression.
Raw bands form the initial envelope.
Ratchet logic creates trailing support and resistance.
Opposite-trail breaks determine regime changes.
Optional median slope confirms those reversals.
This combination is what separates the indicator from simply plotting median ± MAD.
Visual strength model
The script calculates a separate Trend Strength value used only to control the presentation of the gradient and glow.
It does not alter:
Trend direction.
Trail levels.
Flip conditions.
Trend Strength combines:
Price distance from the active trail.
Absolute rolling-median slope.
Distance Strength
The script first measures:
Trail Distance = |Close - Active Trail|
This is normalized by the current band width.
The normalized distance is capped when price reaches twice the active band width away from the trail.
Conceptually:
Close to trail = low distance strength.
Far from trail = high distance strength.
This reflects how separated price is from the current structural boundary.
Slope Strength
The indicator also measures:
|Current Median - Median |
This value is normalized by the current band width and capped at one.
The purpose is to compare median movement against the current statistical width.
A steep median relative to the band width produces stronger visual slope strength.
Combined Trend Strength
The final visual strength is:
70% Distance Strength.
30% Median Slope Strength.
and is capped at one.
The distance component receives greater weight because the visual system places more emphasis on how strongly price is separated from the active trail.
Again, this number is not a probability, forecast or additional signal.
It is a visual intensity measure.
Layered gradient
The area between the active trail and current close is divided into several intermediate levels.
The script creates reference points approximately:
15% of the distance from trail to price.
35%.
60%.
82%.
Then the final segment to price.
These create five layered gradient regions.
The layers become progressively more transparent as they move away from the trail.
This gives the trail visual depth without turning the entire area between price and structure into one solid block.
Gradient direction
The geometry of the gradient is determined by whether close is above or below the active trail.
The colour itself comes from the current bullish or bearish trend regime.
The gradient therefore visualizes:
The active trend colour.
The distance between price and trail.
The relative strength of the trend visualization.
The gradient does not determine the regime.
Trend-strength gradient response
Higher Trend Strength reduces transparency in several layers.
This makes the ribbon more visible when:
Price is strongly separated from the trail.
The rolling median is moving meaningfully.
Lower strength produces a softer appearance.
This allows the visual presentation to communicate more than simple bullish or bearish state.
Flip bloom
The indicator includes a temporary post-flip bloom.
The bloom is derived from the number of bars elapsed since the most recent bullish or bearish transition.
Importantly, in the current implementation the bloom begins after the flip bar:
Flip bar: no bloom boost.
1 bar after flip: maximum bloom.
2 bars after flip: reduced bloom.
3 bars after flip: smaller residual bloom.
Afterward: bloom disappears.
The relative bloom strengths are:
1.00
0.55
0.25
This emphasizes the early bars following a newly confirmed regime change.
Why bloom after the flip?
The flip itself can optionally contain a break in the trail.
Applying the bloom to the following bars emphasizes the newly established active trail rather than drawing a large effect around a temporarily hidden flip point.
The bloom is cosmetic.
It does not modify the underlying calculations.
Trail glow
The active trail can also display a persistent glow.
Glow width is based on:
ATR(14) × a factor that increases with Trend Strength
This ATR(14) is fixed for visualization and is independent of the user-selected ATR Length used by the optional minimum-width floor.
The glow therefore becomes slightly wider as visual trend strength increases.
Two layers are used:
A tighter inner glow.
A broader outer glow.
The inner glow responds more strongly to Trend Strength and post-flip bloom.
Rolling Median display
The rolling median can be displayed independently from the trail.
This is useful for studying the difference between:
The current robust center.
The statistical raw bands.
The ratcheting trend trail.
During a bullish regime, the active Lower Trail can remain below the rolling median.
During a bearish regime, the active Upper Trail can remain above it.
The median is not itself the trend signal.
Raw MAD Bands display
The raw upper and lower MAD bands can also be shown.
These lines make it easier to see how the trailing logic differs from the unrestricted statistical envelope.
Raw bands:
Can move in either direction.
Trailing bands:
Can ratchet in only one direction while their persistence condition remains active.
The gap between raw and trailing levels illustrates the hysteresis introduced by the trend logic.
Trend candles
The script can redraw candles on the main chart using the active trend colour.
Bullish regime:
Uses the selected Bullish colour.
Bearish regime:
Uses the selected Bearish colour.
The candle colour represents the persistent trail regime, not whether each individual candle closed higher or lower.
A bearish candle can therefore remain bullish-coloured while the broader MAD Trail regime remains bullish.
Signal markers
Bullish and bearish markers appear only on complete transitions between established regimes.
A bullish marker requires:
Previous trend = bearish.
Current trend = bullish.
A bearish marker requires:
Previous trend = bullish.
Current trend = bearish.
Initial trend assignment does not generate a flip marker.
How to interpret the indicator
Bullish regime
A bullish state means price has previously broken above the opposing Upper Trail and the Lower Trail is now active.
The Lower Trail can be interpreted as:
Dynamic trend support.
A structural invalidation reference.
A trailing regime boundary.
Bearish regime
A bearish state means price has broken below the opposing Lower Trail and the Upper Trail is active.
The Upper Trail can be interpreted as:
Dynamic resistance.
A bearish invalidation reference.
A trailing regime boundary.
Price close to trail
When price approaches the active trail:
Visual distance strength decreases.
The gradient becomes softer.
The market is closer to the regime boundary.
This does not guarantee a reversal.
A healthy trend can repeatedly retest its active trail.
Price far from trail
When price moves substantially away:
Distance Strength rises.
The visual effect becomes stronger.
This indicates greater separation from the active structural boundary.
It should not automatically be interpreted as a better entry.
A market can be strongly extended and simultaneously close to exhaustion.
Median and trail rising together
During a bullish regime, a rising median combined with a rising Lower Trail indicates:
The robust center is moving upward.
The structural support boundary is also advancing.
This represents cleaner directional alignment.
Median flattening while trail remains bullish
The persistent regime can remain bullish while the median begins flattening.
This indicates:
The trend has not yet been invalidated.
But the robust center is no longer advancing as strongly.
The visual slope-strength component may weaken under this condition.
Raw band expansion
If MAD increases:
Raw bands widen.
Trail reset levels can move farther away.
This means recent source values are becoming more dispersed around the median.
Raw band contraction
If MAD falls:
The raw envelope tightens.
If the ATR floor is disabled, the structure can become substantially narrower.
If the ATR floor is enabled, contraction stops once the selected minimum width is reached.
How to use the indicator
1. Trend regime filter
Use the persistent trail state as directional context:
Bullish trail regime = prioritize long-side setups.
Bearish trail regime = prioritize short-side setups.
The trail does not define a complete trading system by itself.
2. Pullback structure
During a bullish regime, the Lower Trail can provide a dynamic reference for deeper pullbacks.
During a bearish regime, the Upper Trail can provide a reference for rallies.
The farther price moves from the trail, the greater the current structural separation.
3. Regime transitions
Bullish and bearish flips identify moments when price has crossed completely through the opposing robust-deviation trail.
These may be used as:
Trend-change alerts.
Confirmation for another entry method.
Potential exit conditions.
4. Median confirmation
Users who want more selective signals can enable Median Slope Confirmation.
This can be especially useful when:
The market is choppy.
Price frequently sweeps through statistical boundaries.
5. Pure robust-volatility mode
Disable the ATR Minimum Width to make band width depend only on:
Rolling MAD.
MAD Scale.
Deviation Factor.
This produces the purest version of the model.
6. Hybrid robust-volatility mode
Enable ATR Minimum Width when the MAD channel becomes too narrow for the instrument or timeframe.
This preserves MAD as the primary engine while adding a conventional range-based safety floor.
Input guide
Source
Series used for the rolling median and MAD calculation.
MAD Lookback
Controls the number of observations used for the rolling median and dispersion estimate.
Shorter values adapt faster.
Longer values create a broader and more stable distribution.
MAD Scale
Multiplier applied directly to raw MAD.
The commonly cited normal-distribution consistency factor is approximately 1.4826; the script default is 1.4655.
Deviation Factor
Controls the final width of the MAD envelope.
ATR Minimum Width
Prevents the active band width from falling below an ATR-derived floor.
ATR Length
Controls the ATR used by the optional floor.
ATR Floor
Controls the minimum width as a multiple of ATR.
Median Slope Confirmation
Requires the rolling median to move in the direction of a proposed trend flip.
Slope Lookback
Controls how far back the current median is compared.
It also influences the visual slope-strength calculation.
Flip Trigger
Selects Close or Source for trail-break detection.
Break Trail On Flips
Creates a visual discontinuity on transition bars.
How this differs from a standard Supertrend
A conventional Supertrend generally uses:
A price midpoint such as HL2.
ATR as the full band-width model.
MAD Volatility Trail instead uses:
Rolling median as its center.
Median Absolute Deviation as its primary width.
ATR only as an optional minimum floor.
The trail mechanics are conceptually related, but the statistical foundation is different.
How this differs from Bollinger Bands
Bollinger Bands normally use:
A moving average.
Standard deviation.
Symmetrical raw bands.
MAD Volatility Trail uses:
Rolling median.
Median Absolute Deviation.
One-sided trailing bands.
Persistent trend-state logic.
Bollinger Bands are primarily a statistical envelope.
MAD Volatility Trail converts its robust statistical envelope into a trend-regime system.
How this differs from median ± MAD alone
A simple median-MAD indicator would plot:
Median.
Median + MAD width.
Median - MAD width.
Those bands would move freely.
This indicator adds:
Ratchet logic.
Persistent bullish/bearish state.
Opposite-trail break conditions.
Optional median-slope confirmation.
Signals and alerts.
The raw statistical model is therefore only the first stage.
MAD versus ATR
ATR measures the size of trading ranges.
MAD measures dispersion of the selected source around its median.
They can behave very differently.
For example:
A volatile but mean-reverting market can have large ATR with relatively controlled median dispersion.
A persistent directional displacement can produce increasing MAD even if individual candle ranges are moderate.
The optional floor allows both concepts to coexist without replacing the MAD foundation.
Robust statistics and financial markets
Financial return and price distributions frequently contain:
Outliers.
Large jumps.
Skew.
Fat tails.
Mean-and-standard-deviation models remain extremely useful, but robust alternatives can provide different information when unusual observations are present.
Median and MAD belong to a family of robust statistical tools designed to reduce sensitivity to extreme sample values.
This does not make the resulting indicator immune to market shocks.
If enough of the rolling window moves, the median and MAD will also move.
The advantage is primarily that one isolated observation has less influence.
Strengths
Uses an exact rolling median.
Uses exact Median Absolute Deviation rather than an approximation.
More resistant to isolated outliers than mean/standard-deviation envelopes.
Provides a configurable MAD scale.
Supports a pure MAD or MAD-plus-ATR hybrid width.
Converts robust statistics into persistent trend boundaries.
Uses one-sided trail logic to reduce rapid regime switching.
Provides optional median-direction confirmation.
Separates signal logic from visual strength.
Includes dynamic gradient, glow and post-flip visualization.
Exposes raw MAD, scaled MAD, active band width and Trend Strength in the Data Window.
Limitations
The indicator is reactive rather than predictive.
Robust statistics do not eliminate whipsaws.
A very short MAD Lookback can still react sharply.
A very long lookback can delay adaptation to new regimes.
Median calculations can remain unchanged across several bars and then move discretely as the rolling sample changes.
Higher Deviation Factors reduce reversals but increase confirmation lag.
The ATR floor changes the model from pure MAD dispersion to a hybrid MAD/ATR structure.
Median Slope Confirmation can reject false breaks but also delay genuine reversals.
Extreme readings in the visual-strength system are not probabilities of continuation.
Glow and bloom are cosmetic and should not be treated as separate signals.
Computational considerations
Unlike many moving averages, the exact rolling median and MAD calculations require the script to build and process the values inside the selected window.
For each bar:
The rolling source sample is collected.
Its median is calculated.
Absolute deviations from that median are calculated.
A second median is calculated from those deviations.
Larger MAD Lookbacks therefore require more work than a simple recursive EMA or ATR calculation.
This is the cost of calculating the robust statistics directly.
Causality and live-bar behaviour
The indicator uses current and historical values without intentional future-looking references.
On completed historical bars, the model is causal.
On a live unfinished bar:
The Source can change.
The current rolling median can change.
MAD can change.
Raw bands can change.
A trail break can appear or disappear.
Users who require confirmed regime changes should evaluate signals at bar close.
Data Window
The indicator exposes four useful diagnostic values.
Raw MAD
The unscaled median absolute deviation.
Scaled MAD
Raw MAD multiplied by the selected MAD Scale.
Active Band Width
The actual band width after:
MAD scaling.
Deviation Factor.
Optional ATR minimum floor.
Trend Strength
The visual-strength score expressed from approximately 0 to 100.
This is calculated from trail distance and median movement.
It is not part of the trend-flip logic.
Alerts
The indicator includes:
MAD Trail Bullish: established bearish regime changes to bullish.
MAD Trail Bearish: established bullish regime changes to bearish.
MAD Trail Flip: either regime transition occurs.
Summary
MAD Volatility Trail builds a trend-following regime from robust statistics.
The calculation begins with an exact rolling median of the selected Source.
Rather than measuring dispersion with standard deviation, the script calculates the Median Absolute Deviation:
MAD = Median(|X - Median(X)|)
The raw MAD is scaled and multiplied by a configurable Deviation Factor to create the statistical width around the rolling median.
The resulting raw upper and lower bands are:
Median + Band Width.
Median - Band Width.
An optional ATR minimum floor prevents these bands from becoming excessively narrow during low-dispersion conditions.
The raw envelope is then transformed into one-sided trailing boundaries.
The Lower Trail can ratchet upward while price remains above it, while the Upper Trail can ratchet downward while price remains below it.
These trails create hysteresis and form the actual regime-switching structure.
A bearish regime turns bullish only when the selected trigger breaks above the opposing Upper Trail, optionally while the rolling median itself is rising.
A bullish regime turns bearish only when the trigger breaks below the Lower Trail, optionally while the median is falling.
The active Lower Trail is displayed during bullish regimes and the active Upper Trail during bearish regimes.
A separate visual-strength model measures price-to-trail distance and median slope relative to the active band width. That score controls gradient and glow intensity but does not alter signals.
The result is a robust alternative to conventional mean-, standard-deviation- and ATR-centered trend trails.
Rather than allowing individual extreme prices to dominate its statistical center and dispersion estimate, MAD Volatility Trail uses the median twice: once to define the center of the distribution and again to define the typical absolute distance from that center.
This creates a trend framework designed around robust location, robust dispersion and persistent trailing structure .
지표

Adaptive T3 Hull [BackQuant]Adaptive T3 Hull
Overview
Adaptive T3 Hull is a configurable trend-following overlay that combines the lag-compensation structure of a Hull-style moving average with T3 smoothing and several optional mechanisms designed specifically to control overshoot, hooks and oscillating tails.
A conventional Hull construction gains responsiveness by comparing a faster and slower smoother, extrapolating their difference, and then smoothing the result again. This can produce a very responsive trend estimate, but the same lag compensation responsible for that responsiveness can also create exaggerated curvature around sharp reversals.
Adaptive T3 Hull makes that trade-off directly controllable.
The indicator replaces the traditional weighted-moving-average Hull stages with T3 smoothers and expands the basic Hull architecture with:
Adjustable fast/slow length relationships.
Adjustable Hull lag compensation.
Configurable final smoothing geometry.
Curvature-sensitive tail damping.
Optional asymmetric damping around turns.
An adaptive T3 volume factor.
An optional ATR-based velocity limiter.
Optional final lag compensation.
Trend-strength-dependent ribbon intensity.
Tail and curvature diagnostics in the Data Window.
The result is not intended to reproduce a standard HMA exactly. It is a generalized Hull-style framework in which the user can explicitly control the balance between responsiveness, smoothness and overshoot.
Core idea
Most trend smoothers face the same fundamental compromise:
More smoothing reduces noise but increases lag.
More lag compensation improves responsiveness but can create overshoot.
The Hull concept addresses lag by comparing a fast smoother with a slower smoother and projecting the difference forward.
A generalized form can be written as:
Hull Raw = Fast + Compensation × (Fast - Slow)
If Compensation is zero:
Hull Raw = Fast
No additional lag compensation is applied.
If Compensation is one:
Hull Raw = 2 × Fast - Slow
This reproduces the familiar compensation structure used in the standard Hull Moving Average.
Values between zero and one provide partial compensation.
Adaptive T3 Hull defaults to a substantially smaller compensation value. This is deliberate. It reduces the tendency for the projected line to extend beyond the fast smoother during sharp changes in direction.
The remaining responsiveness can then be controlled using the fast-length ratio, T3 characteristics and optional final generalization rather than relying entirely on aggressive Hull extrapolation.
Processing chain
The complete indicator can be understood as the following sequence:
Select the source and main Hull Length.
Derive a fast T3 length from the Fast Length Ratio.
Derive a final smoothing length from a configurable power-law relationship.
Calculate fast and slow T3 smoothers.
Measure velocity and curvature of the fast T3.
Normalize curvature using ATR.
Optionally reduce the active T3 Volume Factor during high curvature.
Recalculate the fast and slow T3 legs with the adaptive factor.
Measure the active curvature state.
Optionally reduce Hull compensation when curvature increases.
Construct the compensated fast-minus-slow T3 Hull.
Smooth that result through another T3 stage.
Optionally apply a final generalized lag-compensation stage.
Optionally limit extreme one-bar movement using ATR.
Determine trend from the final line slope.
Build a smoothed one-bar-offset ribbon around the result.
Each stage affects a different part of the lag-versus-overshoot problem.
T3 smoothing
The T3 is a multi-stage recursive smoother constructed from a sequence of exponential moving averages.
The script calculates six EMA stages:
E1 = EMA(Source)
E2 = EMA(E1)
E3 = EMA(E2)
E4 = EMA(E3)
E5 = EMA(E4)
E6 = EMA(E5)
Those stages are then combined using coefficients derived from the T3 Volume Factor.
The final T3 has the general form:
T3 = C1×E6 + C2×E5 + C3×E4 + C4×E3
where C1 through C4 change with the Volume Factor.
This construction allows T3 smoothing to maintain substantial smoothness while using coefficient-based compensation to reduce some of the lag created by repeated EMA filtering.
Important: T3 Volume Factor does not use trading volume
Despite its name, the T3 Volume Factor is not calculated from market volume.
It is a coefficient controlling the internal T3 response.
Changing it does not incorporate:
Exchange volume.
Volume profile.
OBV.
Money flow.
It changes how aggressively the internal EMA stages are combined.
Higher values generally increase compensation and responsiveness, but can also increase overshoot.
Lower values generally produce a more restrained and smoother response.
This relationship is particularly important in this indicator because Hull compensation and T3 compensation can interact.
An aggressive T3 followed by aggressive Hull extrapolation can produce substantially more tail behaviour than either technique alone.
Why combine T3 and Hull logic?
Hull-style smoothing and T3 smoothing approach lag reduction differently.
The Hull architecture uses:
A fast smoother.
A slow smoother.
The difference between them.
A final smoothing stage.
T3 uses:
Multiple recursive EMA stages.
A coefficient-controlled combination of those stages.
Adaptive T3 Hull combines both ideas.
Instead of:
Fast WMA.
Slow WMA.
Final WMA.
the indicator uses:
Fast T3.
Slow T3.
Compensated difference.
Final T3.
This produces a smoother underlying structure while retaining the ability to compensate for lag.
However, combining two lag-reduction mechanisms also makes overshoot control more important. Much of the indicator is therefore devoted to regulating that compensation dynamically.
Hull Length
Hull Length establishes the main smoothing horizon.
It is used to derive:
The slow T3 length.
The fast T3 length.
The final smoothing length.
Lower values:
React more quickly.
Track shorter trend changes.
Increase sensitivity to local curvature.
Can generate more frequent directional flips.
Higher values:
Produce broader trend estimates.
Reduce short-term variation.
Increase response delay.
Generally produce more persistent regimes.
Unlike a standard HMA, the relationship between these three smoothing stages is not fixed.
Fast Length Ratio
The fast T3 length is calculated as:
Fast Length = Hull Length × Fast Length Ratio
with the result rounded to a valid integer.
In a conventional Hull structure, the fast stage normally uses approximately half the main length.
Therefore:
Fast Length Ratio = 0.50
reproduces the familiar half-length relationship.
The default configuration uses a larger ratio, making the fast leg closer in length to the slow leg.
This matters because the difference:
Fast T3 - Slow T3
is the quantity used for lag compensation.
If the fast and slow stages are very different:
Their separation can become larger.
Hull compensation becomes stronger.
The resulting line can react faster.
Overshoot potential increases.
If their lengths are closer:
Their separation becomes smaller.
The compensation term becomes more restrained.
The final line generally becomes smoother.
Fast Length Ratio is therefore another direct control over the aggressiveness of the Hull projection.
Hull Compensation
Hull Compensation controls how much of the fast-versus-slow difference is added back to the fast T3.
The underlying formula is:
Hull Raw = Fast T3 + Effective Compensation × (Fast T3 - Slow T3)
Before adaptive damping is applied, Effective Compensation begins from the Hull Compensation input.
Compensation = 0
The raw line becomes the fast T3 itself.
No Hull-style extrapolation occurs.
Compensation = 1
The calculation becomes:
2 × Fast T3 - Slow T3
which matches the standard Hull lag-compensation form.
Compensation between 0 and 1
Only part of the fast-slow separation is extrapolated.
This creates a middle ground between:
Pure fast smoothing.
Full Hull compensation.
Compensation above 1
The difference is extrapolated even more aggressively than a conventional Hull construction.
This can create a highly responsive line, but it also increases the likelihood of:
Overshoot.
Hooks.
Large tails after sharp turns.
The default is intentionally conservative relative to a standard Hull.
What are Hull tails?
Hull-style moving averages can develop a distinctive oscillating or hooked appearance around strong reversals.
This occurs because the lag-compensation term is effectively extrapolating the difference between two smoothers.
Imagine the fast smoother accelerating upward while the slow smoother is still catching up.
The difference:
Fast - Slow
becomes positive.
Adding that difference to the fast smoother projects the result even further upward.
When price abruptly reverses, the fast smoother begins turning first while the slow smoother remains elevated.
The compensation term can then change rapidly and cause the completed Hull to:
Extend beyond the fast line.
Hook sharply.
Reverse with excessive curvature.
This is not necessarily an error in the Hull formula. It is a consequence of aggressive lag compensation.
Adaptive T3 Hull includes several independent tools for reducing this behaviour.
Final Hull smoothing
After the fast and slow T3 legs are combined, the raw Hull is smoothed again.
The final smoothing length is calculated from:
Length^Hull Smoothing Exponent × Final Smoothing Multiplier
This generalizes the standard Hull square-root stage.
A conventional HMA normally uses approximately:
sqrt(Length)
which is equivalent to:
Length^0.50
before rounding.
Hull Smoothing Exponent
The Hull Smoothing Exponent controls how strongly the final smoothing length grows as the main Hull Length increases.
Exponent = 0.50
Reproduces the square-root relationship used in the conventional Hull construction.
Exponent below 0.50
Produces a shorter final smoothing stage, particularly at larger main lengths.
This generally:
Increases responsiveness.
Allows more of the compensated movement through.
Exponent above 0.50
Creates a longer final smoothing stage.
This generally:
Reduces local variation.
Smooths more aggressively.
Adds response delay.
The script allows this relationship to be generalized instead of forcing the standard square-root rule.
Final Smoothing
Final Smoothing applies an additional multiplier to the derived root length:
Final Length = Length^Exponent × Root Multiplier
This gives a second level of control over the final stage without changing the underlying power-law relationship.
Higher values:
Increase final smoothing.
Reduce local hooks.
Slow the line.
Lower values:
Decrease final smoothing.
Increase responsiveness.
Allow more short-term curvature through.
The Smoothing Exponent controls how smoothing scales with Hull Length.
The Final Smoothing multiplier controls the overall magnitude of that final stage.
Curvature measurement
Adaptive tail damping requires a way to determine when the fast T3 is changing direction unusually quickly.
The indicator first calculates velocity:
Velocity = Fast T3 - Previous Fast T3
Previous velocity is:
Previous Velocity = Previous Fast T3 - Fast T3 two bars ago
Curvature is then approximated as the absolute change in velocity:
Curvature = |Velocity - Previous Velocity|
This is a discrete second-difference concept.
Velocity describes how quickly the smoother is moving.
Curvature describes how quickly that velocity itself is changing.
For example:
A steadily rising line can have positive velocity but low curvature.
A line suddenly flattening after a strong rise can have high curvature.
A sharp reversal can produce very high curvature.
This makes curvature particularly useful for detecting the conditions in which Hull overshoot tends to appear.
ATR normalization
Raw curvature is not directly comparable across instruments.
A $10 curvature movement is enormous for one market and negligible for another.
The script therefore normalizes curvature using ATR:
Normalized Curvature = Curvature / ATR
The result is capped at 1.
This creates an adaptive pressure measure between approximately:
0 = little curvature relative to recent range.
1 = very large curvature relative to recent range.
ATR is calculated using the Damping Normalization length.
This normalized curvature drives several optional adaptive mechanisms.
Damping Normalization
Damping Normalization controls the ATR period used when converting curvature into a relative value.
Short values:
Make the normalization respond rapidly to current volatility.
Allow damping pressure to change quickly.
Longer values:
Create a more stable volatility baseline.
Reduce rapid changes in normalized curvature.
This setting does not smooth the final T3 Hull directly.
It changes how the adaptive systems interpret curvature.
Adaptive Tail Damping
Adaptive Tail Damping dynamically reduces Hull Compensation when curvature becomes large.
The process can be summarized as:
Effective Compensation = Hull Compensation × (1 - Damping Pressure × Damping Strength)
When curvature is low:
Damping Pressure approaches zero.
Effective Compensation remains close to the selected Hull Compensation.
When curvature becomes large:
Damping Pressure increases.
Effective Compensation is reduced.
This means the indicator deliberately removes some of its lag compensation precisely when the fast T3 is bending sharply.
Why reduce compensation during curvature?
Hull compensation is most useful when the fast and slow smoothers are moving consistently in the same directional structure.
During a smooth trend:
The fast line leads the slow line.
Their separation can be used to reduce lag.
During a sharp turn:
The fast line may reverse before the slow line.
Their separation can become a poor estimate of useful forward compensation.
Extrapolating the full difference can create overshoot.
Adaptive damping therefore treats high curvature as a reason to trust the Hull extrapolation less.
Damping Strength
Damping Strength determines how much curvature can reduce Hull compensation.
At zero:
Curvature has no effect on compensation.
As the value increases:
High-curvature events remove progressively more compensation.
The line becomes more restrained around sharp turns.
At a Damping Strength of 1 and maximum normalized curvature, compensation can theoretically be reduced all the way toward zero.
This does not stop the underlying T3 from moving.
It removes the additional Hull extrapolation.
Asymmetric Turn Damping
By default, curvature damping can apply whenever the fast T3 experiences significant curvature.
Asymmetric Turn Damping makes the condition more selective.
When enabled, damping pressure is only applied when the current velocity is moving against the previous directional pace.
Conceptually:
A previously rising fast T3 is damped when its upward velocity begins weakening or reversing.
A previously falling fast T3 is damped when its downward velocity begins weakening or reversing.
This allows strong acceleration in the existing direction to retain more compensation while focusing the damping mechanism around deceleration and turning behaviour.
The purpose is to distinguish:
Curvature caused by trend acceleration.
Curvature caused by trend exhaustion or reversal.
This can preserve responsiveness during strong continuation while still suppressing tails around turns.
Adaptive T3 Volume Factor
Adaptive T3 Volume Factor provides a second curvature-sensitive damping mechanism.
Instead of changing the Hull compensation, this feature changes the internal T3 coefficient itself.
The active factor is approximately:
Active VF = Base VF × (1 - Normalized Curvature × VF Damping Strength)
subject to the configured minimum.
When curvature is low:
Active VF remains near the selected T3 Volume Factor.
When curvature rises:
Active VF is reduced.
The T3 becomes less aggressively compensated.
This attacks overshoot earlier in the processing chain.
Hull damping versus VF damping
The two mechanisms affect different stages.
Adaptive Tail Damping
changes how much:
Fast T3 - Slow T3
is extrapolated.
Adaptive T3 Volume Factor
changes how the T3 smoothers themselves are constructed.
Using both means curvature can reduce:
The aggressiveness of each T3 leg.
The aggressiveness of the Hull compensation between those legs.
This can strongly suppress tails but may also reduce responsiveness.
The controls are therefore optional and independently adjustable.
VF Damping Strength
VF Damping Strength controls how strongly curvature reduces the T3 Volume Factor.
Higher values:
Produce larger reductions during sharp curvature.
Increase smoothing around turns.
Can reduce T3 overshoot more aggressively.
Lower values:
Keep Active VF closer to the base setting.
Preserve more of the original T3 response.
Minimum VF
Minimum VF prevents the adaptive mechanism from reducing the active coefficient indefinitely.
It defines the lower bound used when Adaptive T3 Volume Factor is active.
This keeps the filter within a controlled response range during extreme curvature.
If the selected base Volume Factor is already below the requested minimum, the script does not force it upward above the base value.
Generalize Final Hull
Generalize Final Hull adds another optional lag-compensation stage after the main T3 Hull has already been completed.
A second smoothed version of the completed Hull is calculated.
The final target then becomes:
Hull Target = Hull Base + Generalization × (Hull Base - Second Hull)
This uses the same broad idea as Hull compensation:
Compare a faster estimate with a slower version.
Add part of their difference back to the faster estimate.
At zero Generalization:
The stage has no effect.
As Generalization increases:
The final result becomes more responsive.
Lag is reduced further.
Overshoot potential increases.
This option exists because the earlier tail controls allow the user to reduce aggressive compensation in the main Hull construction and, if desired, reintroduce a smaller amount of controlled responsiveness at the end.
Generalization
Generalization controls the amount of final compensation.
Lower values create subtle lag reduction.
Higher values increasingly extrapolate the difference between the first and second completed Hull smoothers.
This feature should be considered one of the more aggressive responsiveness controls in the indicator.
If the objective is maximum tail suppression, it can be left disabled.
Velocity Limiter
The Velocity Limiter addresses a different problem.
Curvature damping changes how the line is calculated.
The Velocity Limiter places a direct cap on how far the completed line is allowed to move in one bar.
The maximum permitted movement is:
Maximum Step = ATR × Max ATR / Bar
The desired change is:
Delta = Hull Target - Previous T3 Hull
That change is clamped between:
-Maximum Step
+Maximum Step
The final T3 Hull then advances by only the permitted amount.
Why use a velocity limiter?
Occasionally, a large price shock or a combination of aggressive settings can cause the completed Hull target to jump sharply.
The limiter acts as a final mechanical speed limit.
It can reduce:
Single-bar jumps.
Extreme hooks.
Shock-driven movement.
However, this comes with a clear trade-off.
If the market genuinely reprices very quickly, the limiter deliberately prevents the trend line from following the full move immediately.
It therefore introduces controlled lag.
Max ATR / Bar
This setting determines the maximum permitted single-bar movement in ATR units.
For example:
0.35 allows the completed line to move by no more than 0.35 ATR in one bar.
Lower values:
Create stronger movement suppression.
Produce smoother transitions.
Can significantly delay response to genuine breaks.
Higher values:
Interfere less often.
Allow larger legitimate moves.
The limiter is disabled by default because it is a strong constraint.
How the tail controls work together
The script provides several different ways to reduce tail behaviour because overshoot can originate at multiple stages.
Fast Length Ratio
Reduces fast-versus-slow separation.
Hull Compensation
Directly controls extrapolation of that separation.
Final Smoothing
Smooths the compensated output more heavily.
Adaptive Tail Damping
Reduces Hull compensation during curvature.
Asymmetric Turn Damping
Restricts that damping mainly to deceleration and turning behaviour.
Adaptive T3 Volume Factor
Makes the underlying T3 calculations more conservative during curvature.
Velocity Limiter
Caps the final single-bar movement.
Generalization
Moves in the opposite direction by optionally adding some final lag compensation back.
These controls are intentionally modular.
A user does not need to enable all of them.
Default design philosophy
The default settings intentionally do not reproduce a standard Hull Moving Average.
A standard Hull-like configuration would approximately use:
Fast Length Ratio near 0.50.
Hull Compensation near 1.00.
Hull Smoothing Exponent near 0.50.
Final Smoothing near 1.00.
The default Adaptive T3 Hull uses a much more restrained compensation structure.
This shifts the design away from maximum lag cancellation and toward smoother trend tracking with reduced tail behaviour.
The advanced controls then allow users to progressively move the model toward either:
More responsiveness.
More stability.
Trend determination
Trend direction is determined directly from the slope of the completed T3 Hull.
If:
Current T3 Hull > Previous T3 Hull
the direction becomes bullish.
If:
Current T3 Hull < Previous T3 Hull
the direction becomes bearish.
If the line is unchanged:
The previous state persists.
The trend does not depend on price crossing the line.
It depends on whether the adaptive T3 Hull itself is rising or falling.
Long and short signals
A long signal occurs when direction changes into the bullish state.
A short signal occurs when direction changes into the bearish state.
The markers therefore identify:
A change in slope regime.
They do not represent:
Guaranteed entries.
Price targets.
Stop levels.
Because the signal is based on local slope, more responsive configurations will naturally produce more flips during sideways conditions.
Ribbon construction
The optional band is not a conventional upper-and-lower volatility channel.
The main line is the current T3 Hull.
The secondary ribbon reference is calculated from a smoothed version of the previous-bar T3 Hull :
Ribbon Reference = WMA(T3 Hull , Band Smoothing)
The area between these two lines is filled with a gradient.
This creates visual separation between:
The current adaptive trend estimate.
A delayed and smoothed reference to its prior values.
The band therefore functions as a trend ribbon rather than a statistical volatility envelope.
Band Smoothing
Band Smoothing controls the WMA applied to the one-bar-offset Hull series.
Lower values:
Keep the ribbon reference close to the main line.
Produce a tighter band.
Respond quickly to direction changes.
Higher values:
Create a slower reference.
Widen the visual separation during sustained movement.
Create a smoother ribbon.
This input affects the visualization only.
It does not change:
The T3 Hull calculation.
Trend direction.
Signals.
Trend Strength
The indicator also calculates a normalized trend-velocity measure for visualization.
Raw strength is based on:
|Current T3 Hull - Previous T3 Hull| / ATR
and is multiplied by the Strength Sensitivity input.
The result is capped at 1 and then smoothed with an EMA.
This produces a normalized value from approximately:
0 = very little line movement relative to ATR.
1 = strong line movement relative to ATR.
This is a measure of trend-line velocity , not a statistical probability that the trend will continue.
Strength Smoothing
Strength Smoothing controls how quickly the visual strength estimate changes.
Lower values:
React quickly to acceleration and deceleration.
Create faster ribbon-intensity changes.
Higher values:
Produce steadier strength visualization.
Reduce flickering in the gradient.
It does not affect the underlying trend calculation.
Strength Sensitivity
Strength Sensitivity determines how quickly line velocity reaches the maximum normalized strength.
Higher values:
Cause smaller ATR-normalized movement to appear strong.
Increase gradient intensity more easily.
Lower values:
Require greater movement before maximum visual intensity is reached.
Strength-Weighted Gradient
When disabled, the ribbon uses a fixed gradient transparency.
When enabled, gradient intensity changes with Trend Strength.
As the T3 Hull moves more quickly relative to ATR:
The near portion of the ribbon becomes more visible.
The broader gradient becomes stronger.
When trend velocity is weak:
The ribbon becomes more subdued.
This is purely a visualization feature.
It does not alter:
Direction.
Signals.
Smoothing.
Tail damping.
Trend candles
The indicator can recolor the main chart candles according to the active T3 Hull slope state.
Bullish trend = selected Long Color.
Bearish trend = selected Short Color.
The candle colour describes the indicator regime, not the individual candle’s own open-to-close direction.
A bearish candle can therefore remain bullish-coloured while the T3 Hull is still rising.
Tail diagnostics
Several internal values are exposed in TradingView’s Data Window.
These provide insight into how the adaptive model is currently behaving.
Effective Hull Compensation
Shows the compensation actually being used after adaptive tail damping.
If adaptive damping is disabled:
It remains equal to Hull Compensation.
If damping is active:
It falls below the base value when curvature pressure increases.
This is useful for seeing when the indicator is automatically becoming more conservative.
Active T3 Volume Factor
Shows the T3 coefficient currently being used.
If Adaptive T3 Volume Factor is disabled:
It remains equal to the base Volume Factor.
When enabled:
It can decrease during high curvature.
Normalized Curvature
Shows the current curvature estimate after ATR normalization.
Values closer to 1 represent greater changes in fast-T3 velocity relative to recent range.
Trend Strength
Shows the smoothed normalized T3 Hull velocity as a percentage.
This is the same quantity used by the optional Strength-Weighted Gradient.
Tail Overshoot
The script also measures whether the final T3 Hull has extended beyond the fast T3 in the direction of the fast/slow separation.
An upper overshoot occurs when:
Fast T3 is above Slow T3.
Completed T3 Hull is above Fast T3.
A lower overshoot occurs when:
Fast T3 is below Slow T3.
Completed T3 Hull is below Fast T3.
When this happens, Tail Overshoot reports:
|T3 Hull - Fast T3| / ATR
This expresses the size of the overshoot in ATR units.
A value of zero means the completed Hull is not currently beyond the fast T3 under that definition.
This diagnostic is particularly useful when tuning:
Hull Compensation.
Damping Strength.
Fast Length Ratio.
Adaptive VF.
Final Smoothing.
Generalization.
How to interpret the indicator
Rising T3 Hull
A rising line indicates a bullish trend state.
The model’s completed combination of T3 smoothing, Hull compensation and any active damping controls is moving upward.
Falling T3 Hull
A falling line indicates a bearish trend state.
Smooth persistent slope
A stable slope with few direction changes generally indicates a cleaner trend environment for this style of filter.
Frequent colour changes
Rapid bullish/bearish transitions generally indicate:
Sideways price action.
A very responsive configuration.
Insufficient smoothing for the current market.
High normalized curvature
High curvature means the fast T3’s velocity is changing rapidly relative to ATR.
If adaptive controls are enabled, this is where:
Hull compensation may decrease.
T3 Volume Factor may decrease.
High tail overshoot
A larger Tail Overshoot value indicates the completed Hull has moved materially beyond the fast T3.
If the objective is a less tail-heavy line, possible adjustments include:
Reduce Hull Compensation.
Increase Final Smoothing.
Increase Fast Length Ratio.
Increase Damping Strength.
Enable Adaptive T3 Volume Factor.
Reduce or disable Generalization.
Enable the Velocity Limiter.
How to use the indicator
1. Trend regime filter
The most direct use is as a slope-based regime filter:
Rising T3 Hull = bullish trend state.
Falling T3 Hull = bearish trend state.
This can be combined with independent entry logic.
2. Trend transition signals
Long and short markers identify when the adaptive line changes slope direction.
These can be used as:
Regime-change alerts.
Confirmation for another setup.
Potential trailing-exit conditions.
They are not standalone guarantees of a sustained reversal.
3. Pullback reference
During a persistent trend, the T3 Hull can act as a smoothed directional reference.
Price returning toward the line while the line continues to slope in the original direction may represent a pullback within the existing regime.
4. Ribbon expansion
The distance between the current T3 Hull and its delayed WMA reference can visually highlight persistent movement.
A stronger ribbon separation can occur when the current adaptive trend estimate is moving away from its delayed historical reference.
5. Tail tuning
The Data Window diagnostics allow the indicator to be treated as a filter-design tool.
Users can observe:
When compensation is being damped.
How strongly curvature is elevated.
Whether the completed line is overshooting.
How the active T3 coefficient changes.
This can make parameter changes easier to understand than tuning solely by appearance.
Suggested tuning approaches
Smooth / reduced-tail configuration
For a calmer trend line:
Use lower Hull Compensation.
Use a larger Fast Length Ratio.
Increase Final Smoothing.
Enable Adaptive Tail Damping.
Use moderate or higher Damping Strength.
Leave Generalization disabled.
If strong shocks still create large movements:
Enable the Velocity Limiter.
Responsive configuration
For faster behaviour:
Reduce Fast Length Ratio toward the traditional half-length relationship.
Increase Hull Compensation.
Reduce Final Smoothing.
Reduce the Hull Smoothing Exponent.
Use a more aggressive T3 Volume Factor.
These changes generally increase overshoot risk.
Adaptive configuration
For responsiveness in normal conditions with additional protection near turns:
Use moderate Hull Compensation.
Enable Adaptive Tail Damping.
Enable Asymmetric Turn Damping.
Optionally enable Adaptive T3 Volume Factor.
This allows stronger compensation during smooth directional movement while automatically reducing it when the line begins to decelerate or turn.
Maximum tail-control configuration
For very aggressive tail suppression:
Low Hull Compensation.
Higher Final Smoothing.
Adaptive Tail Damping enabled.
Higher Damping Strength.
Adaptive T3 Volume Factor enabled.
Generalization disabled.
Velocity Limiter enabled.
This can create a very stable line, but the cost is additional lag.
How this differs from a standard Hull Moving Average
A conventional HMA normally uses:
WMA at half length.
WMA at full length.
2 × Fast - Slow lag compensation.
Final WMA around sqrt(Length).
Adaptive T3 Hull changes every major part of that architecture:
T3 replaces WMA.
Fast Length Ratio is configurable.
Hull Compensation is configurable.
The final smoothing exponent is configurable.
Final smoothing has an additional multiplier.
Compensation can adapt to curvature.
T3 behaviour can adapt to curvature.
Final movement can be ATR-limited.
An additional generalized compensation stage can be enabled.
It is therefore better understood as a generalized adaptive Hull framework than as a conventional HMA with a different smoothing length.
How this differs from a normal T3
A standard T3 produces one smoothed price estimate from repeated EMA stages and a fixed Volume Factor.
Adaptive T3 Hull uses multiple T3 calculations in a Hull-style structure:
Fast T3.
Slow T3.
Compensated fast-slow projection.
Final T3 smoothing.
It can also dynamically alter the T3 factor according to curvature.
The T3 is therefore a building block inside the larger trend model.
How this differs from simply smoothing an HMA
Applying an additional moving average to an HMA can reduce its tails, but it also adds lag after the overshoot has already occurred.
Adaptive T3 Hull attacks the problem at several earlier stages.
It can:
Reduce the fast-slow separation.
Reduce compensation itself.
Reduce compensation specifically around sharp turns.
Reduce the T3 factor during curvature.
Change the final Hull smoothing geometry.
Limit extreme final movement.
This provides more control than applying one additional smoothing layer to a completed HMA.
Parameter interaction
Many settings interact strongly.
Fast Ratio + Hull Compensation
A low Fast Ratio creates greater separation between fast and slow legs.
Combining that with high Hull Compensation can produce aggressive extrapolation.
Hull Compensation + Adaptive Damping
Hull Compensation defines the maximum starting compensation.
Adaptive damping determines how much of it survives during curvature.
T3 Volume Factor + Hull Compensation
Both can contribute to lag reduction.
High values in both stages may amplify overshoot.
Final Smoothing + Generalization
Final Smoothing adds lag and stability.
Generalization removes some of that lag again.
Using both allows the user to create a smooth base and then selectively reintroduce responsiveness.
Adaptive VF + Adaptive Hull Damping
Both respond to curvature but at different stages.
Enabling both can create strong protection around turns.
Velocity Limiter + all other controls
The Velocity Limiter is applied near the end of the pipeline.
It can therefore override an aggressive target generated by the preceding calculations.
Input guide
Source
Price series used by the complete indicator.
Hull Length
Primary calculation horizon.
T3 Volume Factor
Controls the internal T3 coefficient structure. It does not use trading volume.
Hull Compensation
Controls how much of the fast-minus-slow T3 separation is added to the fast T3.
Final Smoothing
Multiplies the final Hull smoothing length.
Adaptive Tail Damping
Reduces Hull Compensation during high curvature.
Damping Strength
Controls the amount of compensation reduction.
Damping Normalization
ATR horizon used to normalize curvature.
Fast Length Ratio
Controls the fast T3 length relative to the main Hull Length.
Hull Smoothing Exponent
Controls the power-law relationship used to derive the final smoothing length.
Asymmetric Turn Damping
Restricts curvature damping primarily to deceleration and turning behaviour.
Adaptive T3 Volume Factor
Reduces the T3 coefficient during high curvature.
VF Damping Strength
Controls how strongly curvature reduces the active T3 factor.
Minimum VF
Limits how far the adaptive T3 factor can be reduced.
Velocity Limiter
Caps final one-bar T3 Hull movement using ATR.
Max ATR / Bar
Defines the maximum movement allowed by the Velocity Limiter.
Generalize Final Hull
Enables an additional lag-compensation stage after the main T3 Hull.
Generalization
Controls the strength of that final compensation.
Strength-Weighted Gradient
Allows ribbon intensity to vary with normalized T3 Hull velocity.
Strength Smoothing
Smooths the visual trend-strength measure.
Sensitivity
Controls how quickly ATR-normalized movement reaches maximum visual strength.
Band Smoothing
Controls the delayed WMA reference used to build the ribbon.
Strengths
Combines T3 smoothing with a generalized Hull framework.
Directly exposes Hull lag compensation as a user control.
Provides multiple independent methods for reducing oscillating tails.
Uses ATR-normalized curvature for adaptive behaviour.
Can distinguish general curvature from decelerating/turning curvature.
Can adapt the T3 coefficient as well as Hull compensation.
Allows the standard Hull square-root smoothing relationship to be generalized.
Includes an optional ATR-based velocity limiter.
Provides optional final lag compensation for advanced tuning.
Includes real-time tail and curvature diagnostics.
Provides trend-strength-reactive visualization without altering signals.
Limitations
The indicator remains a reactive trend filter rather than a predictive model.
Increasing lag compensation generally increases overshoot risk.
Aggressive tail suppression generally increases lag.
Slope-based signals can whipsaw in ranging markets.
The large number of controls creates many interacting parameter combinations.
Over-tuning parameters to one asset or historical period can reduce robustness elsewhere.
The Velocity Limiter can delay response to genuine price shocks.
Generalization can reintroduce overshoot that earlier damping stages removed.
Trend Strength measures line velocity, not probability of continuation.
Tail Overshoot is a diagnostic relative to the fast T3, not a trading signal.
Causality and real-time behaviour
The calculations use current and historical data without intentional future references.
The indicator can therefore be evaluated causally on completed bars.
However, on a live unfinished candle:
The source can change.
The T3 stages can change.
Curvature can change.
Adaptive compensation can change.
The final slope can change.
A long or short signal can appear or disappear before bar close.
Users requiring confirmed trend transitions should evaluate signals on completed candles.
Alerts
The indicator includes three alert conditions:
T3 Hull Long: the completed T3 Hull changes into a rising trend state.
T3 Hull Short: the completed T3 Hull changes into a falling trend state.
T3 Hull Signal: either directional transition occurs.
Summary
Adaptive T3 Hull is a generalized trend smoother built around the idea that Hull-style lag compensation does not need to be fixed.
The model begins with fast and slow T3 smoothers rather than traditional WMAs. Their difference is used to compensate the fast T3 for lag, but the amount of compensation is directly configurable.
This alone allows the user to move continuously between:
A restrained fast T3.
A partially compensated Hull structure.
A conventional 2×fast-minus-slow construction.
More aggressive extrapolation.
The final smoothing stage is also generalized. Instead of forcing the conventional square-root Hull relationship, the user can control both the smoothing exponent and a separate multiplier.
The adaptive systems then focus specifically on the behaviour that often makes Hull-style smoothers difficult to tune: oscillating tails around sharp turns.
The script measures changes in fast-T3 velocity, normalizes that curvature using ATR, and can use the result to:
Reduce Hull compensation.
Reduce the T3 Volume Factor.
Apply damping only around deceleration and turns.
An optional velocity limiter provides a final ATR-based cap on extreme one-bar movement, while an optional generalized compensation stage can reintroduce controlled responsiveness after the main smoothing process.
The final line determines trend through its slope, while a delayed WMA reference forms the optional ribbon. Ribbon intensity can also respond to normalized trend velocity.
Adaptive T3 Hull is therefore designed less as one fixed moving-average formula and more as a configurable filter architecture for exploring the trade-off between lag, smoothness, responsiveness and overshoot .
Its default configuration intentionally favors a less tail-heavy response than a conventional Hull construction, while the advanced controls allow users to move the model toward either greater responsiveness or stronger damping depending on the behaviour they want from the trend filter.
지표

Black-Litterman Allocator [BackQuant]# Black-Litterman Allocator
IMPORTANT: Concept / Educational Implementation
Black-Litterman Allocator is a research and educational concept that implements a practical version of the Black-Litterman portfolio-allocation framework inside TradingView and Pine Script.
It is intended to demonstrate how equilibrium priors, covariance estimates, subjective investor views, view confidence, mean-variance optimization, portfolio constraints, volatility targeting and portfolio backtesting can be combined into one visual allocation model.
It should not be interpreted as an institutional-grade portfolio optimizer, automated investment product, portfolio recommendation, or guarantee that the resulting allocation is optimal.
The outputs depend heavily on:
The selected asset universe.
The chart timeframe.
The covariance lookback.
The quality and synchronization of TradingView price data.
The chosen prior-weight scheme.
Risk-aversion assumptions.
The investor views entered by the user.
The confidence attached to those views.
Portfolio constraints.
Volatility-target settings.
Transaction-cost assumptions.
The optional regime filter.
The default universe and default views are examples for demonstrating the framework. They are not investment recommendations.
The script is best treated as a portfolio-allocation laboratory : a way to study how changing assumptions about equilibrium, risk, correlations and expected returns can propagate through a Black-Litterman-style allocation process.
Overview
Black-Litterman Allocator is a 15-asset cross-asset portfolio model that starts with a neutral portfolio prior, reverse-engineers the expected returns implied by that prior, optionally incorporates up to five investor views, solves for a new posterior allocation, applies portfolio constraints and volatility targeting, and then simulates the resulting portfolio through time.
The model follows a broad sequence:
Collect return history for the selected 15-asset universe.
Estimate an annualized covariance matrix.
Stabilize that matrix using diagonal covariance shrinkage.
Construct a prior portfolio.
Estimate the market risk-aversion parameter.
Reverse-optimize the prior into implied equilibrium returns.
Convert investor views into the Black-Litterman P, Q and uncertainty structure.
Blend the prior with those views to obtain posterior expected returns.
Optionally calculate posterior covariance.
Solve a mean-variance portfolio from the posterior.
Apply availability, short-selling, gross exposure and position-size constraints.
Target a desired portfolio volatility.
Apply additional leverage and gross-exposure caps.
Rebalance periodically.
Track the resulting equity curve and portfolio statistics.
The script also provides detailed visualizations showing:
Prior versus final active weights.
Equilibrium versus posterior expected returns.
The impact of individual views.
Current gross and net exposure.
Portfolio volatility and scaling.
Turnover.
Portfolio equity versus a benchmark.
Drawdown and daily returns.
A broad set of performance and risk statistics.
Why Black-Litterman exists
Traditional mean-variance optimization has an important practical weakness.
The optimizer is extremely sensitive to expected-return estimates.
Suppose several assets have similar volatility and correlation characteristics, but one asset is assigned an expected return only slightly higher than the others.
A mathematical optimizer can interpret that small difference very aggressively and allocate an unrealistic amount of capital to that asset.
Small estimation errors in expected returns can therefore produce very large changes in portfolio weights.
This is one reason unconstrained mean-variance portfolios often produce allocations that appear unstable or unintuitive.
The Black-Litterman framework was developed by Fischer Black and Robert Litterman as a way of approaching the problem from the opposite direction.
Instead of beginning with a set of independently estimated expected returns, the framework begins with an equilibrium portfolio and asks:
What expected returns would make this portfolio mathematically optimal?
Those implied returns become the prior.
Investor views are then introduced as controlled deviations from that equilibrium rather than replacing the equilibrium assumptions entirely.
This creates a useful distinction:
Prior = what the portfolio implies before the investor expresses a view.
Views = where the investor believes equilibrium is wrong.
Posterior = the combined result after balancing both sources of information.
That is the central idea behind this indicator.
Important distinction: the prior in this script
In textbook Black-Litterman, the equilibrium portfolio is often represented using market-capitalization weights.
This script is intentionally more flexible.
It provides three different prior schemes:
Equal Weight.
Inverse Volatility.
Manual Weights.
For that reason, the word equilibrium should be interpreted carefully.
If Equal Weight or Inverse Volatility is selected, the prior is a user-selected equilibrium proxy , not necessarily the true global market portfolio.
If Manual Weights is selected and the user enters representative market-cap or benchmark weights, the prior can be made closer to the traditional Black-Litterman interpretation.
This flexibility is intentional because TradingView users may want to study Black-Litterman mechanics without first sourcing a complete set of institutional market-cap weights.
Asset universe
The allocator supports fifteen simultaneously selected assets.
The default universe is designed as a broad cross-asset example containing:
Cryptocurrency.
US equities.
International equities.
Precious metals.
Energy.
The US dollar.
Long-duration Treasury exposure.
The default list includes assets such as Bitcoin, Ethereum, Solana, major equity indices, gold, silver, oil, DXY and TLT.
Every symbol can be replaced by the user.
This allows the framework to be adapted to:
Global macro portfolios.
Equity-sector portfolios.
Cryptocurrency portfolios.
ETF portfolios.
Multi-asset portfolios.
However, all assets should represent actual price series .
Market-capitalization series, synthetic quantities or unrelated non-price data should not be inserted as if they were tradable asset prices, because the resulting returns would contaminate the covariance matrix and portfolio calculations.
Data availability protection
A multi-asset allocator has a specific problem when some assets have shorter histories than others.
Suppose fourteen assets have ten years of data but the fifteenth asset was only listed six months ago.
If missing values are simply converted into zeros, the new asset may appear to have:
Almost no volatility.
Artificially stable returns.
Artificial correlations.
This is especially dangerous when using inverse-volatility weighting, because an asset with incorrectly measured near-zero volatility could receive a very large prior allocation.
The script protects against this by maintaining a separate data-availability state for every asset.
An asset is only admitted into the active universe once it has accumulated at least one complete covariance lookback of valid price history.
Until then:
Its active mask remains disabled.
It receives no prior weight.
It receives no optimized weight.
Views referencing it are ignored.
The allocation table displays it as having no usable data.
This makes the universe dynamic.
A newly listed asset can eventually become active once enough genuine history has accumulated.
Return calculations
The allocator uses two forms of return data for different purposes.
Log returns
Log returns are used for covariance estimation:
Log Return = ln(Price / Previous Price)
These are stored in a rolling history matrix.
Simple returns
Simple returns are used when compounding the simulated portfolio:
Simple Return = Price / Previous Price - 1
This distinction is deliberate.
Log returns are convenient for statistical covariance calculations, while simple returns are appropriate for directly multiplying portfolio wealth through time.
Rolling return-history matrix
The script maintains a rolling matrix containing return history for all fifteen assets.
Each row represents a historical bar and each column represents one asset.
Once the requested covariance lookback has been collected, the matrix acts as the input for the covariance engine.
Rather than recalculating years of historical data from scratch on every bar, the script operates the history as a rolling buffer.
The full Black-Litterman calculation is also performed only on rebalance events rather than continuously.
This is important because:
Covariance estimation is computationally expensive.
Matrix multiplication is expensive.
Matrix inversion is expensive.
TradingView imposes execution limits.
The indicator therefore approximates how a real asset-allocation process is normally operated: weights remain relatively stable between scheduled portfolio reviews and are recomputed at discrete intervals.
Covariance matrix
The covariance matrix is one of the central inputs to the entire model.
For N assets, covariance produces an N × N matrix.
The diagonal contains the variance of each asset.
The off-diagonal entries contain covariance between pairs of assets.
Conceptually:
Positive covariance means two assets tend to move in the same direction.
Negative covariance means they tend to move in opposing directions.
Covariance near zero suggests weaker linear co-movement.
The portfolio does not consider the risk of each asset independently.
Instead, portfolio risk depends on:
Individual asset volatility.
Portfolio weights.
The covariance relationships between every pair of assets.
This is why diversification cannot be measured simply by counting positions.
Ten highly correlated assets may behave more like one large risk exposure than ten independent exposures.
Covariance Lookback
The Covariance Lookback controls how many bars are used to estimate the covariance matrix.
Shorter windows:
Adapt more quickly.
Reflect recent correlation changes.
Contain fewer observations.
Produce noisier covariance estimates.
Longer windows:
Provide more observations.
Create more statistically stable estimates.
Adapt more slowly when correlations change.
This parameter is particularly important when the number of assets is large relative to the number of observations.
With fifteen assets, an extremely short covariance window can create a poorly conditioned or nearly singular matrix.
That can make matrix inversion unstable and produce extreme portfolio weights.
Annualization
The covariance matrix is annualized using the Trading Days per Year input.
The script supports:
252 days.
365 days.
252 is generally appropriate for traditional financial markets operating primarily on weekdays.
365 may be more appropriate for a crypto-only daily portfolio.
Mixed universes require judgement because crypto trades continuously while many traditional markets do not.
The annualization setting affects:
Covariance.
Volatility.
Return statistics.
Risk-aversion estimates.
It should therefore be selected consistently with the universe and timeframe being studied.
Covariance shrinkage
Raw sample covariance matrices can be noisy.
This is particularly problematic when:
The lookback is short.
There are many assets.
Several assets are highly correlated.
Market relationships change rapidly.
The script applies a simple fixed-coefficient shrinkage toward a diagonal covariance target.
The diagonal variances are retained.
The off-diagonal covariance terms are multiplied by:
1 - Shrinkage
Therefore:
Shrinkage = 0
leaves the sample covariance relationships largely unchanged.
Shrinkage = 1
removes the off-diagonal covariance terms and effectively treats the assets as uncorrelated for optimization purposes.
Intermediate values partially reduce estimated correlations.
This is best described as Ledoit-Wolf-style diagonal shrinkage , not as a full automatic Ledoit-Wolf estimator.
A true Ledoit-Wolf implementation estimates an optimal shrinkage intensity statistically.
Here, the user directly controls the shrinkage coefficient.
Why shrinkage can help
Portfolio optimization involves matrix inversion.
If covariance estimates are noisy, the inverse matrix can amplify those errors dramatically.
Shrinkage intentionally sacrifices some estimated correlation detail in exchange for greater numerical stability.
A moderate amount of shrinkage can therefore:
Reduce unstable allocations.
Reduce sensitivity to short-term correlation noise.
Improve matrix conditioning.
Too much shrinkage can also remove genuine diversification information.
The parameter is a bias-versus-variance trade-off.
Safe matrix inversion
Black-Litterman requires several matrix inversions.
Matrices can become singular or nearly singular when:
Assets are highly correlated.
Lookbacks are too short.
Data is incomplete.
The script checks whether the matrix is square and sufficiently non-singular before using a standard inverse.
When necessary, it falls back to a pseudo-inverse.
This does not magically make poor data reliable, but it prevents a singular matrix from immediately destroying the calculation.
A pseudo-inverse should still be interpreted cautiously because the underlying portfolio problem may be poorly conditioned.
Prior portfolio
Before Black-Litterman can estimate equilibrium returns, it requires a prior portfolio.
Three schemes are provided.
Equal Weight
Every active asset receives an equal allocation:
Weight = 1 / Number of Active Assets
This is the simplest prior.
It expresses no preference based on:
Market capitalization.
Volatility.
Expected return.
Its strength is simplicity.
Its weakness is that it assumes every asset deserves the same capital allocation regardless of risk.
Inverse Volatility
Inverse Volatility gives greater prior weight to assets with lower historical volatility.
Conceptually:
Raw Weight ∝ 1 / Volatility
The weights are then normalized.
This produces a risk-oriented prior rather than a capital-oriented prior.
Lower-volatility assets receive more weight.
Higher-volatility assets receive less.
This can be useful for diversified macro portfolios, but it has an important implication:
the quietest asset may dominate the prior.
For example, a bond or currency exposure may receive much more prior weight than cryptocurrency simply because its realized volatility is lower.
This is not a bug.
It is the direct consequence of using inverse volatility as the prior definition.
Manual Weights
Manual mode allows the user to enter fifteen raw numbers corresponding to the fifteen selected assets.
The entries are normalized automatically.
This means the values do not need to sum to 100.
The user can enter:
Percentages.
Market capitalizations.
Benchmark weights.
Relative notional values.
Only their proportions matter.
If the intention is to approximate traditional Black-Litterman market equilibrium, Manual Weights can be used to supply actual or approximate market-cap weights.
Reverse optimization
Once the prior weights are known, the model derives the returns that would make those weights consistent with mean-variance equilibrium.
The implied equilibrium excess-return vector is:
Pi = Delta × Sigma × Wprior
where:
Pi = implied equilibrium excess returns.
Delta = risk-aversion coefficient.
Sigma = covariance matrix.
Wprior = prior portfolio weights.
This is called reverse optimization .
Normal portfolio optimization asks:
Given expected returns, what weights should I own?
Reverse optimization asks:
Given the portfolio weights, what expected returns would justify owning them?
That reversal is one of the key ideas behind Black-Litterman.
Why implied returns matter
Expected returns are difficult to estimate directly.
Historical averages are noisy.
Forecast models disagree.
Small errors can create enormous portfolio changes.
Black-Litterman instead begins from a portfolio that the user considers a reasonable neutral starting point.
The model then backs out the expected returns consistent with that portfolio.
These implied returns become the equilibrium prior against which investor opinions are expressed.
Risk aversion: Delta
Delta controls the relationship between expected return and risk.
Higher Delta means:
Greater assumed aversion to risk.
A larger equilibrium return requirement for a given covariance structure and prior.
Lower Delta implies less risk aversion.
The script provides:
Auto (Implied).
Manual.
Manual Delta
Manual mode allows the user to directly select the risk-aversion coefficient.
This is useful when:
A stable assumption is preferred.
The user is reproducing an external Black-Litterman study.
The portfolio prior is known but a particular Delta is desired.
Auto Delta
Auto mode estimates Delta from the current prior portfolio.
The script estimates:
Prior portfolio variance.
An annualized return estimate over the covariance horizon.
The selected risk-free rate.
It then forms an implied risk-aversion estimate from excess return relative to variance.
The value is constrained to a practical range to prevent extreme estimates from destabilizing the optimizer.
This Auto mode is a practical implementation choice for the concept.
It should not be interpreted as a uniquely correct market risk-aversion estimate.
Tau: uncertainty in the prior
Tau is one of the most important Black-Litterman parameters.
It scales uncertainty in the equilibrium prior.
Conceptually:
Prior Uncertainty = Tau × Sigma
A smaller Tau implies stronger confidence in the equilibrium-return prior.
A larger Tau gives the model more freedom to move away from the prior when investor views are introduced.
In practical terms:
Smaller Tau
Makes the prior harder to move.
Reduces the effect of views.
Larger Tau
Increases prior uncertainty.
Allows views to exert more influence.
Tau should not be interpreted in isolation.
Its effect interacts with:
The covariance matrix.
View confidence.
View direction.
The number of views.
Investor views
The script supports up to five simultaneous investor views.
Each view contains:
A view type.
Asset A.
Optional Asset B.
Expected return Q.
Confidence.
Each view can be:
Off.
Absolute.
Relative.
The expected-return input is interpreted as an annualized expected return or annualized relative return .
Absolute views
An absolute view expresses an opinion about one asset.
For example:
“Asset A will return 10% annually.”
In matrix notation, the corresponding row of the P matrix contains:
+1 for Asset A.
0 for all other assets.
Q then contains:
0.10
for a 10% annual view.
Relative views
A relative view expresses one asset relative to another.
For example:
“Asset A will outperform Asset B by 5% annually.”
The corresponding P row contains:
+1 for Asset A.
-1 for Asset B.
0 elsewhere.
Q becomes:
0.05
This does not necessarily mean Asset A itself must return +5%.
It means:
Expected Return A - Expected Return B = 5%
Relative views are one of the most useful features of Black-Litterman because investors are often more confident about relative relationships than exact absolute returns.
It may be easier to hold the view:
“Gold will outperform equities.”
than:
“Gold will return exactly 12.4%.”
P matrix
The P matrix describes which assets each investor view references.
Each row corresponds to one active view.
Each column corresponds to one of the fifteen assets.
An absolute view creates one non-zero exposure.
A relative view creates a long-versus-short pair.
P therefore translates a verbal market opinion into portfolio mathematics.
Q vector
Q contains the expected return associated with each view.
For absolute views:
Q = expected annual asset return.
For relative views:
Q = expected annual outperformance of A relative to B.
The relationship:
P × Returns = Q
defines what the investor believes.
View confidence
Black-Litterman does not require every opinion to be treated as equally reliable.
Each view therefore receives a confidence value.
Confidence controls its uncertainty.
The basic principle is:
Low confidence = large view uncertainty.
High confidence = small view uncertainty.
The script converts intuitive percentage confidence into an Omega uncertainty term using a confidence mapping related to the Idzorek-style approach to expressing subjective confidence. User-specified confidence was developed precisely to make the otherwise difficult view-uncertainty input more interpretable.
Omega
Omega represents uncertainty in the views.
For each active view, the script first measures the variance of the corresponding view portfolio using:
P × TauSigma × P'
It then scales that variance according to confidence:
Omega = ((1 - Confidence) / Confidence) × View Variance
This has intuitive behaviour.
High confidence
If confidence approaches 100%:
(1 - c) / c approaches zero.
Omega becomes small.
The view receives substantial influence.
Low confidence
If confidence approaches zero:
(1 - c) / c becomes very large.
Omega becomes large.
The view has little effect.
The script bounds confidence away from exactly zero and one for numerical stability.
Why confidence matters
Suppose two investors both believe Bitcoin will outperform gold by 10%.
Investor A has 90% confidence.
Investor B has 20% confidence.
Their view Q is identical.
But their portfolio allocations should not necessarily be identical.
The confidence parameter allows the same directional opinion to produce very different posterior tilts.
This is one of the most useful parts of Black-Litterman.
It separates:
What you believe.
How strongly you believe it.
View disagreement: Q - PΠ
The Views table displays:
Q - PΠ
This measures how far the investor view differs from the equilibrium prior.
Suppose equilibrium already implies that Asset A will outperform Asset B by 8%.
If the user enters a relative view of 9%, the disagreement is only 1%.
The posterior may therefore change only slightly.
If the user instead enters 20%, the disagreement with equilibrium is much larger.
The same confidence level will then produce a much larger posterior adjustment.
This quantity is extremely useful because it shows that the impact of a view depends not only on the view itself, but on how different it is from what the prior already expects.
Posterior expected returns
Once P, Q and Omega have been constructed, the script calculates the Black-Litterman posterior expected-return vector.
Conceptually:
Posterior = Prior + Confidence-Weighted Adjustment
The full adjustment depends on:
Tau.
Sigma.
P.
Q.
Omega.
The disagreement Q - PΠ.
The model therefore does not simply overwrite the expected return of the named asset.
The adjustment can propagate across the entire asset universe through covariance relationships.
This is a fundamental feature of Black-Litterman.
If two assets are strongly related, a view about one may alter the posterior expectation of the other even if that second asset was not explicitly named.
Why views propagate
Suppose the user enters a strong bullish view on one equity index.
If several other equity indices are highly correlated with it, the covariance matrix tells the model that those assets are economically related.
The posterior adjustment therefore does not exist in isolation.
This means:
Views influence related assets.
Portfolio effects depend on covariance.
The same view can produce different tilts under different correlation regimes.
That behaviour is intentional.
No active views
If no usable views are active:
Posterior expected returns remain equal to the equilibrium prior returns.
The allocation is then driven by:
The prior.
Covariance.
Risk aversion.
Portfolio constraints.
Volatility targeting.
This makes the script useful even without discretionary views.
It can be used to study how the prior portfolio behaves under the optimization and risk-management layers by itself.
Posterior covariance
The script can optionally include the Black-Litterman posterior covariance adjustment.
Investor views introduce uncertainty about expected returns.
The posterior covariance calculation incorporates additional uncertainty associated with combining the prior and the views.
When enabled, the optimizer uses this adjusted covariance matrix.
When disabled, optimization uses the original covariance estimate.
The practical effect is usually more subtle than changing the expected-return vector, but it can affect:
Position sizes.
Diversification.
Volatility estimates.
View-driven tilts.
Portfolio optimization
After calculating posterior expected returns, the script solves a mean-variance allocation.
The unconstrained portfolio is conceptually:
w* = (Delta × SigmaPosterior)^-1 × PiPosterior
This converts posterior return expectations and covariance into portfolio weights.
If:
There are no views.
The prior and covariance are internally consistent.
No constraints alter the result.
the solution tends toward the prior portfolio.
Views create deviations away from that starting point.
Why unconstrained weights can be extreme
Mean-variance optimization can produce very large positive or negative positions.
This happens because matrix inversion magnifies differences between:
Expected returns.
Volatility.
Correlations.
If two assets are highly correlated but have slightly different expected returns, the optimizer may create a large long position in one and a large short position in the other.
Mathematically this can be valid.
Practically it may be unusable.
The script therefore applies several layers of portfolio constraints after the raw solution.
Data mask
Assets without sufficient price history receive zero weight regardless of what the raw optimizer produces.
This prevents incomplete covariance columns from entering the live portfolio.
Long-only mode
When Allow Short Weights is disabled:
All negative optimizer weights are clipped to zero.
The remaining positive positions are then normalized.
This converts the portfolio into a long-only allocation.
The result is no longer the exact unconstrained analytical Black-Litterman solution.
That is expected.
Real portfolios frequently require constraints that alter the theoretical optimum.
Short-enabled mode
When shorting is enabled, negative posterior weights are permitted.
This allows:
Long-short portfolios.
Relative-value expressions.
Negative allocations to assets receiving sufficiently weak posterior expectations.
Gross exposure becomes especially important in this mode because a portfolio can have low net exposure while still carrying substantial absolute risk.
For example:
+150% long.
-50% short.
= 100% net exposure.
= 200% gross exposure.
Gross Exposure
The Gross Exposure input controls the target sum of absolute portfolio weights before volatility targeting.
Gross exposure is:
Gross = Sum of |Weight|
This differs from net exposure:
Net = Sum of Weight
For long-only portfolios, gross and net are normally similar.
For long-short portfolios, they can differ significantly.
Volatility targeting
After the portfolio has been normalized, the script estimates total portfolio volatility using:
Portfolio Variance = w' × Sigma × w
Portfolio Volatility = sqrt(Portfolio Variance)
This is a full covariance-aware portfolio volatility calculation.
It does not simply average asset volatility.
The model then calculates a volatility scaling factor:
Volatility Scale = Target Volatility / Estimated Portfolio Volatility
subject to minimum and maximum limits.
If estimated portfolio volatility is below target:
Exposure can increase.
If estimated volatility is above target:
Exposure is reduced.
Why portfolio volatility matters
Suppose two assets each have 20% volatility.
A 50/50 portfolio does not necessarily have 20% volatility.
If the assets are weakly correlated, portfolio volatility may be much lower.
If they are highly correlated, it may remain close to 20%.
Using:
sqrt(w'Σw)
allows the volatility target to account for diversification.
Target Volatility
Target Volatility defines the desired annualized risk level of the portfolio before later hard caps are considered.
Examples might conceptually include:
A lower target for a defensive multi-asset portfolio.
A higher target for a crypto-focused portfolio.
The setting is not automatically appropriate simply because the portfolio reaches it.
A volatility target does not account for:
Tail risk.
Liquidity.
Gap risk.
Regime changes.
Nonlinear derivatives.
It is one risk-control dimension.
Maximum volatility-target leverage
A very low-volatility portfolio can theoretically require enormous leverage to reach a high volatility target.
The Max Vol-Target Leverage setting prevents this.
For example, if the mathematical scaling factor is 6× but the maximum leverage is 3×:
The model uses no more than 3×.
This protects against explosive leverage during unusually quiet covariance estimates.
Maximum weight per asset
After volatility targeting, every individual position is subjected to a hard position-size cap.
This ordering is important.
If the position cap were applied before leverage scaling, the volatility scaler could simply increase the capped position again.
Applying the cap afterward ensures the final position magnitude cannot exceed the selected maximum.
For example:
Max Weight = 30%
means no individual position can remain above 30% after the volatility scaling stage.
Maximum gross exposure after volatility targeting
After individual caps are applied, the portfolio is also checked against a maximum total gross exposure.
If gross exposure exceeds that maximum, every position is scaled downward proportionally.
This provides a second portfolio-level safeguard.
The result is a hierarchy:
Generate raw Black-Litterman weights.
Apply long/short rules.
Normalize initial gross exposure.
Apply volatility targeting.
Cap individual positions.
Cap final gross exposure.
Why the target may not be reached
The volatility target is not guaranteed to be achieved exactly.
Suppose the model wants to increase portfolio exposure enough to reach 15% volatility.
If doing so would violate:
Maximum leverage.
Maximum asset weight.
Maximum gross exposure.
the constraints take priority.
The resulting portfolio may therefore have volatility below the requested target.
This is intentional.
Risk limits are allowed to override the target.
Rebalancing
The complete optimizer does not run on every bar.
The user selects a Rebalance Every N Bars interval.
For a daily chart:
Approximately 21 bars corresponds roughly to one trading month.
Longer rebalance intervals:
Reduce turnover.
Reduce computation.
Allow allocations to persist longer.
Shorter intervals:
React faster to new covariance and view conditions.
Increase turnover.
Increase computational load.
The covariance matrix and Black-Litterman solve run only on rebalance events.
Forced rebalances
Two events can trigger a solve outside the normal schedule:
The regime filter changes from CASH back to ACTIVE.
The number of assets with sufficient history changes.
This prevents the portfolio from waiting many bars before responding to a material change in state.
Regime filter
The script includes an optional regime filter based on the chart symbol.
The filter compares:
A fast EMA.
A slow EMA.
When the fast EMA is above the slow EMA:
Regime = ACTIVE
When the fast EMA is not above the slow EMA:
Regime = CASH
This filter applies to the chart symbol , not individually to the fifteen assets.
That distinction is important.
If the indicator is placed on SPX, the regime filter reflects SPX.
If it is placed on Bitcoin, it reflects Bitcoin.
The regime state therefore acts as a global risk-on/risk-off switch for the entire portfolio.
CASH regime
When the regime filter turns off:
The live asset weights are flattened to zero.
The strategy stops compounding asset returns while the regime remains inactive.
When the filter turns ACTIVE again:
A new Black-Litterman solve is forced immediately.
The user should therefore choose the chart symbol intentionally if the regime filter is enabled.
Regime filter limitation
A single chart-symbol EMA regime is an intentionally simple overlay on a much more sophisticated cross-asset model.
It should not be confused with a multi-asset economic-regime model.
It answers only:
Is the fast trend of the chart symbol above its slower trend?
The regime layer can have a very large impact on historical results.
Backtests with and without it are therefore testing materially different systems.
Transaction costs
The script calculates turnover on each committed rebalance:
Turnover = Sum of |New Weight - Previous Weight|
The selected transaction-fee rate is then applied to that turnover.
This is more realistic than assuming rebalancing is free.
However, the cost model remains simplified.
It does not separately model:
Bid-ask spread.
Slippage.
Market impact.
Short borrow fees.
Financing costs.
Taxes.
Different fee schedules by asset.
The fee input should therefore be treated as an approximate portfolio-level trading-cost assumption.
Important backtest implementation note
The current implementation charges transaction fees when a new active portfolio is committed during a rebalance.
The transition that flattens the portfolio when the regime filter enters CASH is not separately charged an explicit turnover fee in the current code.
Therefore, backtests using the regime filter may slightly understate transaction costs associated with risk-off exits.
This is one reason the script should be treated as a concept rather than a production execution simulator.
No-lookahead portfolio return handling
The portfolio return for the current bar is calculated using the weights that were already active before the current rebalance solve.
Only after that return has been calculated does a new set of weights become active.
This prevents the optimizer from using newly calculated current-bar weights to capture a return that occurred before those weights could have existed.
This ordering is essential for a meaningful historical simulation.
Prior versus posterior weight chart
One of the main visual components is the paired horizontal weight chart.
Each asset receives two bars:
Prior weight.
Final active portfolio weight.
The prior represents the selected equilibrium starting allocation.
The active portfolio reflects the portfolio after:
Views.
Optimization.
Short constraints.
Gross normalization.
Volatility targeting.
Position caps.
Final gross caps.
Therefore, the visible gap between the bars represents more than the mathematical Black-Litterman posterior alone.
It represents the complete practical allocation change from prior to final active book .
If the regime filter is currently in CASH, the live active weights may be zero.
This distinction is important when interpreting the chart.
Allocation table
The Allocation Table shows each of the fifteen assets with:
Prior Weight.
Post Weight.
Delta Weight.
Equilibrium Expected Return.
Posterior Expected Return.
Prior Weight
The allocation before investor views and final portfolio construction.
Post Weight
The current active portfolio weight after the complete optimization and risk-control process.
Delta Weight
The difference between the active weight and prior weight.
Positive values indicate the asset has been increased relative to the prior.
Negative values indicate it has been reduced.
Equilibrium E
The implied return derived through reverse optimization.
Posterior E
The expected return after the active investor views have been incorporated.
Comparing equilibrium and posterior expected return is often more informative than looking only at weights.
A return expectation can change substantially while the final weight changes only modestly because:
The asset is highly volatile.
It is highly correlated with another holding.
The maximum-weight constraint binds.
Portfolio volatility limits exposure.
Views table
The Views Table shows each active view and includes:
View description.
Q.
Confidence.
Omega.
Q - PΠ.
This allows the user to inspect not only what the view says, but how strongly it conflicts with equilibrium and how uncertain it is.
Two views with identical Q values may have very different portfolio effects if:
Confidence differs.
Covariance differs.
Equilibrium expectations differ.
Current Book table
The Current Book table provides a compact summary of the active portfolio.
It includes:
ACTIVE or CASH regime.
Prior scheme.
Number of active views.
Number of rebalances.
Gross exposure.
Net exposure.
Number of live assets.
Turnover.
Risk-aversion Delta.
Tau.
Estimated portfolio volatility.
Volatility scaling factor.
This table is useful for diagnosing why the allocator currently looks the way it does.
For example:
Large view changes but small weights
may be explained by a tight volatility target or maximum-weight constraint.
Large gross but low net
may indicate significant long-short exposure.
Few live assets
means part of the universe has not yet accumulated sufficient historical data.
Equity curve
The script maintains a simulated portfolio equity curve beginning from the selected Initial Capital.
Initial Capital affects only the scale of the equity curve.
It does not affect:
Weights.
Sharpe ratio.
Volatility.
Portfolio optimization.
The equity curve compounds the historical portfolio returns generated by the active weights.
The line changes colour according to whether equity increased or decreased from the previous bar.
Benchmark Buy & Hold
A benchmark equity curve can be displayed beside the portfolio.
Both curves begin from the same nominal capital.
The benchmark is also used in:
Beta.
Alpha.
The benchmark can be changed independently from the fifteen-asset universe.
For meaningful interpretation, the benchmark should be relevant to the portfolio being studied.
A broad global macro portfolio compared only with SPX is answering a different question from an equity portfolio compared with SPX.
Daily returns
The script can optionally plot the portfolio’s per-bar percentage return.
This is useful for visually inspecting:
Return clustering.
Large gains.
Large losses.
Regime-filter cash periods.
Because it shares the pane with the equity curve, it is generally best viewed separately.
Rolling drawdown
Drawdown is measured relative to the previous portfolio-equity peak:
Drawdown = (Current Equity - Peak Equity) / Peak Equity
The result is negative while the portfolio remains below its historical high.
The visual fill becomes stronger as drawdown deepens.
The Max DD for Scaling input affects only the visual intensity scale.
It does not limit portfolio losses or modify the allocation.
Performance metrics
The metrics table includes a broad range of return and risk statistics.
Net Profit
Percentage change in portfolio equity from initial capital.
Maximum Drawdown
Largest historical peak-to-trough decline in the simulated portfolio.
Win Rate
Percentage of non-zero portfolio-return bars that were positive.
Flat CASH bars are excluded from the win/loss count.
This prevents periods where the portfolio is deliberately inactive from automatically being classified as losing periods.
Annual Mean Return
Arithmetic average per-bar portfolio return multiplied by the selected annualization factor.
This is not identical to CAGR.
Annual Standard Deviation
Per-bar return standard deviation scaled by the square root of the annualization factor.
Variance
Square of annualized standard deviation.
Sharpe Ratio
Measures annualized excess mean return relative to total return volatility using the selected risk-free rate.
Sortino Ratio
Measures return relative to downside-return variability rather than total volatility.
Omega Ratio
Compares the aggregate positive portfolio returns with the magnitude of aggregate negative portfolio returns.
Gain-to-Pain
Compares net return with the aggregate magnitude of negative returns.
CAGR
Compound annual growth rate based on beginning equity, ending equity and elapsed calendar time.
Calmar Ratio
CAGR divided by absolute maximum drawdown.
Beta
Measures covariance of portfolio returns with benchmark returns relative to benchmark variance.
Alpha
Estimates annualized portfolio return in excess of the return implied by its benchmark Beta and selected risk-free rate.
Skewness
Measures asymmetry of the historical portfolio-return distribution.
Positive skew indicates a longer or heavier positive tail.
Negative skew indicates a more pronounced negative tail.
VaR 95th Percentile
The implementation reports the fifth percentile of historical portfolio returns.
It can be interpreted as the lower-tail return threshold associated with approximately the worst 5% of observations.
It is displayed as a return value rather than converting the loss into a positive number.
Conditional VaR
Conditional VaR averages the returns in the lowest 5% tail.
This provides information about the average severity of outcomes beyond the VaR threshold.
Historical VaR and Conditional VaR rely entirely on the observed backtest sample.
They should not be interpreted as guarantees about future tail losses.
Risk-free rate
The selected Risk-Free Rate influences:
Sharpe.
Alpha.
Auto risk-aversion estimation.
Changing it therefore affects both reported performance statistics and potentially the portfolio itself when Auto Delta is enabled.
Understanding prior versus posterior
The most important conceptual visualization in the script is the difference between the prior and posterior state.
Suppose the prior allocation is:
Asset A: 20%
Asset B: 20%
Asset C: 20%
Asset D: 20%
Asset E: 20%
Now suppose the investor enters:
Asset A will outperform Asset B by 8%, with high confidence.
Black-Litterman does not simply add 8% weight to A and remove 8% from B.
Instead, the model asks:
What did equilibrium already imply about A versus B?
How uncertain is the prior?
How confident is the investor?
What is the covariance of the A-minus-B view?
How are A and B related to the rest of the portfolio?
The resulting posterior return adjustment then passes through the optimizer.
The final weights are subsequently modified by the portfolio constraints.
This explains why Black-Litterman allocations can behave very differently from manually applying arbitrary portfolio tilts.
Example: low-confidence relative view
Suppose equilibrium implies:
Expected A return = 8%
Expected B return = 7%
The equilibrium difference is 1%.
The investor believes:
A will outperform B by 5%
but assigns only 20% confidence.
The view disagrees with equilibrium, but Omega is relatively large because confidence is low.
The posterior therefore moves toward the investor view without fully accepting it.
Example: high-confidence relative view
Using the same equilibrium assumptions, suppose confidence is increased to 90%.
Omega becomes much smaller.
The investor view therefore carries much greater influence.
The posterior A-minus-B expected-return spread moves much closer toward the stated view.
The final weights may then shift significantly, subject to risk and portfolio constraints.
Example: view already priced into equilibrium
Suppose the user believes A will outperform B by 5%.
But the equilibrium prior already implies approximately 5%.
Then:
Q - PΠ ≈ 0
There is little disagreement to resolve.
Even a high-confidence view may produce only a small posterior adjustment.
This is an important property of the model.
Black-Litterman does not reward the user simply for entering a strong opinion.
The opinion must differ from equilibrium before it meaningfully changes the posterior.
Absolute versus relative confidence
Absolute views generally require greater confidence in the expected return level itself.
Relative views can be easier to interpret because the user only needs an opinion about the spread between two assets.
For example:
“Equities will return 14%.”
is a stronger forecasting statement than:
“Equities will outperform bonds by 4%.”
Neither is inherently superior.
The model supports both because portfolio managers frequently express views in both forms.
Why the model is useful conceptually
The value of Black-Litterman is not that it discovers the future.
It provides a disciplined method for converting beliefs into portfolio changes.
Without a framework, an investor may say:
“I like gold.”
“I am bearish equities.”
“Bitcoin should outperform bonds.”
but those statements do not specify:
How much the portfolio should change.
How volatility should affect the position.
How correlated assets should respond.
How conviction should change the allocation.
Black-Litterman forces those opinions into a structured portfolio context.
That is what this indicator is intended to demonstrate.
Important implementation difference from institutional Black-Litterman
The script implements the core Black-Litterman mechanics, but several choices are intentionally simplified for TradingView.
These include:
A fixed maximum universe of fifteen assets.
Up to five investor views.
User-selected fixed covariance shrinkage rather than automatically estimated shrinkage intensity.
Equal-weight and inverse-volatility priors in addition to manual market-style priors.
A simplified Auto Delta estimate.
Discrete bar-based rebalancing.
Simplified transaction costs.
A single chart-symbol regime filter.
Historical covariance from TradingView price data.
These choices make the model practical and interpretable inside Pine Script.
They also mean that results should not be compared directly with a production institutional implementation without understanding the differences.
Mixed-market data considerations
Cross-asset portfolios introduce data-alignment problems.
Cryptocurrency trades continuously.
Equities, commodities and bonds have market sessions and holidays.
Different TradingView symbols may also come from different exchanges or data providers.
The covariance matrix assumes the return observations are meaningfully aligned.
Users should therefore be careful with:
Intraday mixed-asset universes.
Assets from incompatible sessions.
Symbols with limited historical coverage.
Synthetic or non-tradable price series.
Daily or broader timeframes are generally easier to interpret for a macro allocation concept.
Backtest limitations
Historical simulation is useful for understanding behaviour, but this should not be treated as proof of future performance.
The backtest does not model every real-world implementation issue.
Examples include:
Bid-ask spreads.
Market impact.
Execution latency.
Portfolio financing.
Borrow availability.
Short borrow costs.
Taxes.
Different trading sessions.
Rebalancing at exact executable prices.
Changes in instrument availability.
Survivorship effects in a manually selected universe.
The model also uses historical covariance as an estimate of future covariance.
Correlations can change abruptly during stress periods.
The most diversified-looking portfolio based on historical data can become much more concentrated in risk when formerly independent assets begin moving together.
No automatic investment views
The script does not create investor views for the user.
Q and confidence are deliberately manual.
This is important because Black-Litterman is a framework for combining beliefs with equilibrium.
It does not tell the investor what those beliefs should be.
Views could theoretically come from:
Macro analysis.
Valuation models.
Momentum models.
Fundamental research.
Quantitative forecasts.
Discretionary judgement.
The quality of the posterior cannot exceed the quality of the assumptions provided to it.
Parameter interaction
Black-Litterman parameters should not be tuned independently.
Several important interactions exist.
Tau + Confidence
Both influence how aggressively views move the posterior.
Higher prior uncertainty combined with high view confidence can create strong posterior changes.
Covariance Lookback + Shrinkage
A short noisy covariance window may require more shrinkage for stability.
A long sample may tolerate less.
Target Volatility + Leverage Caps
A high volatility target may have little effect if maximum leverage or gross exposure is restrictive.
Views + Max Weight
A strong posterior preference for one asset may never appear fully in the active portfolio if the asset cap is binding.
Shorts + Gross Exposure
Allowing shorts can materially increase gross exposure even when net exposure looks conservative.
Rebalance Frequency + Fees
Frequent optimization allows faster adaptation but increases turnover and assumed trading cost.
Prior selection
The choice of prior is not cosmetic.
It changes the equilibrium return vector itself.
The same investor views can therefore produce different posterior portfolios depending on whether the starting prior is:
Equal Weight.
Inverse Volatility.
Market-like Manual Weights.
Users studying the framework should therefore treat prior construction as one of the primary model assumptions.
Suggested research workflow
A useful way to study the indicator is:
Begin with no investor views.
Choose a prior.
Observe the implied equilibrium returns.
Inspect the covariance-driven allocation.
Add one low-confidence relative view.
Observe Q - PΠ.
Compare equilibrium and posterior returns.
Increase confidence gradually.
Observe how the posterior and weights respond.
Add a second view.
Experiment with Tau.
Enable and disable posterior covariance.
Compare long-only and short-enabled portfolios.
Change the volatility target.
Observe when position or gross caps become binding.
This is generally more informative than immediately entering five aggressive views and trying to interpret the final result.
Example research questions
The allocator can be used to study questions such as:
How much does a 70% confidence view move the portfolio compared with 30% confidence?
How does inverse-volatility equilibrium differ from equal-weight equilibrium?
How does covariance shrinkage change portfolio concentration?
How do relative views propagate into assets not explicitly named?
How much does volatility targeting alter the raw optimizer?
How often do hard position caps bind?
How different are equilibrium expected returns from posterior expected returns?
How much turnover is generated by monthly versus weekly rebalancing?
How does a regime filter alter drawdown and opportunity cost?
These are the types of questions the concept is designed to explore.
Input guide
Initial Capital
Controls the starting dollar value of the simulated equity curve.
It does not change portfolio weights.
Trading Days/Year
Controls annualization.
Use a value consistent with the universe being studied.
Target Volatility
Sets the desired annualized portfolio-volatility target before hard leverage and weight constraints.
Transaction Fees
Approximate fee charged per unit of rebalance turnover.
Rebalance Every N Bars
Controls how frequently the full covariance and Black-Litterman solve occurs.
Allow Short Weights
Allows negative optimized weights.
Max Weight per Asset
Hard cap on individual position magnitude after volatility targeting.
Gross Exposure
Target absolute exposure before volatility scaling.
Max Gross After Vol Target
Final portfolio-level ceiling on gross exposure.
Max Vol-Target Leverage
Maximum scaling multiplier permitted by volatility targeting.
Covariance Lookback
Historical window used for covariance estimation and minimum data availability.
Covariance Shrinkage
Reduces off-diagonal covariance estimates toward zero.
Tau
Controls uncertainty in the equilibrium prior.
Use Posterior Covariance
Allows view uncertainty to modify the covariance matrix used by the optimizer.
Risk Aversion
Selects automatically estimated or manually specified Delta.
Prior Weight Scheme
Selects Equal Weight, Inverse Volatility or Manual Weights.
Investor Views
Supports up to five annualized absolute or relative return views.
Confidence
Controls the uncertainty assigned to each view.
Start Date
Defines the beginning of simulated portfolio equity.
Historical data before the date may still be used to warm up covariance estimates.
Risk-Free Rate
Used in portfolio statistics and Auto Delta estimation.
Benchmark
Used for the buy-and-hold comparison, Alpha and Beta.
Regime Filter
Optional chart-symbol fast/slow EMA filter that moves the portfolio between ACTIVE and CASH.
Prior vs Posterior visualization
Displays the difference between the selected prior allocation and current final portfolio weights.
Strengths
Implements the central Black-Litterman prior-and-views framework directly in Pine.
Supports both absolute and relative investor views.
Allows confidence to directly control view uncertainty.
Uses a complete cross-asset covariance matrix.
Includes diagonal covariance shrinkage.
Supports dynamic asset-data availability.
Provides equal-weight, inverse-volatility and manual priors.
Supports long-only and long-short allocation.
Uses covariance-aware portfolio volatility targeting.
Includes individual and portfolio-level exposure constraints.
Accounts for rebalance turnover fees.
Provides extensive allocation, view and portfolio diagnostics.
Includes a visual prior-versus-final-weight comparison.
Includes portfolio equity, benchmark and risk statistics.
Limitations
This is a concept and educational implementation, not an institutional portfolio-management system.
Historical covariance is only an estimate of future relationships.
The 15-asset universe is fixed in size.
A maximum of five views can be entered.
The prior is only a true market-equilibrium proxy if the selected weights appropriately represent one.
Equal Weight and Inverse Volatility are practical prior substitutes rather than literal global market-cap equilibrium.
The shrinkage coefficient is user-selected rather than statistically estimated.
Auto Delta is a practical approximation.
Portfolio optimization remains sensitive to inputs.
Poor views can produce poor posterior estimates.
High-confidence incorrect views can materially damage the portfolio.
Volatility targeting does not protect against all forms of risk.
Historical volatility can underestimate future crisis volatility.
Hard constraints mean the final portfolio may differ substantially from the analytical unconstrained Black-Litterman optimum.
The final volatility target may not be reached when position, leverage or gross limits bind.
The regime filter is based only on the chart symbol.
The backtest uses simplified transaction costs.
Regime-driven exits to CASH are not separately charged an explicit turnover fee in the current implementation.
Mixed-market TradingView data can contain differing sessions and histories.
Backtested performance does not establish future performance.
Historical and theoretical context
The Black-Litterman framework was developed to address practical problems encountered when applying mean-variance optimization to global portfolios.
Its central contribution is not simply another optimization equation.
It is a different way of constructing expected returns.
Instead of requiring the investor to estimate every asset’s return independently, equilibrium returns provide a coherent starting point. Investor views then alter only the parts of that equilibrium where the investor has an opinion.
This structure can be summarized as:
Start neutral.
Reverse-engineer equilibrium.
State where you disagree.
State how strongly you disagree.
Let covariance propagate those beliefs.
Re-optimize the portfolio.
The original Black-Litterman work emphasized equilibrium as a neutral starting point and allowed investor opinions about absolute or relative performance to tilt that equilibrium according to confidence.
Later work on user-specified confidence made the view-uncertainty problem easier to interpret by expressing conviction in intuitive percentage terms rather than requiring users to manually specify an abstract uncertainty covariance for every view.
This indicator takes those principles and translates them into a practical TradingView research environment.
Summary
Black-Litterman Allocator is an experimental portfolio-allocation framework designed to demonstrate how equilibrium, investor beliefs and portfolio risk can be combined inside TradingView.
The model begins with fifteen selectable assets and estimates their annualized covariance structure using historical log returns. A user-controlled shrinkage process reduces noisy cross-asset covariance estimates, while assets without sufficient historical data are excluded until a complete covariance window becomes available.
The user then selects an Equal Weight, Inverse Volatility or Manual prior portfolio.
That prior is reverse-optimized into implied equilibrium expected returns:
Pi = Delta × Sigma × Prior Weights
Up to five absolute or relative investor views can then be introduced.
Each view specifies:
What the investor expects.
Which assets the view applies to.
How confident the investor is.
Confidence is translated into view uncertainty, allowing weak opinions to create small tilts and high-confidence opinions to exert greater influence.
The Black-Litterman posterior combines those views with equilibrium while accounting for covariance relationships across the entire portfolio.
The resulting posterior expected returns are converted into an optimized allocation, after which the script applies:
Data-availability rules.
Optional long-only constraints.
Gross-exposure normalization.
Portfolio volatility targeting.
Maximum leverage.
Maximum position sizes.
Maximum gross exposure.
The portfolio is then rebalanced through time, transaction costs are approximated, an optional chart-level regime filter can move the book into CASH, and the resulting historical equity curve is compared with a selectable benchmark.
Extensive tables show:
Prior and final weights.
Equilibrium and posterior returns.
View confidence and uncertainty.
View disagreement with equilibrium.
Gross and net exposure.
Portfolio volatility.
Turnover.
Performance and risk statistics.
The purpose of the script is not to claim that Black-Litterman can identify the optimal future portfolio.
Its purpose is to make the framework tangible.
It provides a way to explore how a neutral portfolio can be translated into implied expected returns, how subjective beliefs can be incorporated without completely discarding that prior, how confidence changes the strength of those beliefs, how covariance spreads their effects across the portfolio, and how practical constraints can transform a theoretical posterior into a more realistic active allocation.
Treat the indicator as a concept, a research tool, and a visual implementation of portfolio-allocation theory rather than as an automated investment recommendation.
지표

Nonparametric Relative Momentum [BackQuant]Nonparametric Relative Momentum
Overview
Nonparametric Relative Momentum is a percentile-rank oscillator that measures where the current price or momentum observation sits relative to its own recent empirical history.
Unlike conventional momentum oscillators that transform price using fixed arithmetic relationships, this indicator uses rank statistics . The current observation is compared directly against the previous values in a rolling window and converted into a percentile score from 0 to 100.
The result answers a simple question:
How extreme is the current observation relative to what this market has actually done recently?
Two calculation modes are available:
Price ranks the selected price source directly.
Momentum first measures price change across a configurable horizon, then ranks that momentum against its own recent history.
The oscillator also includes:
Mid-rank handling for tied observations.
Optional output smoothing.
An EMA signal line.
Configurable overbought and oversold zones.
Stepped intensity colouring as the rank becomes more extreme.
Main-chart candle colouring from the 50 midline regime.
Alerts for midline, extreme-zone and signal-line crossings.
Why “nonparametric”?
In statistics, a parametric method generally assumes that data can be described by a particular distribution or by parameters associated with that distribution.
A nonparametric method does not require the same distributional assumption.
Percentile ranks are a classic example.
The oscillator does not need to assume that recent price changes are:
Normally distributed.
Symmetric.
Constant in volatility.
Characterised by a stable mean and standard deviation.
Instead, it works directly from the ordering of the observed data.
If the current momentum observation is greater than almost every momentum observation in the recent window, it receives a high rank.
If it is lower than almost everything observed recently, it receives a low rank.
This makes the oscillator fundamentally relative to the market’s own recent empirical distribution.
Core calculation
The calculation occurs in three stages:
Select the series to rank.
Calculate its empirical percentile rank.
Optionally smooth that rank and calculate a signal average.
The selected ranking target depends on the Rank Target input.
Price Mode
In Price mode:
Target = Selected Price Source
The current source value is compared with the previous values in the Rank Window.
This answers:
Where is current price positioned within its recent price distribution?
A value near 100 means current price is above almost every observation in the comparison window.
A value near 0 means it is below almost every observation.
A value near 50 means it sits near the middle of its recent distribution.
Because Price mode ranks the price level itself, it behaves somewhat like a stochastic or price-position oscillator, although the calculation is based on empirical ranking rather than highest-lowest range normalisation.
Momentum Mode
Momentum mode first calculates:
Momentum = Source - Source
This measures the absolute price change across the selected Momentum Length.
The resulting momentum series is then percentile-ranked over the Rank Window.
The oscillator therefore answers:
How strong is the current momentum observation compared with recent momentum observations?
This is different from asking whether price itself is historically high or low.
For example, price can be near a recent high while momentum has weakened considerably. In that situation:
Price mode may remain highly ranked.
Momentum mode may fall toward the centre or lower half of the distribution.
Conversely, price does not need to be at a long-term extreme for momentum to rank very highly if the current change is unusually strong relative to recent movements.
Why Momentum mode is different from traditional RSI
The standard Relative Strength Index developed by J. Welles Wilder compares smoothed positive and negative price changes.
Its calculation depends on the relative magnitude of average gains and average losses.
Nonparametric Relative Momentum does not use that formula.
Instead:
A momentum observation is calculated.
That observation is ranked against its own historical sample.
For this reason, Momentum mode can be thought of as a rank-based relative momentum oscillator .
Both traditional RSI and this oscillator are bounded between 0 and 100, but the meaning of those values is different.
For example:
RSI = 90
means the balance of smoothed gains versus losses has produced an RSI reading of 90.
Nonparametric Relative Momentum = 90
means the current momentum observation ranks around the upper end of its recent empirical momentum distribution.
That distinction is important.
Percentile rank calculation
For each bar, the indicator compares the current target with every observation in the preceding Rank Window.
It counts:
How many previous values are below the current value.
How many previous values are exactly equal to it.
The percentile rank is then:
Rank = 100 × (Values Below + 0.5 × Equal Values) / Window Length
This produces an oscillator between 0 and 100.
Why use rank instead of magnitude?
Consider two markets.
Market A may normally move only 0.5% over the selected momentum horizon.
Market B may routinely move 5%.
A raw momentum threshold cannot be interpreted the same way for both.
Ranking changes the question.
Instead of asking:
How many points or percent did this market move?
the oscillator asks:
How unusual is this move relative to this market’s own recent behaviour?
This allows the same 0–100 framework to adapt naturally to different price scales and volatility regimes.
Mid-rank treatment of ties
A simple percentile implementation might count only observations strictly below the current value.
That can distort the result when repeated values occur.
This indicator uses mid-rank treatment .
If historical observations equal the current value, each tie contributes one half rather than being classified entirely above or below.
For example, suppose:
40% of observations are below the current value.
20% are exactly equal.
40% are above.
The mid-rank result is:
40 + 0.5 × 20 = 50
This places the tied observation at the centre of its equal-value group.
Mid-ranks are commonly used in rank-based statistics because they provide a more balanced treatment of ties.
Rank Window
The Rank Window determines how much historical data defines the current empirical distribution.
A shorter Rank Window:
Adapts quickly.
Responds strongly to recent regime changes.
Produces more rapid movement between percentiles.
Can create noisier extreme readings.
A longer Rank Window:
Builds the ranking from a larger sample.
Produces a more stable percentile estimate.
Makes extremes harder to reach.
Responds more slowly when market behaviour changes.
The window therefore controls the memory of the oscillator.
It does not smooth the underlying target directly. It changes the reference distribution against which the target is ranked.
Momentum Length
Momentum Length is used only when Rank Target is set to Momentum.
It controls the horizon over which price change is measured:
Momentum = Current Source - Source from Momentum Length bars ago
Shorter values:
Measure faster momentum.
React to shorter impulses.
Change direction more frequently.
Longer values:
Measure broader displacement.
Focus on more persistent movement.
Ignore more short-term fluctuation.
The Momentum Length and Rank Window perform separate roles.
Momentum Length determines what movement is measured.
Rank Window determines the historical sample against which that movement is judged.
Output Smoothing
The raw percentile rank can optionally be passed through an EMA.
A value of 1 leaves the rank effectively unsmoothed.
Higher values:
Reduce rapid rank fluctuations.
Create a smoother oscillator.
Reduce short-lived extreme readings.
Introduce additional lag.
The smoothing occurs after the percentile calculation.
It does not change how observations are ranked.
The 50 midline
The oscillator is centred around 50.
A value above 50 means the current observation ranks above the midpoint of its recent distribution.
A value below 50 means it ranks below the midpoint.
The interpretation depends on the selected mode.
Price mode above 50
Current price is positioned in the upper half of its recent price distribution.
Price mode below 50
Current price is positioned in the lower half.
Momentum mode above 50
Current momentum is stronger than roughly the middle of its recent momentum observations.
Momentum mode below 50
Current momentum is weaker relative to its recent distribution.
The indicator also uses this midline to colour main-chart candles:
Above or equal to 50 = bullish colour.
Below 50 = bearish colour.
This provides a simple relative-regime view on the price chart.
Percentile extremes
Because the oscillator represents rank rather than an unbounded magnitude, readings near 0 and 100 carry a straightforward interpretation.
Near 100
The current observation is greater than almost every value in the recent comparison window.
Near 0
The current observation is lower than almost every value.
These are empirical extremes.
They do not mean price or momentum cannot become more extreme.
A value near 100 can persist while a strong trend continues because new observations may repeatedly remain near the top of the evolving distribution.
Likewise, readings near 0 can persist during sustained downside momentum.
Overbought and Oversold zones
The default static zones are:
Overbought: 90–100
Oversold: 0–10
These are configurable.
The labels “overbought” and “oversold” describe statistical location, not guaranteed reversal conditions.
An overbought reading means:
The ranked observation is near the top of its recent empirical distribution.
An oversold reading means:
It is near the bottom.
During a range, these areas may help identify local extremes.
During a persistent trend, the oscillator can remain in an extreme zone for extended periods.
The zones should therefore be interpreted together with:
Trend context.
Price structure.
Oscillator direction.
Signal-line behaviour.
Why 90/10 instead of 70/30?
Traditional RSI commonly uses 70 and 30.
That convention does not need to apply to a percentile-rank oscillator.
A rank above 90 means the current observation is in approximately the upper tail of the recent empirical sample, while a reading below 10 represents the lower tail.
Using more extreme default zones makes them intentionally selective.
Users who want broader zones can move the boundaries toward values such as 80 and 20.
Signal line
The white Moving Average line is an EMA of the final oscillator:
Signal = EMA(Percentile Rank Oscillator, Signal Length)
This provides a slower reference against which short-term rank movement can be compared.
Oscillator above signal
The percentile rank is strengthening relative to its own recent smoothed level.
Oscillator below signal
The rank is weakening.
Crossovers can be used to identify changes in short-term momentum within the broader percentile regime.
For example:
A bullish crossover below the oversold zone can indicate rank beginning to recover from an extreme.
A bearish crossover above the overbought zone can indicate deterioration from an upper-tail reading.
A crossover near 50 may represent a more neutral momentum transition.
Signal crosses should not be interpreted independently from oscillator location.
Stepped oscillator colouring
The oscillator uses stepped colour intensity based on its position relative to the 50 midline.
Above 50, colours progressively strengthen as the percentile reaches higher levels.
Below 50, bearish intensity progressively strengthens as the percentile falls.
The main regions are approximately:
50–62.5: modest positive rank.
62.5–75: strengthening positive rank.
75–90: strong positive rank.
90–99: upper-tail extreme.
99–100: exceptional upper-tail rank.
The lower half mirrors this concept:
37.5–50: modest negative rank.
25–37.5: weakening relative state.
10–25: strong negative rank.
1–10: lower-tail extreme.
0–1: exceptional lower-tail rank.
These colours do not introduce additional calculations or signals.
They visually communicate how far the oscillator has moved into its empirical distribution.
Column presentation
The percentile oscillator is plotted as columns around a histogram base of 50.
This means:
Values above 50 extend upward.
Values below 50 extend downward from the midline.
Although the numerical scale remains 0–100, this presentation visually emphasises deviation from the centre of the distribution.
The 50 level therefore functions as the oscillator’s equilibrium reference.
Price mode versus Momentum mode
The two modes answer different questions and should not be treated interchangeably.
Price Mode
Asks:
Where is price relative to its recent distribution?
This makes it useful for:
Range position.
Breakout context.
Relative price extremes.
Stochastic-like analysis.
Momentum Mode
Asks:
Where is current price change relative to the recent distribution of price changes?
This makes it useful for:
Momentum expansion.
Momentum exhaustion.
Relative impulse analysis.
Trend-strength transitions.
Momentum mode can identify weakening momentum before price itself leaves the upper part of its distribution.
Price mode can remain elevated simply because the market is still trading near recent highs.
Example: strong uptrend
Suppose price has been rising steadily.
Price Mode may remain above 90 because current price continually sits near the upper edge of its recent range.
Momentum Mode may behave differently:
It can rise toward 100 during acceleration.
Fall back toward 50 when the trend continues at a more ordinary pace.
Drop below 50 if momentum deteriorates significantly even while price remains relatively high.
This distinction can help separate price location from momentum condition .
Example: volatility regime change
Suppose a market normally changes by only small amounts, then suddenly produces a large directional move.
Raw momentum alone shows a large number.
The percentile rank provides additional context by showing whether that movement is unusual relative to the recent distribution.
If the current momentum is greater than nearly every recent observation, the oscillator moves toward 100.
If the market has already experienced many similarly large moves, the same absolute momentum may receive a much less extreme rank.
The indicator therefore adapts automatically to changing empirical behaviour without requiring fixed momentum thresholds.
Midline crossings
A crossover above 50 indicates the ranked series has moved into the upper half of its recent distribution.
A cross below 50 indicates movement into the lower half.
In Momentum mode, these crossings can be used as a simple relative momentum regime:
Above 50 = comparatively stronger momentum state.
Below 50 = comparatively weaker momentum state.
In Price mode, they indicate whether price is above or below the central portion of its recent rank distribution.
These crossings also control the optional main-chart candle colours.
Extreme-zone crossings
The indicator provides alerts when:
The oscillator crosses upward into the overbought zone.
The oscillator crosses downward into the oversold zone.
These alerts identify entry into an extreme percentile area.
They do not indicate that the extreme has ended.
For reversal-oriented analysis, a trader may instead monitor:
A subsequent exit from the zone.
A signal-line crossover.
Divergence with price.
A break in market structure.
Divergence interpretation
Because Momentum mode ranks momentum rather than price, it can also be useful for examining momentum divergence.
For example:
Price may make a higher high while the oscillator produces a lower percentile peak.
This indicates that the latest momentum observation is less exceptional relative to its recent history than it was during the previous price high.
The reverse can occur at lows.
As with conventional divergence, this is evidence of changing momentum characteristics, not confirmation that price must reverse.
How to use the indicator
1. Relative momentum regime
In Momentum mode, use the 50 midline as a simple regime reference:
Above 50 = positive relative momentum state.
Below 50 = negative relative momentum state.
2. Momentum extremes
Use the configurable zones to identify unusually high or low momentum ranks.
Rather than automatically fading these conditions, determine whether the market is:
Trending.
Exhausting.
Breaking out.
Returning toward equilibrium.
3. Signal-line transitions
Oscillator and signal-line crosses can help identify shorter-term changes in rank direction.
The location of the crossover matters.
A bullish crossover at 5 carries different context from one at 95.
4. Price-distribution analysis
Switch to Price mode when the objective is to measure where the current market sits within its recent price distribution.
This can be useful for:
Breakout analysis.
Range positioning.
Relative high/low detection.
5. Trend confirmation
Momentum remaining consistently above 50 can support an existing bullish trend.
Momentum remaining below 50 can support a bearish trend.
Repeated oscillation around 50 indicates that relative momentum is changing sides frequently.
6. Candle regime colouring
The optional overlay candles make the oscillator’s midline state visible directly on the main price chart.
This can be useful when the oscillator pane is being used primarily for extremes and signal-line analysis.
Input guide
Rank Target
Selects what is percentile-ranked.
Price ranks the source itself.
Momentum ranks its change over the selected Momentum Length.
Rank Window
Controls the empirical comparison sample.
Longer values are smoother and statistically broader. Shorter values adapt more quickly.
Momentum Length
Controls the displacement horizon in Momentum mode.
It has no effect in Price mode.
Output Smoothing
Applies optional EMA smoothing to the percentile rank.
1 produces the raw rank.
Signal Length
Controls the EMA signal line.
Shorter values follow the oscillator more closely. Longer values produce slower crossover signals.
Overbought Zone
Sets the lower boundary of the upper extreme area.
Oversold Zone
Sets the upper boundary of the lower extreme area.
How this differs from RSI
Traditional RSI:
Separates gains and losses.
Smooths their magnitude.
Calculates a relative-strength ratio.
Transforms that ratio onto a 0–100 scale.
Nonparametric Relative Momentum:
Calculates price or momentum directly.
Ranks the current observation against historical observations.
Uses no gain/loss ratio.
Uses no assumed distribution.
The identical 0–100 scale therefore represents a different statistical concept.
How this differs from Stochastic
A conventional stochastic oscillator measures where current price lies between the highest high and lowest low of a window.
Its basic concept is:
(Current - Lowest) / (Highest - Lowest)
Nonparametric Price mode instead asks how many historical observations are below the current price.
This distinction matters because the rank considers the entire empirical ordering of the sample, not only its two extreme endpoints.
Two windows can have identical highs, lows and current price but different internal distributions.
A stochastic calculation can return the same value in both cases, while percentile rank can differ because the number of observations above and below the current price is different.
How this differs from a Z-score
A Z-score measures deviation from a mean in standard-deviation units:
Z = (Current Value - Mean) / Standard Deviation
That calculation depends directly on the sample mean and dispersion.
Percentile rank depends only on ordering.
As a result, an extreme outlier can heavily alter a mean and standard deviation but has much less influence on the ordering of the remaining observations.
This is one of the reasons rank statistics can be useful when financial data contains skew, fat tails or isolated extreme moves.
Strengths
Uses a nonparametric empirical ranking process.
Requires no assumption of normality.
Produces an intuitive bounded 0–100 scale.
Adapts naturally to the recent behaviour of each market.
Supports both price-location and momentum-ranking modes.
Uses mid-ranks for tied observations.
Normalises momentum extremes without relying on fixed point or percentage thresholds.
Includes configurable smoothing and signal analysis.
Provides direct midline regime colouring on the main chart.
Limitations
A percentile rank measures relative position, not absolute magnitude.
A reading of 100 does not indicate how much larger the current observation is than the rest of the sample.
Persistent trends can remain at extreme ranks for extended periods.
Short Rank Windows can generate rapid percentile changes.
Long Rank Windows adapt more slowly to regime shifts.
Momentum mode uses absolute source change rather than percentage return, although ranking substantially reduces scale dependence within a single instrument.
Extreme readings are not automatic reversal signals.
Signal-line crosses can whipsaw in noisy conditions.
The oscillator is reactive and does not forecast future price.
Alerts
The indicator provides alerts for:
Cross Up 50: oscillator enters the upper half of its distribution.
Cross Down 50: oscillator enters the lower half.
Overbought: oscillator crosses upward through the selected upper-zone boundary.
Oversold: oscillator crosses downward through the selected lower-zone boundary.
Bull: oscillator crosses above its signal EMA.
Bear: oscillator crosses below its signal EMA.
Summary
Nonparametric Relative Momentum converts either price or momentum into an empirical percentile rank.
Instead of asking how far an observation is from a moving average, how many standard deviations it sits from a mean, or what ratio of gains to losses produced it, the indicator asks where that observation ranks relative to its own recent history.
In Price mode, it measures the relative location of price within its historical distribution.
In Momentum mode, it first calculates price displacement across a chosen horizon and then measures how exceptional that momentum is relative to recent momentum observations.
A mid-rank procedure handles tied values, optional EMA smoothing controls visual responsiveness, and a separate signal average provides crossover analysis. The 50 midline separates the upper and lower halves of the empirical distribution, while configurable overbought and oversold zones highlight the tails.
The result is a distribution-free relative momentum framework that adapts to the observed behaviour of the market rather than relying on fixed magnitude thresholds or an assumed statistical distribution.
지표

Adaptive Trend Ensemble [BackQuant]Adaptive Trend Ensemble
Overview
Adaptive Trend Ensemble is an online-learning trend filter that combines eight different moving-average methods into one continuously weighted trend estimate.
Instead of selecting one moving average permanently, the indicator treats each method as an independent forecasting expert. Every bar, each expert is evaluated according to whether its previous slope correctly anticipated the direction of the latest price move.
Experts that were directionally correct retain more influence. Experts that were wrong lose influence through a multiplicative penalty. The weights are then normalised and used to blend all eight moving-average values into one adaptive ensemble line.
The indicator therefore attempts to answer two separate questions:
Which smoothing method has recently aligned best with price direction?*
How strongly do the weighted methods currently agree on the direction of trend?
The final output includes:
A dynamically weighted ensemble trend line.
Bullish and bearish trend-state colouring.
A gradient between price and the ensemble.
A consensus-driven glow.
Trend-coloured candles.
A live label showing the leading expert and its current weight.
Alerts when the ensemble trend changes direction.
This is not a fixed moving average and it is not a simple average of several indicators. The contribution of each expert changes over time according to its recent directional performance.
Core idea
Moving averages respond differently to the same market.
A Hull Moving Average may respond quickly during a sharp transition, while an RMA may remain stable through temporary noise. A linear-regression estimate may follow a smooth directional move well, while a conventional EMA may perform better during a more ordinary trend.
No individual smoothing method is consistently superior across every environment.
Markets alternate between:
Persistent trends.
Fast breakouts.
Slow directional drift.
Volatile reversals.
Compressed ranges.
Noisy transitions.
A fixed indicator cannot change its mathematical personality when the environment changes. It continues using the same weighting structure regardless of whether that structure currently suits the market.
Adaptive Trend Ensemble addresses this by maintaining a bank of different smoothing methods and changing their influence through time.
The model does not attempt to decide in advance which method is best. It allows recent realised price action to determine which experts should currently receive more weight.
Prediction with expert advice
The indicator is based on a class of online-learning methods commonly described as:
Prediction with Expert Advice
In this framework:
Several experts produce predictions.
The actual outcome is observed.
Each expert receives a loss based on its prediction.
Expert weights are updated.
The combined model places more influence on better-performing experts.
The term “expert” does not imply that each method is intelligent by itself. An expert is simply an individual forecasting rule.
In this indicator, the eight experts are eight moving-average methods.
The model uses a multiplicative-weights process closely related to the Hedge and Weighted Majority families of online-learning algorithms.
The central principle is:
Do not commit permanently to one model.
Track several models simultaneously.
Reduce the weight of models that make mistakes.
Allow the combined forecast to adapt as relative performance changes.
Online learning
The model learns sequentially, one bar at a time.
It does not train on a separate historical dataset and then freeze its parameters.
At each new bar:
The previous slope of each moving average is treated as that expert's prediction.
The realised close-to-close direction is observed.
Each expert receives a loss.
Weights are updated multiplicatively.
Weights are normalised.
The current expert values are blended using the new weights.
This makes the process online and adaptive.
The weight state is carried forward from bar to bar, meaning the current ensemble reflects the accumulated results of earlier expert decisions.
The expert bank
The ensemble contains eight moving-average experts:
Simple Moving Average - SMA*
Exponential Moving Average - EMA
Weighted Moving Average - WMA*
Hull Moving Average - HMA
Double Exponential Moving Average - DEMA*
Running Moving Average - RMA
Arnaud Legoux Moving Average - ALMA*
Least-Squares Moving Average - LSMA
All experts use the same Base Length.
This is important because it keeps their nominal observation horizon comparable. The ensemble is comparing different mathematical treatments of approximately the same lookback rather than comparing completely unrelated time horizons.
Even with an identical length, the experts behave differently because they assign weight to historical observations in different ways.
Simple Moving Average - SMA
The SMA applies equal weight to every observation inside the selected window.
Its general form is:
SMA = Sum of observations / Number of observations
The SMA is stable and easy to interpret, but every included observation has the same importance.
This can make it slower to react when a new trend begins because older prices continue to influence the average until they leave the window.
Within the ensemble, the SMA acts as a neutral equal-weight baseline.
Exponential Moving Average - EMA
The EMA assigns progressively greater weight to recent observations.
Its recursive form is based on:
EMA = α × Current Price + (1 - α) × Previous EMA
where α is determined by the selected length.
Compared with an SMA of the same length, an EMA generally responds more quickly to recent movement.
Its recursive weighting makes it useful during ordinary directional markets, although it can still turn repeatedly when price oscillates in a range.
Weighted Moving Average - WMA
The WMA assigns linearly increasing weight to more recent observations.
For example, in a simplified four-period WMA, the newest value receives four units of weight, while the oldest receives one.
This makes the WMA more responsive than an equal-weight SMA while retaining a finite lookback window.
Within the ensemble, it provides a direct recency-weighted alternative to the exponential behaviour of the EMA.
Hull Moving Average - HMA
The Hull Moving Average was designed to reduce lag while preserving a relatively smooth output.
Its construction combines weighted moving averages over different horizons, applies a lag-compensation step, and then smooths the result over approximately the square root of the original length.
Conceptually:
Calculate a faster WMA.
Calculate a slower WMA.
Use their difference to compensate for lag.
Smooth the compensated result.
The HMA often reacts quickly to changes in trend direction.
That responsiveness can make it valuable during strong transitions, but it may also make it more sensitive to short-term oscillation.
Double Exponential Moving Average - DEMA
Despite its name, DEMA is not simply an EMA calculated twice.
Its general construction is:
DEMA = 2 × EMA - EMA of EMA
The second EMA estimates some of the lag in the first EMA. Subtracting it attempts to create a smoother with less delay.
DEMA can respond quickly to directional changes, although reduced lag may also increase sensitivity during unstable conditions.
Running Moving Average - RMA
RMA is commonly associated with Wilder-style smoothing.
It uses a slower recursive update than a typical EMA of the same nominal length.
Its general form places substantial influence on the previous RMA value, producing a persistent and stable estimate.
The RMA expert often changes direction less aggressively than the faster methods.
Within the ensemble, it acts as one of the more conservative smoothing models.
Arnaud Legoux Moving Average - ALMA
ALMA applies a Gaussian-style weighting curve across the observation window.
The weighting distribution can be shifted toward more recent observations while maintaining a smooth bell-shaped profile.
The script uses a recent-weighted offset and a fixed Gaussian width.
ALMA attempts to balance:
Smoothness.
Reduced lag.
Controlled weighting of the observation window.
It provides a different weighting structure from the linear, exponential and lag-compensated experts.
Least-Squares Moving Average - LSMA
The LSMA is based on linear regression.
Instead of averaging historical prices directly, it fits a straight line through the selected window and evaluates the regression estimate at the current bar.
The method attempts to represent the local directional path of price.
LSMA can follow smooth trends closely because it models slope explicitly. However, it may respond strongly when the local regression direction changes abruptly.
Within the indicator, the LSMA is produced using the rolling linear-regression output.
Base Length
The Base Length is shared by all eight experts.
Lower values:
Make every expert more responsive.
Increase sensitivity to short-term changes.
Produce faster weight and trend changes.
Increase the possibility of whipsaws.
Higher values:
Create smoother expert outputs.
Focus the ensemble on broader trend structure.
Reduce short-term changes.
Increase lag during sudden reversals.
Because all experts share the same length, changing this setting adjusts the entire ensemble horizon.
It does not change the number of experts or their relative starting weights.
Expert predictions
The model evaluates each expert using the direction of its slope.
For each moving average:
Rising slope is represented as +1.
Falling or non-rising slope is represented as -1.
To evaluate the latest completed move, the script uses the expert's slope from the previous bar.
For example:
If the expert was rising from two bars ago to the previous bar, it predicted a positive current move.
If the expert was falling, it predicted a negative current move.
The realised outcome is determined from the current close relative to the previous close:
Close above previous close = positive realised direction.
Close below previous close = negative realised direction.
Unchanged close = zero realised direction.
The model therefore scores directional slope prediction, not the numerical distance between each moving average and price.
An expert is rewarded for getting direction right, even if its plotted value is relatively far from the market.
Likewise, an expert is penalised for getting direction wrong even if its line remains visually close to price.
Loss functions
The indicator provides two loss functions:
Directional 0/1*
Magnitude-weighted
The selected loss determines how strongly incorrect experts are penalised.
Correct experts receive zero loss under both modes.
Directional 0/1 loss
Directional mode treats every incorrect prediction equally.
The loss is:
0 when the expert predicted the realised direction correctly.
1 when the expert predicted incorrectly.
This means that an incorrect prediction on a very small move receives the same loss as an incorrect prediction on a large move.
Directional mode answers a simple question:
Was the expert right or wrong?
It does not consider how important the move was.
This mode can produce consistent learning because every directional observation is treated equally, but it may respond to small and insignificant price changes as strongly as major moves.
Magnitude-weighted loss
Magnitude-weighted mode scales the penalty according to the size of the realised move.
The move is normalised using ATR:
Move = Absolute close-to-close change / ATR
The ATR uses the shared Base Length.
The incorrect expert's loss becomes:
Loss = Normalised Move
with the magnitude capped at 3.
The cap prevents a single extreme bar from creating an unlimited penalty.
This mode gives greater importance to mistakes during large movements.
For example:
An incorrect expert during a 0.10 ATR move receives a small penalty.
An incorrect expert during a 1.00 ATR move receives a larger penalty.
An incorrect expert during a move above 3 ATR receives the capped penalty of 3.
Magnitude-weighted mode answers:
How costly was the directional mistake relative to current volatility?
This can make the ensemble adapt more strongly after significant movements while paying less attention to small fluctuations.
Flat price bars
If the current close is unchanged from the previous close, the realised direction is zero.
Because expert directions are encoded as either positive or negative, no expert can exactly match a zero realised direction.
Under Directional mode, all experts receive the same incorrect classification.
Because every weight is multiplied by the same penalty factor, their relative weight distribution remains effectively unchanged after normalisation.
Under Magnitude-weighted mode, the realised move is zero, so the resulting penalty is also zero.
In both cases, a completely flat close-to-close bar does not materially change the relative ranking of the experts.
Multiplicative weight update
Each expert begins with an equal weight:
Initial Weight = 1 / 8
After the loss is calculated, the weight is updated using:
New Unnormalised Weight = Old Weight × exp(-η × Loss)
where η is the Learning Rate.
This is the central Hedge or multiplicative-weights update.
Correct experts have zero loss:
exp(-η × 0) = 1
Their unnormalised weight is unchanged.
Incorrect experts have a positive loss, so their weight is multiplied by a value below one.
For example, in Directional mode with a Learning Rate of 2:
Incorrect Weight Multiplier = exp(-2) ≈ 0.135
An incorrect expert retains only about 13.5% of its previous unnormalised weight before the weight set is normalised again.
This does not mean its final displayed weight will necessarily fall by exactly 86.5%, because all expert weights are subsequently rescaled so they sum to one.
Why multiplicative updates are used
An additive system might subtract a fixed quantity from each incorrect expert.
That can create problems:
Weights can become negative.
The same penalty has a different effect on large and small weights.
The model may not adapt proportionally.
A multiplicative update preserves non-negative weights and penalises experts proportionally to their current influence.
It also allows the distribution to become concentrated around consistently successful methods.
Learning Rate - η
The Learning Rate controls how aggressively the ensemble shifts weight after mistakes.
Higher values:
Penalise incorrect experts more strongly.
Move influence rapidly toward recent winners.
Can produce winner-take-all behaviour.
Can make the leader change abruptly after a few important bars.
Lower values:
Produce gradual weight changes.
Keep the expert distribution more diversified.
Reduce sensitivity to short-term performance.
Make the model slower to adapt.
The Learning Rate does not change the moving averages themselves. It changes only how quickly their relative influence evolves.
High Learning Rate behaviour
At high settings, a wrong expert may lose most of its weight after one or two mistakes.
This can be beneficial when one smoothing method is clearly better suited to the current regime.
It can also create instability:
A recent winner can dominate the ensemble.
A temporary performance streak can cause excessive concentration.
The model can switch leaders quickly when conditions reverse.
Low Learning Rate behaviour
At low settings, the ensemble behaves more like a slowly adapting average of the expert bank.
No single observation dramatically changes the distribution.
This produces smoother adaptation, but a poorly suited expert may retain substantial influence for longer.
Weight normalisation
After all expert weights are updated, they are normalised:
Normalised Weight = Expert Weight / Sum of All Expert Weights
This ensures that the complete weight set sums to one.
The weights can then be interpreted as each expert's share of the ensemble.
For example:
A 25% weight means that expert contributes one quarter of the weighted output.
A 5% weight means its current influence is relatively small.
The weights are not probabilities that the experts will be correct on the next bar.
They are adaptive influence coefficients based on accumulated relative loss.
Weight Floor
The optional Weight Floor preserves a minimum allocation for every expert.
After normalisation, the adjusted weight is calculated so that:
Every expert receives at least the selected floor.
The remaining weight is distributed according to the normalised Hedge weights.
The full set continues to sum to one.
For eight experts, a floor of 0.01 reserves at least 1% for each expert.
This assigns:
A minimum combined mass of 8%.
The remaining 92% according to relative performance.
A floor of 0.05 reserves at least 5% for each of the eight experts, using 40% of the total distribution as minimum allocations.
The remaining 60% is distributed according to current performance.
Why use a floor?
Without a floor, repeatedly incorrect experts can approach a weight extremely close to zero.
Because the update only reduces weights after losses, an expert with almost no weight may require a long period of relative outperformance before it becomes influential again.
A positive floor keeps all methods alive.
This allows an expert that performed poorly in the previous regime to recover more quickly when the market environment changes.
Weight Floor set to zero
With a zero floor:
The model is free to concentrate almost entirely in one expert.
Recent winners can dominate strongly.
The ensemble can become highly specialised.
This produces the purest multiplicative-weights behaviour but increases the risk of weight collapse.
Positive Weight Floor
With a positive floor:
The expert bank remains diversified.
Cold experts retain some influence.
The model can recover more easily after regime changes.
The leading expert's maximum possible weight is reduced.
The floor therefore controls the balance between specialisation and diversity.
Ensemble output
After the weight update, the current values of the eight experts are blended:
Ensemble = Sum of Expert Weight × Expert Value
This is a weighted average in which the weights are determined by online directional performance.
If the HMA currently has the greatest weight, the ensemble will behave more like the HMA.
If the RMA and SMA dominate, the output will become smoother and more conservative.
If the weights are distributed evenly, the line represents a broad blend of all eight methods.
The output can therefore change its effective smoothing behaviour without changing the user-selected Base Length.
Line Smoothing
The weighted ensemble may be passed through an optional EMA for visual smoothing.
A setting of 1 effectively disables this additional stage.
Higher settings:
Create a smoother displayed line.
Reduce small slope changes.
Delay bullish and bearish flips.
This smoothing is cosmetic in the sense that it occurs after the online expert weighting.
It does not affect:
Expert predictions.
Expert losses.
Weight updates.
Consensus.
Leader selection.
It does affect the final plotted line and the trend state derived from that line.
Trend state
Trend direction is determined from the slope of the smoothed ensemble line.
If the line is above its previous value, trend becomes bullish.
If the line is below its previous value, trend becomes bearish.
If the line is unchanged, the previous trend persists.
This creates a persistent two-state regime.
A bullish flip occurs when the trend changes from bearish to bullish.
A bearish flip occurs when it changes from bullish to bearish.
The trend state is based on the ensemble's slope, not on price crossing the ensemble.
Price may be above or below the line without immediately changing its direction.
Consensus calculation
The indicator calculates a separate weighted directional vote.
Each expert's current slope direction is multiplied by its current weight:
Weighted Vote = Sum of Weight × Direction
Because each direction is either +1 or -1 and the weights sum to one, the vote lies between -1 and +1.
Examples:
+1 means all meaningful weight is assigned to rising experts.
-1 means all meaningful weight is assigned to falling experts.
0 means bullish and bearish weighted influence is evenly balanced.
The displayed consensus strength is:
Consensus Strength = Absolute Value of Weighted Vote
This converts the result to a range from zero to one.
0% means the weighted expert bank is evenly divided.
100% means the weighted influence is entirely aligned in one direction.
Weighted consensus versus expert count
Consensus is not calculated by simply counting how many of the eight experts are rising.
An expert with a 40% weight contributes more than one with a 2% weight.
For example:
Five low-weight experts may be bullish.
Three high-weight experts may be bearish.
The final weighted vote can still be bearish.
This means consensus measures the agreement of the current weighted model, not the raw number of methods on each side.
With a zero Weight Floor, consensus may become very high when one expert dominates, even if several near-zero-weight experts disagree.
With a positive floor, disagreement from the remaining experts has more influence on the consensus value.
Consensus is not confidence
The consensus percentage should not be interpreted as a probability that the trend will continue.
It measures only the current alignment of weighted expert slopes.
High consensus means:
The influential experts point in the same direction.
It does not guarantee:
Future price continuation.
A profitable entry.
Low reversal risk.
Strong agreement can occur late in a mature trend as well as early in a new one.
Leading method
The live information label identifies the expert with the highest current weight.
It displays:
The expert name.
Its current percentage weight.
The weighted consensus strength.
The current ensemble direction.
For example:
Leading: HMA (34.5%)*
Consensus: 78% ▲
This means the HMA currently has the largest share of the ensemble and the weighted expert bank is strongly aligned upward.
The leader percentage is not a win probability.
It is only the experts share of the current normalised weight distribution.
Leader changes
The leading method can change when:
The current leader makes directional mistakes.
Another expert remains correct while competitors are penalised.
A large magnitude-weighted move strongly changes relative weights.
The market transitions into a regime better suited to another smoother.
Leader changes can help reveal how the ensemble is adapting.
For example:
A shift toward HMA or DEMA may reflect stronger preference for responsive methods.
A shift toward SMA or RMA may reflect better recent performance from slower methods.
A shift toward LSMA may occur during a smooth local directional path.
These interpretations are contextual and should not be treated as fixed rules.
Gradient fill
The indicator fills the area between price and the ensemble line.
When price is above the line:
A bullish gradient is displayed.
When price is below the line:
A bearish gradient is displayed.
The gradient visually separates price from the adaptive trend estimate.
The fill reflects price location, while the line colour reflects the slope-derived ensemble trend.
These can temporarily disagree.
For example:
Price may fall below a still-rising ensemble during a pullback.
Price may rise above a still-falling ensemble during a counter-trend rally.
This disagreement can provide useful context.
Consensus glow
A glow is drawn around the ensemble line.
Its brightness changes according to weighted consensus.
When consensus is high:
The glow becomes brighter and more visible.
When the experts are divided:
The glow becomes more transparent.
The glow width is scaled using ATR based on the Base Length, helping the effect remain proportional across instruments and volatility environments.
The glow is a visual representation of model agreement. It does not modify the line or trend calculation.
Candle colouring
Candles can be coloured according to the current ensemble trend:
Bullish trend uses the selected bullish colour.
Bearish trend uses the selected bearish colour.
Candle colouring is based on the direction of the ensemble line, not the direction of each individual candle.
A bearish candle can therefore remain green during a bullish ensemble regime, and a bullish candle can remain red during a bearish regime.
How to interpret the indicator
Bullish ensemble trend
A bullish state means the final ensemble line is rising.
This indicates that the current weighted combination of experts is moving upward.
It does not require all individual experts to be bullish.
Bearish ensemble trend
A bearish state means the final ensemble line is falling.
The weighted combination is moving downward, even if one or more individual experts remain bullish.
High bullish consensus
A strongly positive vote means most influential expert weight is assigned to rising methods.
This can indicate broad directional alignment.
High bearish consensus
A strongly negative vote means the influential experts are predominantly falling.
Low consensus
A consensus near zero means weighted expert directions are divided.
This can occur during:
Trend transitions.
Sideways ranges.
Pullbacks.
Disagreement between faster and slower methods.
Low consensus does not automatically mean price will remain sideways. It means the ensemble's components are not currently aligned.
High leader weight and high consensus
This indicates that:
One method currently dominates.
The broader weighted bank is aligned with it.
The model is highly concentrated and directionally unified.
This can produce a responsive and decisive ensemble, but it also means the output depends heavily on the current leader.
Distributed weights and high consensus
This means several experts maintain meaningful weights while pointing in the same direction.
The trend is supported by a more diversified group of methods.
Leader weight high but consensus low
This can occur when the dominant expert points one way while several remaining experts point the other way.
The ensemble may still follow the leader, but internal disagreement is present.
How to use the indicator
1. Trend regime filter
Use the ensemble slope as directional context:
Prioritise long setups during bullish regimes.
Prioritise short setups during bearish regimes.
The indicator does not define entry price, stop placement or profit targets.
2. Consensus filter
A user may require stronger consensus before acting on the trend state.
For example:
A bullish flip with low consensus may represent an early or uncertain transition.
A bullish regime with high consensus indicates broader weighted alignment.
No universal consensus threshold is appropriate for every market.
3. Pullback analysis
During a bullish ensemble regime:
Price moving toward or below the line may represent a pullback.
The ensemble remaining bullish suggests its trend estimate has not yet reversed.
During a bearish regime:
Price moving toward or above the line may represent a counter-trend rally.
Price interaction with the line should be combined with structure and risk management.
4. Regime adaptation observation
The Leading Method label can be used to study how different smoothers perform through changing environments.
Rather than assuming one moving average is always best, the user can observe:
Which expert gains weight during trends.
Which expert takes over during transitions.
How concentrated the model becomes.
How quickly weights change under different Learning Rates.
5. Bullish and bearish flips
Trend flips can be used as:
Regime-change alerts.
Confirmation for another setup.
Potential exit conditions.
A directional filter for discretionary trades.
Because flips are based on line slope, responsive settings can generate repeated changes during ranges.
Suggested configurations
Balanced adaptive configuration
Moderate Base Length.
Moderate Learning Rate.
Directional loss.
Small positive Weight Floor.
Minimal Line Smoothing.
This keeps the model adaptive while preserving some expert diversity.
Fast adaptation configuration
Shorter Base Length.
Higher Learning Rate.
Magnitude-weighted loss.
Zero or very small Weight Floor.
Line Smoothing of 1 or 2.
This allows rapid concentration around recent winners but can create unstable leader changes.
Conservative diversified configuration
Longer Base Length.
Lower Learning Rate.
Directional loss.
Positive Weight Floor.
Additional Line Smoothing.
This creates slower and more diversified adaptation.
Large-move-focused configuration
Magnitude-weighted loss can be used when mistakes during large ATR-normalised moves should matter more than errors during minor fluctuations.
This may reduce the influence of small alternating bars on the weight distribution.
Pure directional configuration
Directional loss is useful when every close-to-close directional observation should be treated equally.
It creates a straightforward right-or-wrong scoring process.
How this differs from averaging moving averages
A normal moving-average ribbon or composite may calculate:
Average of SMA, EMA, HMA and other methods.
If every method receives equal weight permanently, its influence never changes.
Adaptive Trend Ensemble instead calculates:
Performance-dependent weights.
Sequential loss updates.
A dynamically changing weighted output.
Two bars with the same expert values can produce different ensemble values if the weight distributions differ.
How this differs from selecting the current fastest average
The indicator does not select whichever moving average is currently closest to price or whichever has moved the most.
Weights are based on whether previous expert slopes correctly anticipated realised price direction.
An expert can therefore lead even if it is not the fastest or closest line.
How this differs from an optimisation
The model does not search historical data for one set of parameters with the best backtest result.
It does not change the shared length of each expert.
Instead, it performs continuous online adaptation of the expert weights.
This avoids permanently selecting one historical winner, but it also means recent performance can strongly influence the current model.
How this differs from a machine-learning forecast
The indicator uses a genuine online-learning algorithm, but it is not a neural network or a price-target forecasting model.
It does not estimate the size of the next move.
The experts make binary directional predictions derived from their slopes.
The learning system then adjusts how much influence each moving-average value receives.
It is therefore best understood as an adaptive model-selection and blending process.
Causality and real-time behaviour
The learning update uses:
The prior-bar slope of each expert.
The current close-to-close realised direction.
It does not use future bars.
On historical completed candles, the update is fully causal.
On the current live candle:
The close can continue changing.
The realised direction can change.
Expert values can change.
Weights and consensus can update intrabar.
A bullish or bearish flip may appear before the candle closes.
Users requiring confirmed signals should evaluate the indicator at bar close.
Strengths
Combines eight distinct smoothing methods.
Adapts expert influence through online learning.
Supports directional and magnitude-sensitive losses.
Uses multiplicative updates rather than fixed weighting.
Provides optional protection against permanent weight collapse.
Separates ensemble direction from expert consensus.
Displays the currently leading method.
Uses one shared horizon for a fairer expert comparison.
Requires no offline training process.
Provides transparent open-source calculations.
Summary
Adaptive Trend Ensemble combines eight moving-average experts using a multiplicative online-learning model.
Each expert uses the same Base Length but applies a different smoothing method. The previous slope of each expert acts as its directional prediction for the latest close-to-close move.
After the realised direction is observed, incorrect experts receive either a fixed directional loss or an ATR-normalised magnitude-weighted loss. Their weights are reduced using an exponential Hedge update, then normalised and optionally adjusted using a minimum Weight Floor.
The current expert values are blended according to these adaptive weights, producing one ensemble line whose effective behaviour changes as different methods gain or lose influence.
A separate weighted vote measures current directional agreement. This consensus controls the visual glow and is displayed beside the current leading expert.
The result is a transparent adaptive trend model that does not assume one moving average will remain optimal. Instead, it continuously redistributes influence toward the methods that have recently aligned better with realised price direction while retaining configurable control over responsiveness, diversity and visual smoothing.
지표

Innovation-Gated Hull Supertrend [BackQuant] Innovation-Gated Hull Supertrend
Overview
Innovation-Gated Hull Supertrend is an adaptive trend-following overlay that combines three distinct signal-processing components:
A Hull Moving Average projection for responsive trend estimation.
An innovation-gated recursive filter for adaptive noise reduction.
A volatility-based Supertrend applied to the filtered Hull estimate.
The indicator is designed to behave differently during quiet and active market conditions.
When the Hull estimate changes only slightly relative to recent volatility, the innovation gate restricts how much of that movement is admitted into the filtered trend estimate. The Supertrend bands can also expand during these quieter conditions, reducing sensitivity to minor fluctuations.
When a larger and statistically more meaningful change occurs, the gate opens. The recursive filter becomes more responsive, the Supertrend bands return closer to their base width, and the model is allowed to react more quickly.
The result is a trend framework that attempts to balance two competing requirements:
Remain stable when price movement is small and noisy.
Respond more quickly when new information produces a meaningful displacement.
The indicator does not predict future prices. It is a causal trend model that adapts its response according to the size of newly arriving information relative to the current volatility environment.
Core calculation chain
The complete calculation can be summarised as:
Calculate a Hull Moving Average projection from the selected price source.
Estimate current volatility using ATR, standard deviation, or a blend of both.
Compare the Hull projection with the recursive filter’s previous estimate.
Normalise that difference by volatility to calculate an innovation score.
Pass the score through a smooth logistic gate.
Use the gate to adapt the recursive filter’s measurement and process uncertainty.
Generate the innovation-filtered Hull estimate.
Optionally adapt the Supertrend band multiplier using the same gate.
Apply Supertrend logic around the filtered Hull estimate.
Generate bullish and bearish regime changes when the Supertrend changes sides.
Each stage solves a different problem.
The Hull projection provides a responsive directional input. The innovation filter decides how much of that input should be trusted. The Supertrend then converts the filtered estimate into a persistent trailing regime.
Historical background
The indicator combines ideas from several areas of technical analysis and signal processing.
Hull Moving Average
The Hull Moving Average was developed by Alan Hull as a method of reducing lag while preserving a smooth output.
Traditional moving averages face a basic trade-off:
Short averages respond quickly but contain more noise.
Long averages are smoother but react later.
The Hull Moving Average attempts to improve this balance by combining weighted moving averages of different lengths.
Its general construction is:
Fast WMA = WMA of price over approximately half the main length.
Slow WMA = WMA of price over the full length.
Raw Hull = 2 × Fast WMA - Slow WMA.
Final Hull = WMA of the Raw Hull over the square root of the main length.
The subtraction stage compensates for some of the delay introduced by the longer average. The final square-root smoothing stage reduces noise in the compensated series.
Recursive estimation and the Kalman-filter principle
The innovation filter is based on the general recursive-estimation framework associated with Kalman filtering.
The Kalman filter was developed by Rudolf E. Kálmán and became widely used in engineering, navigation, aerospace, robotics and control systems.
A recursive estimator typically follows two stages:
Predict the current state from the previous state.
Correct that prediction using the newest observation.
The correction depends on how uncertain the model is and how reliable the new observation is believed to be.
The difference between the observation and prediction is called the:
Innovation
In this indicator:
The observation is the current Hull projection.
The prediction is the previous filtered estimate.
The innovation is the difference between them.
A large innovation means the Hull projection has moved significantly away from the model’s prior estimate.
A small innovation means the new observation is close to what the model already expected.
Supertrend
Supertrend is a volatility-trailing concept built from an underlying price reference and ATR-based bands.
Its basic structure consists of:
An upper band above the reference.
A lower band below the reference.
One-sided trailing behaviour.
A regime switch when price crosses the opposing band.
In a bullish regime, the lower band acts as the active trail.
In a bearish regime, the upper band acts as the active trail.
This indicator modifies the conventional approach in two important ways:
The central reference is the innovation-filtered Hull estimate rather than a normal price midpoint.
The band multiplier can adapt according to the innovation gate.
Stage 1: Hull projection
The first stage calculates the Hull projection from the selected price source.
The script determines:
The full Hull length.
A half-length rounded to a valid integer.
A square-root length rounded to a valid integer.
It then calculates:
Fast WMA = WMA(source, half length)
Slow WMA = WMA(source, full length)
Raw Hull = 2 × Fast WMA - Slow WMA
Hull Projection = WMA(Raw Hull, square-root length)
The Hull projection is more responsive than many conventional moving averages of a similar nominal length.
However, responsiveness also means it can react to short-lived movements. For that reason, the Hull projection is not used directly as the final trend line. It becomes the observation supplied to the innovation filter.
Hull Length
The Hull Length controls the underlying trend horizon.
Lower values:
React more quickly.
Follow shorter trend legs.
Produce more local changes.
Admit more short-term noise into the next stage.
Higher values:
Produce a smoother projection.
Focus on broader trend structure.
Respond later to sudden reversals.
The Hull Length therefore controls the basic timescale of the model before any adaptive filtering or Supertrend logic is applied.
Stage 2: Volatility model
The innovation must be interpreted relative to current market conditions.
A movement of 10 points may be large in a quiet market but insignificant in a highly volatile market.
The indicator therefore normalises the innovation using a selectable volatility estimate.
Three modes are available:
ATR
Standard Deviation
Blend
ATR mode
Average True Range measures recent trading range while accounting for gaps from the previous close.
True Range is based on the greatest of:
Current high minus current low.
Absolute current high minus previous close.
Absolute current low minus previous close.
ATR then smooths True Range across the selected Volatility Length.
ATR is useful because it measures the realised movement range of the instrument.
It is sensitive to:
Wide candles.
Price gaps.
Range expansion.
Standard Deviation mode
Standard deviation measures how widely the Hull projection has varied around its recent mean.
It is a dispersion measure rather than a range measure.
Standard deviation responds to:
Variation in the selected series.
Directional displacement.
Changes in the distribution of the filtered input.
While ATR focuses on bar range, standard deviation focuses on dispersion of the Hull series itself.
Blend mode
Blend mode calculates the average of ATR and standard deviation.
Conceptually:
Blended Volatility = (ATR + Standard Deviation) / 2
This provides a combined estimate incorporating:
Observed range behaviour.
Statistical dispersion of the Hull projection.
Neither measure is universally superior. The blend attempts to reduce dependence on only one definition of volatility.
Volatility Length
The Volatility Length controls how quickly the normalisation baseline changes.
Lower values:
React faster to recent volatility changes.
Cause the innovation score to adjust more quickly.
May make the gate less stable.
Higher values:
Produce a slower volatility baseline.
Create more consistent normalisation.
May respond later when volatility changes abruptly.
The volatility estimate is prevented from falling below the instrument’s minimum tick size, avoiding unstable division during extremely quiet periods.
Stage 3: Innovation calculation
The filter begins each bar with a prediction.
In this implementation, the prediction is the previous filtered estimate.
The innovation is:
Innovation = Hull Projection - Previous Filter Estimate
The innovation may be positive or negative.
A positive value means the Hull projection is above the prior estimate.
A negative value means it is below the prior estimate.
The absolute innovation measures the size of the disagreement regardless of direction.
Innovation score
The raw innovation is normalised by current volatility:
Innovation Score = |Innovation| / Volatility
This expresses the new movement in volatility units.
For example:
A score of 0.25 means the innovation is approximately one quarter of the selected volatility measure.
A score of 1.00 means it is approximately equal to that volatility measure.
A score above 1.00 means the change is larger than the current volatility baseline.
The score is dimensionless, making it more comparable across instruments and price scales.
This is the key quantity used to determine whether the filter should remain cautious or become more responsive.
Stage 4: Logistic innovation gate
The innovation score is passed through a logistic function.
The logistic function has the form:
Gate = 1 / (1 + exp(-x))
Its output remains between zero and one.
In the indicator, the gate input depends on:
Innovation Score
Innovation Threshold
Gate Sharpness
Conceptually:
Gate Input = Sharpness × (Score - Threshold)
When the score is below the threshold:
The gate approaches zero.
The filter treats the new Hull movement cautiously.
When the score rises above the threshold:
The gate moves toward one.
The filter becomes more willing to admit the new movement.
The logistic function creates a smooth transition rather than a hard on/off switch.
This is important because a binary threshold could cause abrupt changes whenever the score moves slightly above or below one exact value.
Innovation Threshold
The Innovation Threshold determines where the gate begins moving from a quiet state toward an active state.
Higher values:
Require a larger volatility-normalised innovation.
Keep the filter conservative for longer.
Reject more moderate changes.
Lower values:
Open the gate sooner.
Increase responsiveness.
Allow smaller movements to influence the estimate.
The threshold should be interpreted in relation to the selected volatility model.
Gate Sharpness
Gate Sharpness controls how rapidly the logistic gate transitions around the threshold.
Lower sharpness:
Creates a gradual transition.
Produces a wider intermediate region.
Changes responsiveness smoothly.
Higher sharpness:
Makes the gate behave more like a hard switch.
Creates a faster transition near the threshold.
Produces stronger separation between quiet and active states.
An extremely high value can make the adaptive behaviour abrupt, while a low value may reduce the distinction between quiet and active conditions.
Admission Floor
The gate is converted into an admission value.
The Admission Floor ensures that the filter never completely ignores the Hull projection.
The admission calculation is:
Admission = Floor + (1 - Floor) × Gate
When the gate is near zero:
Admission remains near the selected floor.
When the gate is near one:
Admission approaches one.
A lower floor creates stronger filtering during quiet conditions.
A higher floor keeps the model more responsive even when innovation is small.
This setting prevents the estimator from becoming fully frozen.
Stage 5: Adaptive recursive update
The admission and gate values modify two uncertainty terms:
Measurement noise.
Process noise.
These terms control how the recursive filter balances its existing estimate against the new Hull observation.
Measurement Noise
Measurement Noise represents uncertainty in the incoming Hull projection.
Higher measurement noise tells the filter:
Trust the new observation less.
Remain closer to the previous estimate.
Produce more smoothing.
Lower measurement noise tells the filter:
Trust the Hull projection more.
Correct the estimate more aggressively.
Become more responsive.
The script adapts measurement noise using the admission value:
Adaptive Measurement Noise = Base Measurement Noise / Admission
When admission is low:
Measurement noise increases.
The new Hull movement receives less weight.
When admission is high:
Measurement noise moves closer to its base value.
The filter becomes more receptive.
Process Noise
Process Noise represents uncertainty in the filter’s current state model.
Higher process noise tells the estimator:
The underlying trend may be changing.
The previous estimate may no longer be reliable.
Allow faster adaptation.
Lower process noise tells it:
Assume the existing state remains relatively stable.
Change the estimate more cautiously.
The script increases process noise as the gate opens:
Adaptive Process Noise = Base Process Noise × (1 + Process Boost × Gate)
This creates a two-sided adaptive response.
During quiet conditions:
Measurement noise increases.
Process noise remains closer to its base level.
The filter resists small changes.
During high-innovation conditions:
Measurement noise decreases toward its normal value.
Process noise increases.
The filter becomes substantially more responsive.
Process Boost
Process Boost controls how strongly the process uncertainty expands when the gate opens.
Higher values:
Allow faster response to large innovations.
Increase the filter gain during active movement.
Can make the model more sensitive after shocks.
Lower values:
Keep behaviour closer to the base recursive filter.
Produce more controlled adaptation.
May respond more slowly to genuine regime changes.
Covariance and filter gain
The recursive filter maintains an internal covariance representing uncertainty in its estimate.
Before the new observation is processed:
Predicted Covariance = Previous Covariance + Adaptive Process Noise
The filter gain is then:
Gain = Predicted Covariance / (Predicted Covariance + Adaptive Measurement Noise)
The gain remains between zero and one.
A low gain means:
The previous estimate receives more influence.
The Hull observation receives less influence.
A high gain means:
The filter moves more strongly toward the current Hull projection.
The new estimate is:
Filtered Hull = Prediction + Gain × Innovation
The covariance is then updated for the next bar.
Why the filter is innovation-gated
A normal recursive filter may use constant process and measurement noise settings.
That means its responsiveness is broadly fixed.
This indicator changes those terms according to the size of the innovation.
The model therefore behaves differently under two broad conditions.
Quiet condition
When the Hull projection remains close to the prior estimate relative to volatility:
Innovation score is low.
Gate remains mostly closed.
Admission is limited.
Adaptive measurement noise rises.
Process noise remains lower.
Filter gain falls.
The filtered Hull changes more slowly.
Active condition
When the Hull projection moves meaningfully away from the prior estimate:
Innovation score rises.
Gate opens.
Admission approaches one.
Measurement noise decreases.
Process noise increases.
Filter gain rises.
The estimate adapts more quickly.
This allows the model to filter small movement without applying the same degree of resistance to every large move.
Stage 6: Innovation-adaptive Supertrend bands
The filtered Hull becomes the centre of the Supertrend calculation.
The initial raw bands are:
Upper Band = Filtered Hull + Factor × ATR
Lower Band = Filtered Hull - Factor × ATR
The Supertrend uses its own ATR Period, which is independent of the volatility length used by the innovation score.
This distinction is important:
Innovation volatility determines whether the filter should admit new information.
Supertrend ATR determines the distance of the trailing regime bands.
Adaptive band factor
When Adapt Bands With Innovation is enabled, the Supertrend factor changes according to the gate.
The adaptive factor is:
Adaptive Factor = Base Factor ×
When the gate is near one:
The adaptive factor approaches the base factor.
Bands become relatively tighter.
The Supertrend can respond more readily.
When the gate is near zero:
The factor expands above its base value.
Bands become wider.
Minor price fluctuations are less likely to cause a reversal.
This creates coordinated adaptation:
Quiet conditions produce stronger filtering and wider bands.
Active conditions produce faster filtering and narrower bands.
The same innovation state therefore influences both the centre estimate and the trailing threshold.
Quiet Band Expansion
Quiet Band Expansion controls how much wider the Supertrend factor becomes when the innovation gate is closed.
A value of zero disables the expansion effect even if band adaptation is enabled.
Higher values:
Create wider bands during low-innovation conditions.
Reduce quiet-market reversals.
Delay new signals until price moves further.
Lower values:
Keep the adaptive factor closer to its base setting.
Allow more responsive regime changes.
The expansion is greatest when the gate is near zero and fades as the gate opens.
Supertrend trailing logic
The raw upper and lower bands are converted into one-sided trailing bands.
The lower band is prevented from moving downward while price remains above its previous value.
The upper band is prevented from moving upward while price remains below its previous value.
This ratcheting behaviour creates:
A rising lower trail during bullish conditions.
A falling upper trail during bearish conditions.
A trend change occurs when price crosses the active opposing boundary.
In a bullish regime:
The lower band is the active Supertrend.
In a bearish regime:
The upper band is the active Supertrend.
ATR Period and Factor
ATR Period
Controls the volatility horizon used to construct the Supertrend bands.
Lower values:
React faster to current range changes.
Produce more variable band widths.
Higher values:
Produce a steadier range estimate.
Respond more slowly to sudden volatility changes.
Factor
Controls the base distance between the filtered Hull and the Supertrend bands.
Lower factors:
Create tighter bands.
Produce earlier regime changes.
Increase sensitivity to noise.
Higher factors:
Create wider bands.
Produce fewer regime changes.
Increase confirmation delay.
When adaptation is enabled, the selected factor acts as the minimum or active-condition factor. Quiet conditions may expand it further.
Trend signals
The indicator generates a long signal when the Supertrend changes into its bullish state.
It generates a short signal when the Supertrend changes into its bearish state.
The signal requires the completed calculation chain:
Hull projection.
Innovation filtering.
Adaptive band factor.
Supertrend regime change.
The plotted symbols are:
𝕃 for a bullish transition.
𝕊 for a bearish transition.
These markers identify regime changes. They are not complete trading systems and do not define stop placement, position size or profit targets.
Innovation impulse alert
The script also includes an Innovation Impulse alert.
This occurs when the innovation score crosses above the selected Innovation Threshold.
It indicates that:
The difference between the Hull projection and the recursive estimate has become large relative to volatility.
The gate is entering a more active state.
The filter is beginning to admit new information more aggressively.
An innovation impulse does not necessarily produce an immediate Supertrend reversal.
It can occur:
During acceleration within an existing trend.
At the beginning of a possible regime change.
During a temporary volatility shock.
It is therefore best interpreted as an information-arrival event rather than an automatic long or short signal.
Visual components
Hull Projection
Displays the unfiltered Hull Moving Average input.
This is useful for comparing:
The responsive raw projection.
The innovation-filtered result.
The final Supertrend.
The Hull projection will generally react first.
Filtered Hull
Displays the recursive innovation-gated estimate.
The distance between the Hull projection and filtered Hull helps illustrate the filter’s current behaviour.
During quiet conditions:
The filtered Hull may lag behind small changes.
During meaningful innovations:
It can move more rapidly toward the Hull projection.
IGH Supertrend
Displays the final volatility trail around the filtered Hull.
It is the primary regime output.
The line is coloured according to the persistent bullish or bearish trend state.
Candle colouring
Candles may be coloured according to the active Supertrend regime:
Bullish colour during the long regime.
Bearish colour during the short regime.
This provides immediate chart-wide directional context.
How to interpret the indicator
Bullish regime
A bullish regime indicates that price has crossed into the bullish side of the adaptive Supertrend structure.
The active trail is positioned below the market and can be interpreted as:
A dynamic trend boundary.
A possible pullback reference.
A regime invalidation guide.
Bearish regime
A bearish regime indicates that price has crossed into the bearish side of the adaptive structure.
The active trail is positioned above the market and may act as:
Dynamic resistance.
A rally reference.
A bearish regime invalidation guide.
Low innovation score
A low score means the current Hull movement is small relative to volatility.
The model responds by:
Filtering more strongly.
Reducing admission.
Using a lower recursive gain.
Potentially expanding the Supertrend bands.
This is intended to reduce reactions to small fluctuations.
High innovation score
A high score means the Hull projection has changed substantially relative to volatility.
The model responds by:
Opening the gate.
Increasing admission.
Increasing process uncertainty.
Raising the filter gain.
Reducing quiet-condition band expansion.
This allows a faster response when the incoming information is more significant.
Rising Hull without a trend flip
The Hull projection may turn before the filtered Hull or Supertrend.
This means:
The fast input has changed.
The adaptive filter has not yet admitted enough of that change.
The Supertrend boundary has not yet been crossed.
This is not an error. It demonstrates the staged confirmation design.
Innovation impulse without trend reversal
An innovation impulse can occur without a long or short signal.
This may indicate:
Acceleration in the existing trend.
A volatility shock.
An attempted reversal that has not crossed the Supertrend.
The Supertrend remains the final regime layer.
How to use the indicator
1. Trend regime filter
Use the active Supertrend state to filter another entry method:
Prioritise long setups during bullish regimes.
Prioritise short setups during bearish regimes.
2. Pullback framework
In a bullish regime, pullbacks toward the Supertrend may represent tests of the active trend boundary.
In a bearish regime, rallies toward the Supertrend may represent resistance tests.
A touch alone does not guarantee continuation.
3. Innovation monitoring
The innovation alert can be used to identify when the model detects a meaningful change in its input.
This may help direct attention to:
Fresh acceleration.
Breakout attempts.
Possible trend transitions.
4. Confirmation framework
The three optional lines can be read as a progression:
Hull projection changes first.
Filtered Hull adapts according to innovation.
Supertrend confirms the final regime.
This allows users to study the difference between early movement and confirmed structure.
5. Trailing risk reference
The final Supertrend may be used as a visual trailing reference.
However, it does not account for:
Account size.
Position size.
Slippage.
Liquidity.
Maximum acceptable loss.
It should not replace a complete risk-management process.
Parameter interaction
The settings should not be tuned independently without considering how they interact.
More responsive configuration
A more responsive setup may use:
Lower Hull Length.
Lower Innovation Threshold.
Higher Admission Floor.
Lower Measurement Noise.
Higher Process Noise or Process Boost.
Lower Supertrend Factor.
Lower Quiet Band Expansion.
This will generally produce earlier changes but more noise.
More conservative configuration
A more conservative setup may use:
Higher Hull Length.
Higher Innovation Threshold.
Lower Admission Floor.
Higher Measurement Noise.
Lower Process Boost.
Higher Supertrend Factor.
Higher Quiet Band Expansion.
This will generally create fewer transitions but greater delay.
Balanced interpretation
Changing several settings in the same direction can produce an extreme result.
For example:
A very low threshold, high admission floor, large process boost and tight Supertrend factor may overreact.
A very high threshold, low admission floor, high measurement noise and wide Supertrend factor may respond excessively slowly.
The appropriate balance depends on the instrument, timeframe and intended holding period.
How this differs from a standard Hull trend indicator
A standard Hull trend indicator normally uses:
Hull slope.
Price crossing the Hull.
A fast and slow Hull comparison.
This indicator instead:
Uses the Hull as an observation.
Measures its disagreement with a recursive estimate.
Normalises that disagreement by volatility.
Adapts the filter gain according to the innovation.
Applies a final Supertrend regime around the filtered result.
The Hull is therefore the beginning of the model, not the final signal.
How this differs from a fixed Kalman-style filter
A fixed recursive filter uses constant uncertainty settings.
Innovation-Gated Hull Supertrend adapts both measurement and process uncertainty according to the normalised innovation.
This means:
Small innovations are filtered more heavily.
Large innovations receive greater admission.
The response speed is therefore state dependent.
How this differs from a standard Supertrend
A standard Supertrend is commonly centred around a raw price reference such as HL2.
This indicator uses:
A responsive Hull projection.
An innovation-gated recursive estimate of that projection.
An optionally adaptive band multiplier.
The Supertrend is therefore built around a filtered trend estimate rather than raw price alone.
Strengths
Combines responsive and stable trend-processing stages.
Normalises new movement by current volatility.
Uses a smooth gate rather than a binary threshold.
Adapts measurement and process uncertainty.
Can widen trend bands during quiet conditions.
Can respond more rapidly to meaningful innovations.
Separates early movement from final regime confirmation.
Supports ATR, standard deviation and blended volatility models.
Provides trend, impulse and visual comparison outputs.
Limitations
The indicator is reactive rather than predictive.
Strong filtering can delay genuine reversals.
Responsive settings can increase whipsaws.
A large innovation may represent a temporary shock rather than a lasting trend.
Supertrend signals still depend on ATR and price crossing behaviour.
Parameter combinations can materially change the model’s behaviour.
The indicator may require different settings across assets and timeframes.
The recursive state develops from the available chart history.
Values can update while the current real-time candle is still forming.
Causality and real-time behaviour
The calculation uses current and historical observations without future-looking references.
However, like most indicators calculated on live candles, the current bar’s values can change before the candle closes.
This means:
The Hull projection may move intrabar.
The innovation score and gate may change intrabar.
A Supertrend transition may appear and disappear before confirmation.
Users requiring confirmed signals should evaluate the indicator at bar close or configure alerts accordingly.
Alerts
The indicator provides three alert conditions:
IGH ST Long: the adaptive Supertrend changes into a bullish regime.
IGH ST Short: the adaptive Supertrend changes into a bearish regime.
IGH Impulse: the normalised innovation score crosses above the selected threshold.
The impulse alert identifies increased information flow into the filter. It does not specify direction by itself because the innovation score uses the absolute size of the prediction error.
Summary
Innovation-Gated Hull Supertrend combines a responsive Hull Moving Average, a volatility-normalised innovation gate, an adaptive recursive filter and a volatility-trailing Supertrend.
The Hull projection provides an early estimate of directional movement. The recursive filter compares that projection with its prior state and measures the resulting innovation relative to ATR, standard deviation or a blend of both.
A logistic gate then determines how strongly the new movement should be admitted. During quiet conditions, the filter becomes more conservative and the Supertrend bands can expand. During meaningful displacement, the filter becomes more responsive and the bands move closer to their base width.
The final Supertrend converts the adaptive estimate into a persistent bullish or bearish regime.
The indicator is designed to make responsiveness conditional rather than fixed: small movements receive stronger filtering, while larger volatility-adjusted innovations are allowed to influence the model more quickly.
지표

VWAP Deviation Trend [BackQuant]VWAP Deviation Trend
Overview
VWAP Deviation Trend is a volume-weighted trend-following overlay that transforms VWAP and its surrounding price distribution into a directional trailing structure.
Rather than using VWAP only as a fair-value line, the indicator calculates:
A configurable anchored or rolling VWAP.
The volume-weighted standard deviation of price around that VWAP.
Adaptive upper and lower deviation bands.
One-sided trailing boundaries used to confirm bullish and bearish regimes.
The indicator is designed to identify when price has moved far enough away from accepted volume-weighted value to establish a meaningful directional shift.
Unlike a simple VWAP crossover, price can move through VWAP without immediately changing the active trend. A new regime requires price to break the opposite trailing deviation boundary, optionally with confirmation from the direction of VWAP itself.
The updated visual engine also measures trend strength and uses it to control:
Gradient intensity.
Trail glow width.
Post-flip bloom effects.
The visual separation between price and the active trail.
Core concept
VWAP represents the average price paid over a selected period, weighted by trading volume.
The basic formula is:
VWAP = Sum of Price × Volume / Sum of Volume
Prices associated with greater volume contribute more heavily to the final value. This makes VWAP a useful approximation of:
Volume-weighted fair value.
The center of traded activity.
The average position of market participants.
An institutional execution benchmark.
However, VWAP alone does not explain how widely price has been distributed around that value.
VWAP Deviation Trend treats VWAP as the center of a volume-weighted price distribution and measures the dispersion around it. That dispersion is then used to create trailing trend boundaries.
VWAP calculation modes
The indicator supports five VWAP windows:
4 Hours
Daily
Weekly
Rolling Lookback Bars
Rolling Lookback Days
4 Hours
Resets VWAP at fixed four-hour intervals.
This can be useful for:
Cryptocurrency markets.
Intraday futures.
Continuously traded markets.
Shorter fair-value regimes.
Daily
Resets at the beginning of each calendar day.
This is the traditional intraday VWAP structure and is useful for:
Session bias.
Intraday mean reversion.
Day-trading trend confirmation.
Weekly
Accumulates volume and price across the current week.
This creates a slower structural anchor suited to:
Swing trading.
Weekly positioning.
Broader accepted-value analysis.
Rolling Lookback Bars
Calculates VWAP over a fixed number of candles.
The window moves forward continuously and does not reset at a calendar boundary.
This is useful for:
Systematic trend models.
Consistent multi-timeframe analysis.
Markets where daily sessions are less important.
Rolling Lookback Days
Includes bars that fall within a selected number of calendar days.
This keeps the analytical window tied to elapsed time instead of a fixed candle count.
Anchored versus rolling VWAP
Anchored modes begin at a fixed boundary and accumulate until the next reset.
Rolling modes continually remove old observations as new observations arrive.
Anchored VWAP is useful when a particular session or week has structural meaning. Rolling VWAP is useful when the trader wants a stable and continuously adapting lookback.
Volume-weighted deviation
The indicator calculates more than the VWAP mean.
It also measures volume-weighted price variance using:
Weighted Mean Square = Sum of Price² × Volume / Sum of Volume
Weighted Variance = Weighted Mean Square - VWAP²
Weighted Deviation = Square Root of Weighted Variance
This measures how widely prices associated with meaningful trading volume are distributed around VWAP.
A small deviation suggests:
Trading is concentrated near fair value.
The market is relatively balanced.
Price acceptance is narrow.
A large deviation suggests:
Trading is spread across a wider range.
Price discovery is more active.
The market is less tightly centered around VWAP.
Because the calculation is volume weighted, high-volume prices influence the bands more than low-volume excursions.
Fallback when volume is unavailable
If usable volume is not available, the indicator falls back to an unweighted arithmetic mean and variance.
This allows it to function on synthetic or limited-volume symbols, although the result should then be interpreted as a rolling or anchored mean rather than a true VWAP.
Deviation bands
The raw width is calculated as:
Deviation Width = Weighted Deviation × Deviation Multiplier
The upper and lower raw bands are:
Upper Band = VWAP + Band Width
Lower Band = VWAP - Band Width
Higher deviation multipliers create wider bands and fewer trend changes.
Lower multipliers create tighter bands and faster, more frequent flips.
ATR minimum width
During low-dispersion periods, volume-weighted deviation can become extremely narrow.
This can cause small and insignificant movements to trigger repeated reversals.
The optional ATR floor calculates:
ATR Floor = ATR × ATR Minimum Multiplier
The final width becomes:
Band Width = Maximum of Deviation Width and ATR Floor
This preserves volume-weighted deviation as the primary band engine while preventing the channel from collapsing below a practical volatility threshold.
Trailing-band construction
The raw deviation bands move freely with VWAP and dispersion.
The indicator converts them into one-sided trailing levels.
Lower trail
While the selected trigger remains above the lower trail:
The trail can rise.
It cannot move downward.
This creates a ratcheting support structure.
Upper trail
While the trigger remains below the upper trail:
The trail can fall.
It cannot move upward.
This creates a ratcheting resistance structure.
The active trend trail is:
The lower trail during bullish regimes.
The upper trail during bearish regimes.
Why trailing logic matters
A raw VWAP band can move toward price and create unstable signals.
The one-sided trail preserves trend structure and creates hysteresis.
Hysteresis means the threshold required to enter a bullish regime is different from the threshold required to enter a bearish regime.
This allows price to rotate around VWAP without constantly changing the active trend.
Trend initialization
When the first valid VWAP is available:
The trend initializes bullish if the trigger is at or above VWAP.
The trend initializes bearish if the trigger is below VWAP.
After initialization, a full break of the opposite trail is required to change regimes.
Bullish trend flip
A bullish flip requires:
The selected trigger to move above the upper trailing band.
The current trend not already to be bullish.
VWAP slope confirmation to pass if enabled.
Once confirmed:
The trend becomes bullish.
The active trail moves beneath the market.
A bullish signal marker is displayed.
Bearish trend flip
A bearish flip requires:
The selected trigger to move below the lower trailing band.
The current trend not already to be bearish.
VWAP slope confirmation to pass if enabled.
Once confirmed:
The trend becomes bearish.
The active trail moves above the market.
A bearish signal marker is displayed.
Flip trigger
The trend can be triggered using:
Close
The selected VWAP price source
Close is the more conventional option.
Using the price source, such as HLC3, can produce a slightly smoother trigger because it reflects more of the bar than the close alone.
VWAP slope confirmation
Optional slope confirmation requires VWAP itself to move in the direction of the proposed new trend.
For a bullish flip:
Current VWAP must be above VWAP from the selected lookback.
For a bearish flip:
Current VWAP must be below its prior value.
This can help reject:
Temporary band breaks.
Low-volume price spikes.
Liquidity sweeps against flat fair value.
The tradeoff is additional confirmation delay.
Breaking the trail on flips
The active trail changes from one side of the market to the other during a regime transition.
The Break Trail On Flips option inserts a visual gap on the flip bar so the previous and new trails are not connected by a misleading line segment.
This affects presentation only.
Visual trend-strength engine
The updated script includes a visual-strength model that controls the intensity of the gradient and glow.
It combines two measurements:
Distance between price and the active trail.
Slope of VWAP relative to the current band width.
Distance strength
The script measures:
Absolute Distance = |Close - Trend Trail|
This is normalized by the current band width.
A larger distance indicates stronger separation between price and the structural trail.
Slope strength
VWAP movement across the slope lookback is also normalized by the band width.
This measures whether volume-weighted fair value itself is moving meaningfully relative to the size of the current deviation structure.
Combined trend strength
The final visual strength is weighted:
70% price-to-trail distance.
30% VWAP slope strength.
This produces a value between zero and one.
It does not change trend logic or signals. It controls the visual intensity of the indicator.
Layered gradient fill
Instead of using one flat gradient, the updated indicator divides the space between the trail and price into six visual layers.
The levels are placed progressively between:
The active trend trail.
The current closing price.
The gradient is:
Most concentrated near the structural trail.
Progressively softer toward price.
The opacity adapts to trend strength.
When price is strongly separated from the trail and VWAP is moving with the regime:
The gradient becomes more vivid.
When the trend is weak:
The fill becomes softer and more transparent.
This makes the visual ribbon encode more than direction. It also reflects the current strength of the price-to-structure relationship.
Flip bloom
After a confirmed trend flip, the indicator creates a temporary bloom around the new trail.
The bloom is strongest immediately after the transition and fades over the following bars.
Its intensity follows this general sequence:
First bar after flip: strongest bloom.
Second bar: reduced bloom.
Third bar: light residual bloom.
Afterward: bloom disappears.
This visually emphasizes fresh regime changes without permanently increasing chart brightness.
The bloom is cosmetic and does not affect calculation.
Adaptive trail glow
The glow surrounding the trail also changes with trend strength.
The base width is ATR-scaled, then increases slightly as the visual trend-strength score rises.
This creates:
A broader glow during stronger regimes.
A narrower glow when trend structure is weaker.
The glow contains:
An inner, more visible layer.
A wider, softer outer layer.
Visual interpretation
The updated presentation provides several pieces of information simultaneously:
Color shows the active trend direction.
The trail shows the structural regime boundary.
Gradient intensity reflects trend strength.
Glow width reinforces structural conviction.
The bloom highlights fresh regime transitions.
How to use the indicator
Trend regime filter
Use the active color and trail position as directional context:
Favor longs during bullish regimes.
Favor shorts during bearish regimes.
Pullback structure
In a bullish regime:
VWAP represents volume-weighted fair value.
The lower trail represents deeper structural support.
In a bearish regime:
VWAP represents the mean-reversion anchor.
The upper trail represents deeper structural resistance.
Trend-strength context
A vivid gradient and broader glow suggest:
Price is well separated from the trail.
VWAP is moving in the trend direction.
The regime has stronger structural momentum.
A weak or faded gradient suggests:
Price is closer to the trail.
VWAP slope is weaker.
The trend may be consolidating or losing strength.
Fresh transitions
The bloom helps identify newly established regimes.
A fresh flip with:
Strong bloom.
Growing price separation.
VWAP slope alignment.
generally represents stronger early trend structure than a flip that immediately loses visual intensity.
Dynamic risk management
The active trail may be used as:
A trailing stop reference.
A regime invalidation boundary.
A position-management guide.
Because the trail responds to both volume-weighted dispersion and volatility, it adjusts as market conditions change.
How this differs from a standard VWAP
A standard VWAP:
Plots only volume-weighted mean price.
Usually resets once per session.
Does not maintain trend state.
VWAP Deviation Trend:
Supports anchored and rolling windows.
Calculates volume-weighted dispersion.
Creates adaptive raw bands.
Converts them into directional trailing boundaries.
Maintains persistent bullish and bearish regimes.
Adds a strength-reactive visual system.
How this differs from Supertrend
A traditional Supertrend normally uses a central price such as HL2 and ATR-based bands.
VWAP Deviation Trend uses:
Volume-weighted fair value as the center.
Volume-weighted standard deviation as the primary width.
ATR only as an optional minimum floor.
This means the trail responds not only to range volatility, but also to where trading volume has been concentrated.
How this differs from Bollinger Bands
Bollinger Bands normally use:
A moving average.
Unweighted standard deviation.
Symmetrical non-trailing bands.
This indicator uses:
A volume-weighted mean.
Volume-weighted variance.
One-sided trailing bands.
Persistent trend-state logic.
It is therefore a trend-regime model rather than a standard mean-reversion envelope.
Input guide
VWAP Mode
Selects the anchored or rolling calculation window.
Deviation Multiplier
Controls the width of the statistical bands.
Higher values produce wider, slower regimes. Lower values produce tighter and faster regimes.
ATR Minimum Width
Prevents excessive narrowing during compressed conditions.
VWAP Slope Confirmation
Requires volume-weighted fair value to move with the proposed trend.
Flip Trigger
Selects whether close or the chosen price source must cross the trail.
Visual settings
Allow the trader to display:
The trend trail.
VWAP.
Raw deviation bands.
Layered gradient.
Adaptive glow.
Signals.
Trend candles.
Strengths
Combines fair value, dispersion, and trend structure.
Uses volume-weighted mean and variance.
Supports multiple anchored and rolling VWAP windows.
Uses ATR protection against narrow-band whipsaws.
Creates persistent regimes with hysteresis.
Provides optional VWAP slope confirmation.
Includes a trend-strength-reactive visual system.
Clearly emphasizes fresh trend transitions.
Limitations
Volume quality varies between instruments.
Anchored VWAP modes may be unstable immediately after a reset.
Long windows can react slowly to sudden regime changes.
Tight settings can increase whipsaws.
Wide settings can delay reversals.
Slope confirmation can add additional lag.
Visual strength is contextual and is not a separate trading signal.
Alerts
The indicator includes alerts for:
Confirmed bullish trend flips.
Confirmed bearish trend flips.
These represent complete VWAP deviation regime changes, not ordinary crosses of VWAP.
Summary
VWAP Deviation Trend converts volume-weighted fair value and price dispersion into a directional trend trail.
It calculates VWAP over a configurable anchored or rolling window, measures volume-weighted standard deviation around that VWAP, and builds upper and lower deviation bands. An optional ATR floor prevents the structure from becoming excessively narrow during quiet conditions.
The raw bands are transformed into one-sided trails. The lower trail ratchets upward during bullish regimes, while the upper trail ratchets downward during bearish regimes. Trend changes occur only when price breaks the opposite trail, optionally with confirmation from the slope of VWAP.
The updated visual engine measures price separation and VWAP slope to dynamically control the layered gradient, trail glow, and temporary post-flip bloom. This creates a clearer representation of direction, structural strength, and fresh regime transitions without changing the underlying signal logic. 지표

Median Cascade Trend [BackQuant]Median Cascade Trend
Overview
Median Cascade Trend is a noise-resistant trend-following indicator that combines multiple causal median filters , an Ehlers-style two-pole Super Smoother , and a configurable chop-gating system .
Its purpose is to identify meaningful directional structure while rejecting the types of price movement that frequently cause conventional moving averages to whipsaw:
Single-bar spikes
Short-lived price shocks
Irregular wicks
Low-efficiency sideways movement
Weak slopes that do not represent genuine directional progress
The indicator processes price in three distinct stages:
A median-filter cascade removes impulsive and short-duration noise.
A two-pole low-pass filter smooths the remaining structural signal.
A chop gate decides whether a change in direction is strong enough to update the active trend state.
This creates a trend line that is intentionally more selective than a standard moving average. The line itself can continue evolving, but trend-state changes are only accepted when the underlying movement passes the chosen quality tests.
The result is a system that separates:
The estimated trend line
The raw direction of that line
The confirmed trend regime
That distinction is important. The indicator does not assume that every small turn in a smoothed line represents a valid trend reversal.
Core idea
Most trend filters are built around linear averaging. They combine historical prices using fixed or exponentially decaying weights.
Examples include:
SMA
EMA
WMA
HMA
DEMA
These filters are effective for general smoothing, but they have a weakness: a single extreme observation can influence the output immediately.
If one bar produces a large wick or temporary price shock, a moving average will usually be pulled toward that value because it includes the magnitude of every observation.
A median filter behaves differently.
Instead of averaging the values inside a window, it sorts them and selects the middle observation. This makes it highly resistant to isolated extremes.
Median Cascade Trend uses this property repeatedly before applying traditional low-pass smoothing.
The central idea is:
Remove impulsive noise first.
Smooth the cleaned signal second.
Confirm direction only when the movement is efficient or sufficiently steep.
This ordering is deliberate. Smoothing a noisy series and filtering noise before smoothing are not the same thing.
Where median filtering comes from
Median filters are widely used in digital signal processing, image processing, and engineering.
One of their best-known applications is the removal of impulse noise , sometimes called salt-and-pepper noise in image processing.
Impulse noise consists of isolated extreme observations that are not representative of the surrounding signal.
In market data, comparable events include:
Temporary liquidity gaps
Single-bar stop runs
Erroneous prints
Sharp wick reversals
News spikes that immediately retrace
A linear smoother such as an SMA or EMA cannot distinguish between an important sustained move and an isolated outlier. Both are included according to their numerical magnitude.
A median filter is nonlinear. It selects the central-ranked value rather than calculating an arithmetic mean.
For example, consider five observations:
100
101
102
103
140
The average is:
109.2
The median is:
102
The isolated value at 140 significantly distorts the average but has almost no effect on the median.
This is why median filtering is especially useful when the objective is to preserve structural turns while rejecting isolated noise.
What makes a median filter nonlinear
A normal moving average can be represented as a weighted sum of its inputs.
A median filter cannot.
Its output depends on the ordering of observations, not their arithmetic combination. This makes it a nonlinear filter.
That has several important consequences:
Outliers have limited influence.
Edges and structural shifts can be preserved more cleanly.
The response is not equivalent to ordinary low-pass averaging.
The filter may hold a value until enough observations confirm a change.
In trading terms, the median filter often behaves more like a structural selector than a conventional average.
What “causal” means
The median stages in this indicator are causal.
A causal filter uses:
The current bar
Past bars
It does not use future observations.
This matters because many visually smooth filtering methods can only produce their best result by centering the calculation around the current point, which requires future data.
This script does not do that.
Every value is calculated from information available at that bar, making the filter suitable for live use.
Why use a cascade of median filters
A single median filter can remove isolated spikes, but noise does not always occur as one extreme bar.
It can appear as:
Two-bar shocks
Short bursts of alternating movement
Small clusters of irregular candles
Residual distortion left after the first filtering pass
A cascade applies multiple median stages sequentially:
Stage 1 processes the original source.
Stage 2 processes the output of Stage 1.
Stage 3 processes the output of Stage 2.
Each stage removes a different layer of short-duration instability.
The process is similar to progressively cleaning a signal:
The first stage removes obvious impulse noise.
The second stage removes remaining short-term irregularity.
The third stage produces a more stable structural series before low-pass smoothing.
Median Stage 1
The first median stage is intended to reject isolated one-bar disturbances.
With a short setting such as 3:
The filter remains responsive.
Single-bar spikes are strongly suppressed.
Most genuine multi-bar movement remains visible.
This is the most tactical stage.
Median Stage 2
The second stage receives an already-cleaned input.
Its role is to remove:
Short-duration residual noise
Small alternating movements
Irregularity that survived the first stage
A slightly longer setting such as 5 creates stronger structural consistency.
Median Stage 3
The third stage provides the final nonlinear cleaning pass.
With a longer setting such as 7:
The output becomes more stable.
Short-lived reversals are reduced.
Only more persistent changes are passed into the low-pass stage.
This is the most conservative median stage.
Cascade Stages input
The user can select how many median stages are active:
1 stage: fastest and most responsive
2 stages: balanced noise rejection
3 stages: strongest impulse-noise suppression
The unused stages are still calculated internally, but the selected stage determines which output is sent into the Super Smoother.
Why cascade instead of one very long median
Applying several shorter filters is not always equivalent to applying one very long median filter.
A long median window can:
Delay structural changes heavily
Flatten shorter trend legs
Become insensitive to local turns
A cascade allows the filtering process to be distributed across stages.
This provides greater control over:
How aggressively isolated noise is removed
How much short-duration movement survives
How smooth the final structural input becomes
It also lets users build a progression such as 3, 5, and 7 rather than applying one blunt window.
The low-pass stage
After the median cascade, the signal is passed into a two-pole Super Smoother .
The median cascade removes nonlinear impulse noise, but its output can still contain:
Small step changes
Residual high-frequency movement
Sharp transitions caused by median replacement
The Super Smoother converts that cleaned but potentially stepped series into a smoother trend line.
This creates a hybrid filtering system:
Nonlinear median filtering for outlier rejection
Recursive low-pass filtering for smooth trend extraction
These components solve different problems.
Where the Super Smoother comes from
The Super Smoother is associated with John F. Ehlers’ application of digital signal processing techniques to financial markets.
It is based on the behavior of a two-pole low-pass filter and is designed to suppress high-frequency components more effectively than many conventional moving averages.
Traditional moving averages are simple smoothers, but they are not necessarily optimized as frequency-selective filters.
The Super Smoother uses recursively calculated coefficients derived from:
Exponential decay
Trigonometric terms
A selected cutoff period
The objective is to reduce high-frequency market noise while retaining lower-frequency directional structure.
What a low-pass filter does
A low-pass filter allows slow-moving components of a signal to pass while reducing fast-moving components.
In market terms:
Slow components represent broader trend structure.
Fast components represent short-term noise, rapid oscillation, and microstructure disturbance.
The Low-Pass Length determines the separation.
Lower values:
Allow more short-term movement through.
React faster.
Produce more turns.
Higher values:
Reject more high-frequency movement.
Produce a smoother trend line.
Respond later to structural changes.
Why use a two-pole filter
The number of poles broadly describes the order and steepness of a filter.
A two-pole filter generally provides:
Stronger attenuation of high-frequency noise than a one-pole filter.
A smoother output.
A more defined frequency response.
It also uses prior filter outputs recursively, allowing substantial smoothing without requiring an extremely long direct averaging window.
The full signal-processing chain
The calculation can be understood as:
Raw price source
Median Stage 1
Optional Median Stage 2
Optional Median Stage 3
Two-pole Super Smoother
Direction measurement
Chop-quality validation
Persistent trend state
Each layer has a distinct purpose.
Median cascade
Rejects isolated and short-lived noise.
Super Smoother
Reduces the remaining high-frequency variation.
Direction logic
Determines whether the final line is rising or falling.
Chop gate
Determines whether that directional change is trustworthy enough to update the confirmed trend.
Trend direction calculation
The raw direction is determined by comparing the current trend line with its value several bars ago:
Bullish if trendLine > trendLine
Bearish if trendLine < trendLine
Neutral if equal
The Direction Lookback controls how much movement is required before the line is classified as rising or falling.
A one-bar comparison is extremely responsive but can detect tiny slope changes.
A longer comparison:
Measures movement across a wider interval.
Reduces sensitivity to one-bar flattening.
Produces more stable raw direction.
Raw trend versus confirmed trend
One of the most important design choices is that the script separates:
Raw trend
Confirmed trend
The raw trend reflects the current direction of the filtered line.
The confirmed trend is persistent and changes only when:
The raw trend points in a new direction.
The chop gate is open.
If the line turns but the gate is closed:
The active trend state remains unchanged.
The attempted flip can optionally be displayed as blocked.
This prevents every small line turn from immediately becoming a regime reversal.
Why a chop filter is needed
Even an advanced smoother can turn repeatedly during sideways markets.
Smoothing reduces noise, but it does not determine whether movement is:
Directional
Efficient
Large enough relative to volatility
A line can move upward and downward in a range while making almost no net progress.
The chop gate addresses this by evaluating two separate properties:
Directional efficiency
ATR-normalized slope
Efficiency Ratio
The first gate component measures how efficiently the trend line has moved over a selected window.
The calculation compares:
Net movement
Total movement
Net movement is:
|trendLine - trendLine |
Total movement is:
Sum of |bar-to-bar changes in trendLine|
The Efficiency Ratio is:
Efficiency = Net Movement / Total Movement
The result ranges approximately from 0 to 1.
Efficiency near 1
The line has moved mostly in one direction.
Example:
It advanced 10 units.
Its total path was approximately 11 units.
This indicates a clean directional move.
Efficiency near 0
The line has moved back and forth without achieving much net progress.
Example:
It travelled 20 units in total.
But ended only 1 unit from where it started.
This indicates chop.
Where the Efficiency Ratio comes from
The Efficiency Ratio is commonly associated with Perry Kaufman’s work on adaptive market analysis and the Kaufman Adaptive Moving Average.
Its purpose is to distinguish directional movement from noisy movement.
It does not measure the size of a move alone.
It measures the quality of the path.
This makes it highly suitable as a trend gate.
A market can be volatile but inefficient. It can move aggressively in both directions and still make little progress.
The Efficiency Ratio helps identify that distinction.
Minimum Efficiency
The Minimum Efficiency input determines the directional quality required for the efficiency condition to pass.
Lower values:
Allow more irregular movement.
Open the gate more frequently.
Produce earlier but noisier trend changes.
Higher values:
Require cleaner directional travel.
Block more sideways flips.
Produce fewer but more selective regime changes.
ATR-Normalized Slope
The second gate component measures how large the trend-line movement is relative to current market volatility.
It calculates:
|trendLine - trendLine | / ATR
This converts the line’s movement into ATR units.
Without normalization, a slope of 10 points could be:
Large for one instrument
Negligible for another
Large in a quiet regime
Small during extreme volatility
ATR normalization makes the slope more comparable across assets and regimes.
What normalized slope measures
The Efficiency Ratio asks:
Was the movement directionally clean?
ATR-normalized slope asks:
Was the movement large enough to matter?
These are different questions.
A move can be highly efficient but extremely small.
For example:
A perfectly smooth drift of only 0.02 ATR may not justify a new trend regime.
A move can also be large but inefficient:
A violent range may travel several ATRs while repeatedly reversing.
Using both filters gives a more complete view of trend quality.
Minimum ATR-Normalized Slope
The Minimum ATR-Normalized Slope defines the movement threshold.
Lower values:
Accept weaker slopes.
React sooner.
Allow more low-energy flips.
Higher values:
Require stronger displacement.
Reduce weak trend transitions.
Delay signals until movement becomes more meaningful.
Gate modes
The indicator provides four chop-gate modes.
Efficiency Ratio
Only directional efficiency is required.
Best suited for users who care primarily about whether movement is clean, regardless of its exact magnitude.
ATR-Normalized Slope
Only slope strength is required.
Best suited for users who want movement to exceed a volatility-adjusted threshold, even if the path is not perfectly efficient.
Both
Both conditions must pass:
Efficiency must be high enough.
Slope must be strong enough.
This is the strictest mode and generally provides the strongest chop rejection.
Either
Only one condition must pass.
This is more permissive:
A very clean slow trend may pass through efficiency.
A powerful but less orderly move may pass through slope.
It provides a balance between responsiveness and filtering.
Gate behavior
When the gate is open:
A new raw direction can update the trend state.
Bullish and bearish flips can be confirmed.
When the gate is closed:
The previous confirmed trend persists.
Attempted changes are blocked.
The display can dim, turn neutral, or hide.
This means the indicator behaves like a regime-holding system during chop.
It does not constantly reset to neutral. It retains the last confirmed direction until sufficient evidence supports a new one.
Blocked flips
A blocked flip occurs when:
The filtered line attempts to change direction.
The attempted direction differs from the confirmed trend.
The chop gate is closed.
The raw direction has just changed.
These can optionally be displayed as small X markers.
Blocked flips are useful because they show:
Where a basic slope indicator would have reversed.
Where the chop filter rejected that reversal.
How much signal noise the gate is removing.
They are not trade signals. They are diagnostic information.
Trend persistence
The trend variable is persistent.
Once bullish:
It remains bullish until a valid bearish change passes the gate.
Once bearish:
It remains bearish until a valid bullish change passes the gate.
This persistence is central to the design.
The indicator is not merely coloring every local slope. It is maintaining a confirmed market regime.
Display modes when the gate is closed
The indicator offers three ways to display gated conditions.
Dim
The current trend color remains visible but becomes transparent.
This communicates:
The last confirmed trend is still active.
Current conditions are not strong enough to confirm a new direction.
This is useful when you want regime continuity without overstating conviction.
Neutral
The trend line and candles switch to the selected gate color.
This communicates:
The directional regime is being withheld.
Current conditions are considered non-trending or uncertain.
Hide
The trend line disappears while the gate is closed.
This is the strictest visual mode.
It communicates:
No actionable trend state should be displayed during the gated condition.
Trend line coloring
The base color is determined by the confirmed trend:
Bullish trend uses the long color.
Bearish trend uses the short color.
Uninitialized state uses gray.
The gate display can then modify the final presentation.
This allows the chart to show:
Direction
Confirmation status
Chop-filter activity
without needing a separate panel.
Gradient fill
The indicator fills the area between price and the trend line.
When price is above the trend line:
A bullish gradient is displayed.
When price is below the trend line:
A bearish gradient is displayed.
The fill is stronger near the trend line and fades toward price.
This emphasizes the trend line as the structural reference.
The fill color follows the gate display state:
Full trend color when active
Dimmed during a closed gate in Dim mode
Neutral when configured
Hidden when the trend line is hidden
Trend glow
A soft glow is created around the filtered line using a small ATR-scaled distance.
The glow width is:
ATR(14) × 0.06
Using ATR ensures the glow remains visually proportional across assets and price scales.
The glow does not affect the calculation. It improves readability and reinforces the line as the central structural output.
Candle coloring
Candles can be colored using the confirmed trend state.
When the gate is open:
Bull trend produces bullish candles.
Bear trend produces bearish candles.
When the gate is closed:
Dim mode fades the existing trend color.
Neutral mode uses the gate color.
Hide mode removes the candle override.
This gives an immediate full-chart view of both trend and gate status.
Signal logic
Signals only occur when the confirmed trend changes.
Bullish flip
A bullish signal requires:
The active trend becomes bullish.
The previous trend was bearish.
The gate accepted the change.
Bearish flip
A bearish signal requires:
The active trend becomes bearish.
The previous trend was bullish.
The gate accepted the change.
This is more selective than simply detecting a change in line slope.
How to interpret the indicator
Bullish confirmed regime
A bullish regime means:
The median-filtered and low-pass-smoothed trend line is rising.
The move satisfied the selected chop-filter conditions when the regime changed.
The last accepted direction remains bullish.
Bearish confirmed regime
A bearish regime means:
The final trend line is falling.
The bearish change passed the selected quality gate.
The last accepted direction remains bearish.
Gate closed in an existing trend
This means:
The market is no longer moving with sufficient efficiency or slope.
A new reversal cannot currently be confirmed.
The previous regime remains stored.
This often occurs during:
Consolidation
Pullbacks
Low-volatility drift
Transition phases
Repeated blocked flips
Repeated blocked changes suggest:
The filtered line is oscillating.
Directional quality is weak.
A normal trend-following system would likely be whipsawing.
This is exactly the environment the gate is designed to avoid.
How to use it in practice
1. Directional regime filter
Use the confirmed trend to filter other setups:
Favor long trades during bullish regimes.
Favor short trades during bearish regimes.
Reduce activity when the gate is closed.
2. Trend-following entries
Bullish and bearish flips can be used as directional entry triggers, especially when confirmed by:
Price structure
Breakouts
Volume expansion
Higher-timeframe alignment
3. Pullback framework
During an established trend:
Price returning toward the trend line may represent a pullback.
If the gate remains closed but the trend does not flip, the move may be consolidation rather than reversal.
If the opposite direction eventually passes the gate, the regime has changed more meaningfully.
4. Chop avoidance
The most direct use is avoiding repeated entries during low-quality conditions.
When the display is dim, neutral, or hidden:
Reduce confidence in new trend signals.
Wait for efficiency or slope to recover.
5. Diagnostic comparison
Enable blocked flips to see how often the raw trend attempts to reverse without confirmation.
This helps tune:
Efficiency threshold
Slope threshold
Gate mode
Input guide
Source
Selects the price series used by the median cascade.
Close is the standard choice.
Alternatives such as hl2 or hlc3 may produce a slightly smoother structural input.
Cascade Stages
Controls how many median filters are used.
1: responsive
2: balanced
3: strongest noise rejection
Median Stage Lengths
Control the window used at each stage.
Shorter values:
Preserve responsiveness.
Remove only very short-duration noise.
Longer values:
Produce stronger structural filtering.
Delay shorter turns.
Low-Pass Length
Controls the two-pole Super Smoother.
Lower:
Faster
More reactive
Higher:
Smoother
More conservative
Direction Lookback
Controls how far back the current line is compared when determining raw direction.
Lower:
Faster slope changes
Higher:
More stable directional measurement
Efficiency Length
Controls the window used to measure net movement versus total path movement.
Shorter:
More responsive efficiency reading
More sensitive to recent chop
Longer:
More stable directional-quality assessment
Minimum Efficiency
Controls how clean the directional path must be.
Higher values make the gate stricter.
Slope Length
Controls the interval across which trend-line movement is measured.
Slope ATR Length
Controls the ATR baseline used to normalize slope.
Minimum ATR-Normalized Slope
Controls the minimum volatility-adjusted displacement required.
Higher values require stronger movement.
Tuning examples
Faster trend configuration
1 or 2 median stages
Short median windows
Lower Super Smoother length
Direction Lookback of 1 or 2
Either gate mode
Lower efficiency and slope thresholds
Balanced configuration
2 or 3 median stages
Progressive windows such as 3, 5, 7
Moderate Super Smoother length
Both gate mode
Moderate thresholds
Conservative configuration
3 stages
Longer median windows
Higher Super Smoother length
Longer Direction Lookback
Both gate mode
Higher minimum efficiency and slope
How this differs from a normal moving average
A standard moving average:
Uses linear averaging.
Responds directly to outlier magnitude.
Changes direction whenever its slope changes.
Median Cascade Trend:
Uses nonlinear outlier-resistant preprocessing.
Applies a proper recursive low-pass stage.
Separates raw direction from confirmed regime.
Blocks changes during inefficient or weak movement.
How this differs from a normal median filter
A basic median filter only removes impulse noise.
This indicator extends the idea by adding:
Multiple median stages
Low-pass smoothing
Direction measurement
Efficiency gating
Volatility-normalized slope gating
Persistent trend states
Signals and alerts
It is not simply a median-smoothed line. It is a complete trend-regime system built on median preprocessing.
How this differs from a Supertrend
A Supertrend uses ATR bands around price and changes state when price crosses the trailing boundary.
Median Cascade Trend does not use a volatility band to define direction.
Instead:
Direction comes from the slope of the filtered trend line.
ATR is used only to normalize slope and scale visuals.
Trend changes are controlled by movement quality rather than price crossing a stop band.
Strengths
Strong rejection of isolated price spikes
Preserves broader structural movement
Combines nonlinear and linear filtering
Separates raw turns from confirmed trend changes
Configurable chop rejection
Volatility-normalized slope testing
Persistent directional regimes
Blocked-flip diagnostics
Fully causal calculation
Limitations
Strong filtering can delay genuine reversals.
Long median windows may suppress shorter trend legs.
Strict gate settings can hold the previous regime too long.
Loose gate settings reduce the benefit of chop filtering.
Median filters can produce stepped transitions before low-pass smoothing.
The indicator remains reactive rather than predictive.
Best use cases
Median Cascade Trend is particularly suited for:
Trend filtering in noisy markets
Reducing false reversals caused by wicks
Swing-trading regime identification
Filtering entries from faster systems
Dynamic trend-structure visualization
Avoiding sideways-market whipsaws
It can be applied across:
Equities
Indices
Futures
Forex
Cryptocurrency
Commodities
Alerts
The indicator provides alerts for:
Confirmed bullish trend changes
Confirmed bearish trend changes
Trend changes blocked by the chop filter
The blocked-flip alert is especially useful for monitoring when the line attempts to reverse but market quality remains insufficient.
Summary
Median Cascade Trend is a multi-stage trend extraction system designed to reject impulsive market noise before determining direction. It first applies up to three causal median filters, progressively removing isolated spikes and short-duration disturbances. The cleaned series is then passed through a two-pole Super Smoother to extract a stable low-frequency trend line.
Rather than accepting every change in slope, the indicator evaluates the quality of the movement using directional efficiency and ATR-normalized slope. Depending on the selected gate mode, trend changes can require clean directional travel, sufficient volatility-adjusted displacement, or both.
This produces a persistent trend state that changes only when the filtered line turns and the surrounding movement is strong enough to justify the reversal. The final result is a robust trend-following framework that combines outlier rejection, low-pass smoothing, directional-quality measurement, and chop suppression into a single overlay.
지표

NLMS Volatility Trail [BackQuant]NLMS Volatility Trail
Overview
NLMS Volatility Trail is an adaptive trend-following overlay that combines a machine-learning style adaptive filter with a volatility-based trailing structure. It is built around the Normalized Least Mean Squares (NLMS) algorithm, then converts that adaptive estimate into an ATR-based trailing line designed to follow directional regimes while filtering out minor noise.
The indicator has two core layers:
An NLMS adaptive filter , which learns a dynamic price estimate from prior bars.
An ATR volatility trail , which converts that learned estimate into a step-like directional trailing structure.
The goal is to produce a trend line that is more adaptive than a traditional moving average and more structured than a raw adaptive filter. The NLMS engine learns the underlying price path, while the ATR trail adds volatility-aware confirmation so trend shifts only occur when the adaptive estimate moves meaningfully.
Core idea
Most trend filters use fixed smoothing rules. An EMA, SMA, WMA, or HMA always applies the same mathematical weighting scheme regardless of whether the market is trending, ranging, expanding, or compressing.
NLMS is different. It continuously updates its internal weights based on prediction error.
This means the filter is not just averaging price. It is constantly asking:
How well did the previous weighting structure predict the current bar?
How large was the error?
How should the weights adjust to reduce future error?
The second layer then takes that adaptive estimate and applies an ATR-based trailing mechanism around it. This creates a volatility-adjusted trend trail that reacts to confirmed shifts while ignoring smaller movements that do not exceed the range structure.
What NLMS is
NLMS stands for Normalized Least Mean Squares . It is an adaptive filtering algorithm from digital signal processing. It is closely related to the original LMS algorithm developed by Bernard Widrow and Ted Hoff, which became one of the foundational online learning methods used in adaptive systems.
Adaptive filters have historically been used in:
Noise cancellation
Echo cancellation
Telecommunications
Radar and sonar processing
Signal prediction
Control systems
The basic purpose is to estimate or predict a signal while continuously adapting to changing conditions.
In trading terms, this indicator uses NLMS to build a learned estimate of price from prior bars.
How the NLMS filter works
The filter uses a set of historical inputs called taps .
If taps = 72, the model uses the previous 72 bars:
source
source
source
...
source
Each tap has a learned weight.
The prediction is calculated as:
prediction = w1 × source + w2 × source + ... + wM × source
The filter then compares the prediction to the actual current source:
error = source - prediction
That error drives the weight update.
If the prediction was poor, the weights adjust more.
If the prediction was accurate, the weights adjust less.
This creates an adaptive estimate that evolves with market behavior.
Why it is normalized
The normal LMS algorithm updates weights based on the raw input and prediction error. The issue is that if the input signal becomes large or volatile, updates can become unstable.
NLMS solves this by dividing the update by the input power:
power = sum(source ²)
The update becomes:
w = w + (μ / (ε + power)) × error × input
This normalization makes the learning process more stable across different volatility environments.
When the input power is high:
Updates are scaled down.
The filter avoids overreacting.
When the input power is low:
Updates are allowed to remain meaningful.
This is why NLMS is better suited to markets than a basic adaptive filter. Markets constantly shift between quiet and volatile regimes.
Weight initialization
The script initializes all weights equally:
weight = 1 / M
This means the filter starts with an SMA-like prior. Before learning begins, every historical bar contributes equally.
Over time, the filter adapts away from that equal-weight baseline and learns its own weighting structure.
Inputs that control the NLMS engine
Filter Taps (M)
Controls how many historical bars the model learns from.
Higher taps:
More memory
Smoother adaptive estimate
Slower response to regime change
Lower taps:
Less memory
Faster reaction
More noise sensitivity
Step Size (μ)
Controls the learning rate.
Lower μ:
Slower learning
Smoother output
More stable
Higher μ:
Faster learning
More responsive
Can become noisy if too aggressive
This is one of the most important settings. It controls how quickly the model changes its internal weights.
Regularization (ε)
Prevents instability when input power is very low.
It acts as a stabilizer in the denominator:
ε + power
Higher values make updates more conservative.
Lower values allow stronger adaptation but can become less stable in quiet conditions.
From adaptive filter to volatility trail
The raw NLMS output is not plotted directly as the main trend line. Instead, it is passed into a volatility trailing structure.
The script builds an ATR band around the NLMS estimate:
Upper band = NLMS output + ATR × factor
Lower band = NLMS output - ATR × factor
Then it creates a trailing value that only updates when the NLMS band structure forces it to move.
This creates a trail that behaves similarly to a volatility stop, but the center is not price or hl2. It is the learned NLMS estimate .
ATR volatility trail logic
The trail starts from the NLMS output, then carries forward its previous value:
nlmsAtr := previous nlmsAtr
Then:
If lower band rises above the trail, the trail moves up.
If upper band falls below the trail, the trail moves down.
This creates a directional trailing structure:
In bullish regimes, the trail ratchets upward.
In bearish regimes, the trail ratchets downward.
It filters out small movements because price must move enough relative to ATR and the adaptive estimate to change the trail direction.
Why combine NLMS with ATR
NLMS alone gives an adaptive estimate, but it can still wiggle as the model learns.
ATR alone gives volatility structure, but it is usually tied to raw price and fixed smoothing.
Combining them gives:
Adaptive intelligence from NLMS.
Volatility confirmation from ATR.
Cleaner trend state transitions.
Less dependence on fixed moving-average assumptions.
The NLMS model learns the underlying price behavior, while ATR decides whether movement is large enough to matter.
Trend direction
Trend flips are detected from the trail itself:
Bullish when nlmsAtr crosses above its previous value.
Bearish when nlmsAtr crosses below its previous value.
This means signals are generated when the volatility trail changes direction, not when price simply crosses the line.
That is important because:
The trail must structurally move.
The signal is tied to confirmed trail direction.
Noise around the line does not automatically create a flip.
Visual design
The indicator includes several visual layers.
Main trail line
The central plotted line is the NLMS ATR trail. It changes color based on the current trend state:
Green for bullish trail direction.
Red for bearish trail direction.
Gray before a trend state is established.
Gradient fill
The script fills the space between price and the trail:
If price is above the trail, bullish fill is shown.
If price is below the trail, bearish fill is shown.
The fill is stronger near the trail and fades toward price, making the trail feel like the active structural reference.
Trail glow
A soft glow is drawn around the trail using a small ATR offset:
glow = ATR(14) × 0.06
This highlights the trail visually without cluttering the chart.
Trend candles
Candles are colored by trend state:
Bullish trend = bullish candles.
Bearish trend = bearish candles.
This allows the script to function as a complete regime overlay.
How to interpret the indicator
Bullish state
A bullish state occurs when the NLMS volatility trail turns upward.
This suggests:
The adaptive filter is shifting higher.
The ATR trail has confirmed upward structure.
Trend pressure has turned bullish.
Bearish state
A bearish state occurs when the NLMS volatility trail turns downward.
This suggests:
The adaptive estimate is shifting lower.
The volatility trail has confirmed downside structure.
Trend pressure has turned bearish.
Price above the trail
Generally indicates bullish structure.
Price below the trail
Generally indicates bearish structure.
But the most important signal is the direction of the trail itself, not every price touch.
How to use it in practice
1) Trend following
Use the trail direction as the primary bias:
Favor longs when the trail is bullish.
Favor shorts when the trail is bearish.
2) Dynamic support/resistance
The trail can act like a dynamic structural level:
In uptrends, pullbacks toward the trail can act as support.
In downtrends, rallies toward the trail can act as resistance.
3) Trade management
The trail can be used as:
A trailing stop guide.
A regime invalidation level.
A trend continuation reference.
4) Regime filtering
Because the line adapts using NLMS and only flips when the volatility trail turns, it can be used to filter other entries:
Take only long setups during bullish trail regimes.
Take only short setups during bearish trail regimes.
Avoid countertrend trades when the trail is strongly directional.
Difference from normal Supertrend or ATR trails
A normal ATR trail is usually built directly from price or hl2.
This indicator is different because the trail is built around an adaptive learned estimate.
That means:
The centerline is not raw price.
It is not a fixed moving average.
It is a continuously learned NLMS estimate.
So the trail has a different character:
More adaptive than a standard moving average trail.
More stable than a raw price-based ATR stop.
More responsive to changing market structure than fixed filters.
Difference from the NLMS Adaptive Trend Filter
The NLMS Adaptive Trend Filter plots the learned estimate directly and reads trend from its slope.
NLMS Volatility Trail goes one step further:
It uses the learned estimate as the base.
Then wraps it with ATR structure.
Then turns that into a trailing regime line.
So this version is more structure-oriented and better suited for trailing trend behavior.
Parameter tuning
Taps
Use higher taps for smoother trend structure.
Use lower taps for faster adaptation.
Step Size
Use lower step size for stability.
Use higher step size for responsiveness.
Regularization
Use higher regularization when the filter feels unstable.
Use lower regularization when the filter is too sluggish.
ATR Period
Controls volatility estimate:
Shorter = more reactive trail.
Longer = smoother trail.
ATR Factor
Controls band width:
Higher factor = wider trail, fewer flips.
Lower factor = tighter trail, more flips.
Strengths
Combines adaptive filtering with volatility trailing logic.
Learns from market structure instead of using fixed weights.
Uses ATR to reduce noise and confirm meaningful movement.
Good for trend following and trailing stop frameworks.
Visually clean with gradient fill and candle coloring.
Limitations
Still reactive, not predictive.
Can lag during violent reversals.
High learning rates may create noise.
Low ATR factors may cause whipsaws.
Requires tuning for timeframe and asset volatility.
Summary
NLMS Volatility Trail combines an adaptive NLMS predictor with an ATR-based trailing structure. The NLMS layer continuously learns a dynamic estimate of price from historical bars, while the ATR trail converts that estimate into a cleaner directional regime line. This makes the indicator more adaptive than a traditional moving average and more structured than a raw adaptive filter. It is best used as a trend-following overlay, dynamic support/resistance guide, and volatility-aware trailing framework.
지표

NLMS Adaptive Trend Filter [BackQuant]NLMS Adaptive Trend Filter
Overview
The NLMS Adaptive Trend Filter is a machine learning inspired trend-following indicator built around one of the most important adaptive filtering algorithms in signal processing: the Normalized Least Mean Squares (NLMS) filter .
Unlike traditional moving averages that use fixed weighting schemes, the NLMS filter continuously learns from incoming market data and updates its internal coefficients in real time. Rather than assuming that price behavior remains constant, the filter attempts to adapt its structure as market conditions evolve.
This approach originates from the field of digital signal processing, where adaptive filters have been used for decades in applications such as:
• Telecommunications
• Radar systems
• Echo cancellation
• Noise reduction
• Speech processing
• Control systems
• Financial signal extraction
The goal of this indicator is to bring one of these adaptive filtering concepts into market analysis by creating a trend model that continually adjusts itself based on prediction error rather than relying on static averaging methods.
Historical Background
The roots of the NLMS filter can be traced back to the work of Bernard Widrow and Ted Hoff in the late 1950s and early 1960s.
While working at Stanford University, they developed what became known as the:
Least Mean Squares (LMS) Algorithm
The LMS algorithm was revolutionary because it provided a computationally simple method for training adaptive systems using gradient descent.
Rather than solving a complex optimization problem all at once, the LMS algorithm updates its weights incrementally after each observation.
The basic concept was:
1. Make a prediction.
2. Measure the prediction error.
3. Adjust the model slightly.
4. Repeat indefinitely.
This idea eventually became one of the foundational concepts behind modern machine learning and online optimization.
Many modern neural networks still rely on the same underlying principle:
Error → Gradient → Weight Update
The LMS algorithm later evolved into several variants, one of the most important being:
Normalized Least Mean Squares (NLMS)
NLMS improves stability by scaling weight updates according to the energy of the input signal.
This prevents learning rates from becoming too aggressive during high-volatility periods and too weak during low-volatility periods.
As a result, NLMS became one of the most widely used adaptive filtering algorithms in engineering.
What Makes NLMS Different From Moving Averages?
Traditional moving averages use predetermined weights.
For example:
Simple Moving Average (SMA)
Every observation receives equal weight.
Example:
20-period SMA
Each bar contributes:
1 / 20 = 5%
regardless of market conditions.
Exponential Moving Average (EMA)
Recent observations receive more weight.
The weighting structure is fixed and never changes.
Weighted Moving Average (WMA)
Uses linearly decreasing weights.
Again, the weighting scheme is fixed.
The problem is that markets do not operate under fixed conditions.
Volatility changes.
Trend persistence changes.
Noise levels change.
Market structure changes.
Yet traditional moving averages continue using the exact same weighting model.
NLMS takes a different approach.
Instead of assigning permanent weights, it learns them dynamically.
The filter constantly asks
"What weighting structure would have predicted the current market best?"
It then updates itself accordingly.
The Core Idea Behind Adaptive Filters
Imagine trying to forecast today's price using the previous 20 bars.
A normal moving average assumes a fixed weighting pattern.
An adaptive filter attempts to learn the optimal weighting pattern.
At every bar:
• A prediction is generated.
• Actual price is observed.
• Prediction error is measured.
• Weights are adjusted.
The process repeats indefinitely.
Over time, the filter learns which historical observations are most useful and which are less important.
Understanding Filter Taps
One of the most important concepts in adaptive filtering is the idea of:
Taps
A tap is simply a historical observation used as an input.
If the indicator uses:
20 taps
it means:
Price
Price
Price
...
Price
are all being used to generate the prediction.
Each tap receives a learned weight.
Instead of:
Current Estimate =Average of past 20 bars
the filter becomes:
Current Estimate =
(w1 × Price ) +
(w2 × Price ) +
(w3 × Price )
...
(w20 × Price )
The weights are continuously adjusted through learning.
How Prediction Works
The indicator attempts to estimate current price using previous observations.
Mathematically:
Prediction = Σ(weight × historical price)
This prediction becomes the filter output.
If the prediction is accurate:
Weights change very little.
If the prediction is poor:
Weights adjust more aggressively.
This allows the model to gradually adapt to changing market conditions.
Prediction Error
The engine measures:
Error = Actual Price − Predicted Price
This error drives all learning.
Large error means:
The model is wrong.
Small error means:
The model is performing well.
The objective is to minimize prediction error over time.
The LMS Learning Rule
The original LMS update rule is:
New Weight =Old Weight + Learning Rate × Error × Input
This is effectively a form of gradient descent.
The filter moves its weights in the direction that reduces future prediction error.
This is conceptually identical to many machine learning optimization methods.
Why Normalization Matters
The original LMS algorithm has a weakness.
When input values become very large:
Weight updates can become unstable.
This is particularly problematic in financial markets where volatility constantly changes.
NLMS solves this problem by normalizing updates according to signal energy.
Instead of:
Weight Update ∝ Error
it becomes:
Weight Update ∝ Error / Signal Power
This creates adaptive scaling.
When volatility expands:
Updates automatically shrink.
When volatility contracts:
Updates automatically expand.
This improves stability significantly.
How the Indicator Uses NLMS
The script implements an online one-step predictor.
For every new bar:
1. Previous M bars are gathered.
2. Current price is predicted.
3. Prediction error is calculated.
4. Weight vector is updated.
5. New estimate becomes available.
This process occurs continuously as new data arrives.
Because no future data is used, the filter remains fully causal and suitable for live trading.
Weight Initialization
Initially all weights are equal:
1 / M
This effectively starts the model as a simple moving average.
Over time the filter learns a custom weighting structure based on market behavior.
The initial equal-weight state acts as a neutral prior.
Step Size (μ)
The learning rate controls how aggressively the filter adapts.
Lower values:
• More stable
• Smoother output
• Slower adaptation
Higher values:
• Faster adaptation
• More responsiveness
• Greater noise sensitivity
Think of μ as controlling the intelligence speed of the model.
Small values make it conservative.
Large values make it reactive.
Regularization (ε)
Regularization prevents division by very small values.
Without it:
Periods of extremely low signal power could create unstable updates.
Regularization improves numerical stability and robustness.
It acts as a safety mechanism for the learning process.
Output Smoothing
After the NLMS estimate is generated, an optional EMA can be applied.
This smoothing is not part of the NLMS algorithm itself.
It exists purely for visual clarity.
The raw adaptive filter already contains the learning logic.
The smoothing stage simply reduces small fluctuations.
Setting smoothing to 1 effectively disables it.
Trend Detection
Trend direction is derived from the slope of the adaptive filter.
Bullish:
NLMS Output > Previous Output
Bearish:
NLMS Output < Previous Output
This creates a directional state machine.
Unlike crossover systems, trend changes occur whenever the adaptive estimate changes slope.
Bullish Flips
A bullish signal occurs when:
Trend changes from bearish to bullish.
This means the adaptive filter has transitioned from declining to rising.
Bearish Flips
A bearish signal occurs when:
Trend changes from bullish to bearish.
This means the adaptive filter has transitioned from rising to falling.
Visual Components
The indicator includes several visualization layers.
Adaptive Filter Line
The main output of the NLMS model.
This represents the learned trend estimate.
Gradient Fill
The space between price and filter is colorized.
Price Above Filter:
Bullish shading.
Price Below Filter:
Bearish shading.
This provides immediate visual context regarding trend alignment.
Edge Glow
An ATR-based glow surrounds price.
This helps emphasize directional conditions while improving chart readability.
Trend Candles
Candles can optionally inherit trend coloration.
Green:
Adaptive trend rising.
Red:
Adaptive trend falling.
This allows traders to visualize the model's directional state directly on price.
How It Differs From Traditional Trend Filters
Most trend indicators answer:
"What is the average price?"
NLMS attempts to answer:
"What weighting structure best predicts current price?"
This distinction is extremely important.
The indicator is not simply smoothing price.
It is continuously learning how price behaves.
Traditional indicators use fixed mathematics.
NLMS uses adaptive mathematics.
Strengths
• Self-adjusting weighting structure.
• Adapts to changing market conditions.
• Based on established signal-processing theory.
• Stable due to normalization.
• Less reliant on arbitrary moving-average formulas.
• Learns continuously.
• Fully causal and non-lookahead.
Limitations
• Not a predictive model in the forecasting sense.
• Can still lag during major regime shifts.
• Excessively large learning rates may introduce noise.
• Small tap counts can become unstable.
• Large tap counts can become sluggish.
Like all adaptive systems, there is a tradeoff between responsiveness and stability.
Best Use Cases
The NLMS Adaptive Trend Filter is particularly effective for:
• Trend identification.
• Regime classification.
• Dynamic support/resistance visualization.
• Adaptive trend following.
• Noise reduction.
• Signal confirmation.
Summary
The NLMS Adaptive Trend Filter applies one of the most important adaptive algorithms in modern signal processing to financial markets. Rather than relying on fixed moving-average weights, it continuously learns from prediction error and updates its internal model in real time. Built upon the pioneering work of Widrow and Hoff, the indicator combines adaptive filtering, normalized gradient descent, and online learning principles into a practical trend-following tool that evolves alongside changing market conditions. The result is a trend model that is fundamentally different from traditional moving averages, not because it smooths price differently, but because it learns how to smooth price as new information arrives.
지표

Volatility Gated Supertrend [BackQuant]Volatility Gated Supertrend
Overview
Volatility Gated Supertrend is a regime-aware trend-following indicator built around a modified Supertrend engine with an integrated volatility filter . Unlike a traditional Supertrend, which flips direction whenever price crosses its trailing bands, this version introduces a gating mechanism that can block trend reversals during low-volatility conditions .
The purpose of the indicator is simple:
Keep the responsiveness and structure of a Supertrend.
Reduce false flips during sideways or compressed conditions.
Allow trend transitions primarily when volatility is expanding enough to justify participation.
The result is a smoother and more selective trend engine designed to suppress whipsaws while still reacting to meaningful directional movement.
The full source structure for the indicator can be referenced here: :contentReference {index=0}
Core idea
Traditional Supertrend indicators work well during directional markets but struggle in compressed environments:
Price repeatedly crosses the trailing bands.
Trend direction flips too frequently.
False reversals appear during chop.
This indicator attempts to solve that problem by asking:
“Is there enough volatility expansion to justify accepting a new trend?”
Instead of blindly allowing every flip, the indicator measures:
Current volatility,
Baseline volatility,
Relative expansion or compression.
Only when volatility conditions are sufficient does the trend engine allow a directional transition.
What the Supertrend is
The Supertrend is a volatility-based trailing trend indicator built from:
ATR (Average True Range)
A central price source
A directional trailing stop structure
The classic logic:
Upper band = price source + ATR × multiplier
Lower band = price source − ATR × multiplier
These bands trail price dynamically:
In bullish conditions, the lower band ratchets upward.
In bearish conditions, the upper band ratchets downward.
When price crosses one of the bands:
The trend flips direction.
This creates a clean directional regime model.
How this version differs
The major difference is the volatility gate .
A normal Supertrend asks:
“Did price cross the band?”
This indicator asks:
“Did price cross the band, and is volatility strong enough to trust the move?”
That additional filter dramatically changes behavior in sideways conditions.
ATR and volatility structure
The indicator uses two ATR measurements:
Fast ATR → current short-term volatility
Slow ATR → baseline long-term volatility
The core ratio:
Volatility Ratio = Fast ATR / Slow ATR
Interpretation:
Ratio above threshold → volatility expansion
Ratio below threshold → volatility compression
This becomes the gate logic.
Volatility Gate Logic
The gate opens only when:
Fast ATR / Slow ATR ≥ Gate Threshold
If volatility is too compressed:
The gate closes.
Trend flips are blocked.
Importantly:
The Supertrend bands still calculate normally.
Price can still cross them.
But the directional state will not update while the gate is closed.
This distinction matters because it means:
The market may technically trigger a reversal,
But the indicator intentionally ignores it if volatility conditions are weak.
Why this helps
Most trend-following systems fail in chop because:
Small meaningless moves trigger directional flips.
There is insufficient range expansion.
The market lacks trend persistence.
By requiring volatility confirmation:
Weak reversals are filtered out.
Trend state becomes more stable.
Noise is reduced.
This makes the indicator particularly useful during:
Low-volatility consolidations,
Mean-reverting conditions,
Slow drifting ranges.
Band construction
The indicator uses:
hl2 as the central source,
ATR for dynamic width,
A configurable multiplier for sensitivity.
Formulas:
Upper Band = hl2 + ATR × multiplier
Lower Band = hl2 − ATR × multiplier
The trailing logic prevents the bands from moving backward unnecessarily:
Bullish lower band only rises.
Bearish upper band only falls.
This creates the staircase-style trailing structure common in Supertrend systems.
Trend state
Trend direction is binary:
1 = bullish
-1 = bearish
A raw bullish flip occurs when:
Close > trailing upper band
A raw bearish flip occurs when:
Close < trailing lower band
However:
The trend only updates if the volatility gate is open.
This is the defining behavior of the script.
Blocked flips
One of the most important features is the visualization of blocked signals .
When:
Price crosses a band,
But volatility is insufficient,
The script:
Plots an X-cross marker,
Keeps the existing trend state,
Refuses the flip.
This gives traders visibility into:
Potential but unconfirmed reversals,
Areas of weak participation,
Fake breakouts or low-energy transitions.
Visual behavior
Trend band
The active trailing band changes color based on trend direction:
Bullish → bullish color
Bearish → bearish color
Gate closed → gated color (dimmed)
Trend fill
The script fills the space between price and the active band:
Bullish fill during bullish regimes
Bearish fill during bearish regimes
This creates a cleaner directional overlay.
Outer glow
An additional glow layer expands slightly beyond the trend band:
Adds directional emphasis,
Improves trend readability,
Visually reinforces active regime.
When the gate closes:
The band and candles dim.
This visually communicates:
“The trend engine is currently suppressing flips.”
Candle coloring
Candles can optionally inherit the trend state:
Bullish regime → bullish candles
Bearish regime → bearish candles
Gate closed → dimmed neutral appearance
This allows the indicator to function as a full-chart regime overlay.
Signal logic
Bullish signal
Occurs when:
Trend flips from bearish to bullish,
AND the gate is open.
Bearish signal
Occurs when:
Trend flips from bullish to bearish,
AND the gate is open.
Blocked signal
Occurs when:
A raw flip condition appears,
BUT volatility ratio is below threshold.
This distinction is important:
A blocked signal is not ignored information.
It is a rejected transition.
How to interpret the gate
Gate open
Volatility is active.
Market expansion is sufficient.
Trend flips are allowed.
Gate closed
Market is compressed.
Conditions are likely choppy.
Trend reversals are suppressed.
This effectively turns the indicator into a:
Trend-following system during expansion,
Trend-holding system during compression.
Why ATR ratio works well
ATR ratio is a powerful regime detector because it measures:
Current volatility relative to normal volatility.
Not just:
“Is volatility high?”
But:
“Is volatility high relative to its recent baseline?”
This adaptive behavior allows the gate to work across:
Different assets,
Different timeframes,
Different volatility environments.
Input guide
ATR Multiplier
Controls band width:
Higher = wider bands, fewer flips
Lower = tighter bands, more sensitivity
ATR Length
Controls volatility calculation for the Supertrend itself.
Fast ATR
Short-term volatility measure.
Slow ATR
Long-term baseline volatility measure.
Gate Threshold
Controls how strict the gate is:
Lower threshold = more permissive
Higher threshold = more restrictive
Example:
0.6 → allows more flips
1.0 → requires current volatility to match baseline
1.2 → requires expansion regime
Strengths
Reduces Supertrend whipsaws in chop.
Adds regime awareness.
Uses adaptive volatility filtering.
Clean trend visualization.
Blocked-signal logic provides extra context.
Limitations
Can delay reversals during early expansion.
Very high thresholds may suppress legitimate transitions.
Still fundamentally a trend-following system.
Not designed for low-volatility mean reversion trading.
Best use case
Volatility Gated Supertrend works best as:
A directional regime filter,
A swing trend overlay,
A volatility-aware trend confirmation tool,
A way to suppress noise during consolidations.
It is particularly useful for traders who:
Like Supertrend logic,
But dislike how often it flips in sideways markets.
Summary
Volatility Gated Supertrend extends the classic Supertrend framework by introducing a volatility-aware gating engine that blocks trend reversals during compressed market conditions. By comparing fast ATR against slow ATR, the script determines whether enough volatility expansion exists to justify a directional transition. The result is a cleaner, more stable trend system that retains the strengths of Supertrend logic while dramatically reducing whipsaws during low-energy market regimes. 지표

Volatility Hull Ribbon [BackQuant]Volatility Hull Ribbon
Overview
Volatility Hull Ribbon is a trend-following overlay built from a Hull-style moving average that replaces traditional volume weighting with volatility weighting . Instead of weighting price by traded volume, this indicator weights price by the absolute True Range of each bar, meaning bars with larger range expansion have more influence on the final trend estimate.
The goal is to create a smoother but responsive trend line that pays more attention to bars where the market actually moved with force. It then plots this volatility-weighted Hull structure as either a clean line or a ribbon-style band, with gradient fill, candle coloring, and long/short flip markers.
At a high level, the indicator does three things:
Builds a volatility-weighted moving average using True Range as the weighting source.
Applies Hull-style lag reduction to produce a faster trend-following curve.
Visualizes trend direction using slope, ribbon fill, candles, and flip signals.
Core idea
Most moving averages treat each bar equally or weight only by time. That means a quiet candle and a high-range expansion candle can have similar influence depending on the MA type.
Volatility Hull Ribbon takes a different approach:
Bars with larger True Range are treated as more important.
Bars with smaller True Range have less influence.
Recent bars are also weighted more heavily than older bars.
This creates a trend estimate that responds more strongly when the market expands, while remaining smoother during lower-energy movement.
What “volatility-weighted” means here
The custom weighting function uses:
Price source
Absolute True Range
A decreasing time weight
For each bar inside the lookback:
Weighted price contribution = source * abs(True Range ) * recency weight
Weight contribution = abs(True Range ) * recency weight
Then:
Volatility-weighted average = weighted price sum / weighted True Range sum
So price movement on wide-range bars matters more than price movement on quiet bars.
Why True Range is used
True Range captures more than just high-low movement. It accounts for gaps and previous close displacement. This makes it a broader volatility proxy than simple candle range.
Using True Range as the weight means the filter gives more importance to bars where:
Range expanded,
Price displaced aggressively,
Volatility increased,
Market participation likely intensified.
This is useful because strong trend moves often occur during volatility expansion, not during quiet drift.
Hull-style construction
The indicator then applies a Hull-style transformation to the volatility-weighted average.
The structure is:
VWHMA = VWMA_TR( 2 * VWMA_TR(src, len / 2) - VWMA_TR(src, len), sqrt(len) )
Where VWMA_TR means the custom True-Range-weighted moving average.
This follows the same logic as the classic Hull Moving Average:
Use a faster half-length average.
Use a slower full-length average.
Subtract the lagging component.
Smooth the result with sqrt(length).
The difference is that every smoothing step is volatility-weighted instead of standard weighted-average based.
Why this matters
A classic Hull Moving Average is already designed to reduce lag. This version modifies the internal weighting so the curve becomes more sensitive to volatility-backed price movement .
That means:
Large expansion bars can pull the filter faster.
Weak low-range chop has less effect.
Trend changes during strong movement can be reflected more clearly.
Trend detection
Trend direction is based on the slope of the VWHMA:
Bullish when VWHMA > VWHMA
Bearish when VWHMA < VWHMA
This is a simple but effective regime definition:
Rising volatility-weighted Hull = bullish trend pressure.
Falling volatility-weighted Hull = bearish trend pressure.
The script uses this slope state to color:
The main line,
The ribbon fill,
Optional candles,
Signal markers.
Ribbon mode
When “Plot as Band?” is enabled, the script creates a second line:
onebar_off = WMA(VWHMA , 10)
This is a delayed and smoothed version of the VWHMA. The area between the current VWHMA and this offset line becomes the ribbon.
Interpretation:
Ribbon expansion shows separation between current trend structure and its delayed reference.
Ribbon compression shows trend slowing or flattening.
A clean flip in the ribbon often coincides with trend transition.
The ribbon is not a volatility band. It is a trend displacement ribbon built from the difference between the current VWHMA and its delayed smoothed version.
Gradient fill logic
The fill is directional:
If VWHMA is above the offset line, fill intensity is stronger near the VWHMA and fades toward the offset.
If VWHMA is below the offset line, the gradient reverses.
This creates a cleaner visual than a flat fill because it emphasizes the active side of the ribbon.
In practice:
Strong bright ribbon = trend line leading the delayed reference.
Faded/narrow ribbon = weaker separation.
Ribbon reversal = trend pressure has shifted.
Signal logic
Signals are generated when the VWHMA slope changes direction:
Long signal: crossover(VWHMA, VWHMA )
Short signal: crossunder(VWHMA, VWHMA )
This means:
A long signal prints when the current VWHMA turns upward relative to the previous value.
A short signal prints when the current VWHMA turns downward.
These are slope-flip signals, not price crossover signals.
Important interpretation
A signal does not mean “buy blindly” or “sell blindly.” It means the volatility-weighted trend estimate has changed direction. The quality of the signal depends on:
Market structure,
Higher timeframe trend,
Volatility conditions,
Whether the ribbon is expanding or compressing.
Candle coloring
When enabled, candles are painted according to the VWHMA slope:
Bullish slope = long color.
Bearish slope = short color.
This makes the indicator easier to read as a regime overlay. You can quickly see when the market is consistently aligned with the volatility-weighted trend.
How to use it
1) Trend filter
Use the VWHMA color as a bias filter:
Only favor longs when the VWHMA is rising.
Only favor shorts when the VWHMA is falling.
2) Trend transition tool
Slope flips can identify early trend shifts:
Long marker = VWHMA has turned upward.
Short marker = VWHMA has turned downward.
Because the filter is Hull-style and volatility-weighted, it can react faster than slower trend filters while still suppressing some low-range noise.
3) Ribbon strength reading
The ribbon gives additional context:
Expanding ribbon = stronger separation and cleaner trend pressure.
Contracting ribbon = momentum weakening.
Ribbon flattening = chop or transition risk.
4) Pullback structure
In strong trends, price often respects the VWHMA or ribbon area:
Bull regime: pullbacks into the ribbon can act as support.
Bear regime: rallies into the ribbon can act as resistance.
5) Volatility-backed trend confirmation
Because large True Range bars influence the calculation more, this tool is useful for identifying whether trend changes are being supported by actual range expansion.
If price moves but the VWHMA does not respond strongly, the move may lack volatility-backed confirmation.
Input guide
Price Source
Defines the input series used for the calculation. Close is standard, but hl2, hlc3, or ohlc4 can be used for smoother structural behavior.
Lookback Period
Controls the smoothing length:
Lower values = faster response, more signals, more noise.
Higher values = smoother trend, fewer flips, more lag.
Plot as Band
Enables the ribbon view using the delayed smoothed VWHMA reference.
Line Width
Controls the main line thickness when not relying heavily on band mode.
Show Trend Candles
Paints candles by current trend state.
Show Signals
Toggles the long/short slope-flip markers.
Strengths
Uses volatility-weighted smoothing instead of equal weighting.
Combines volatility sensitivity with Hull-style lag reduction.
Clean ribbon visualization for trend displacement.
Simple slope-based regime interpretation.
Works well as a trend overlay or bias filter.
Limitations
Slope flips can still whipsaw in sideways markets.
Large wick bars can influence the filter strongly because True Range is used as weight.
It does not measure volume, despite using a VWMA-style internal function.
It is a trend tool, not a complete trading system.
Best use case
Volatility Hull Ribbon works best when used as a visual trend structure layer:
Use color for bias.
Use ribbon expansion/compression for strength.
Use slope flips for regime transitions.
Use price interaction with the ribbon for pullback context.
Summary
Volatility Hull Ribbon is a Hull-style trend overlay that replaces traditional weighting with True Range weighting, making the moving average more responsive to volatility-backed price movement. It builds a low-lag volatility-weighted Hull curve, compares it to a delayed smoothed reference to form a ribbon, and uses slope changes to define trend direction and signals. The result is a clean, responsive trend ribbon that highlights when volatility-backed trend pressure is rising, fading, or reversing. 지표

Trading Sessions Suite [BackQuant]Trading Sessions Suite
Overview
Trading Sessions Suite is a full intraday structure framework built around market sessions, kill zones, and session-specific order flow . It transforms the trading day into a sequence of structured regimes, allowing you to track how liquidity, volatility, and positioning evolve across Asia, London, and New York.
Instead of treating price as a continuous stream, this indicator segments the market into time-based auction phases , each with its own:
Range (high and low)
VWAP (fair value)
Open (reference anchor)
Equilibrium (midpoint)
Momentum (session oscillator)
It also overlays kill zones , highlighting the exact windows where volatility and participation tend to expand.
Example of kill zones in action:
Example combining RSI-style oscillator + VWAP structure:
This tool is designed for traders who want to understand how intraday structure builds, shifts, and resolves .
---
Core Philosophy
Markets are not random throughout the day. Liquidity, volatility, and institutional participation are time-dependent .
Each session has distinct characteristics:
Asia → accumulation, compression, range-building
London → expansion, breakout, liquidity grabs
New York → continuation, distribution, reversal potential
Rather than using static indicators, this script builds a dynamic framework tied to these time regimes .
---
Session Engine
The indicator tracks three primary sessions:
Asia Session
London Session
New York Session
Each session is defined by a configurable time window and processed as an independent structure.
Internally, each session maintains a full state:
Session high and low
Session open
Rolling VWAP
Start index (session start)
Drawn objects (box, lines, labels)
Oscillator data (if enabled)
This allows each session to behave like a self-contained market environment .
---
Session Boxes (Auction Structure)
Each session is visualized as a box:
Top = session high
Bottom = session low
Width = duration of the session
This gives you an immediate view of:
Range expansion vs compression
Relative volatility between sessions
Where price is positioned within each session
Interpretation:
Tight box → compression, buildup
Wide box → expansion, active participation
Overlapping boxes → consolidation across sessions
---
Session VWAP (Fair Value per Session)
Each session has its own VWAP:
VWAP = volume-weighted average price within that session only
This is critical because:
VWAP resets every session
Reflects session-specific positioning
Acts as a dynamic equilibrium level
Interpretation:
Price above VWAP → bullish control for that session
Price below VWAP → bearish control
Reversion to VWAP → mean reversion inside session
Unlike standard VWAP, this gives you multiple fair value anchors per day .
---
Session Open & Midline (Key References)
Each session also tracks:
Open Line → where the session started
Midline → (high + low) / 2
These act as:
Bias indicators (above/below open)
Equilibrium zones (midline)
Reaction levels
Typical behavior:
Holding above open → trend continuation
Crossing midline → shift in control
Rejecting midline → continuation signal
---
Range Extension (Forward Liquidity Levels)
When a session closes, its high and low can be extended forward.
These extensions act as:
Future support/resistance
Liquidity targets
Breakout validation zones
Mechanically:
High and low are projected into the next session
Remain until replaced or invalidated
Interpretation:
Next session often trades toward previous session extremes
Breaks of prior session range = regime shift
---
Kill Zones (High-Probability Windows)
Kill zones are specific time windows inside sessions where:
Liquidity spikes
Volatility expands
Institutional activity increases
Included zones:
Asia Kill Zone
London Open Kill Zone
New York Open Kill Zone
New York Close Kill Zone
They are visualized as shaded boxes separate from session boxes.
Why they matter:
Most breakouts occur during kill zones
Most reversals are initiated during kill zones
Liquidity sweeps cluster around these times
From the example:
You can see how price reacts specifically within these windows.
---
Session Oscillator (Embedded Momentum Engine)
Each session optionally includes its own oscillator plotted directly below the session box.
This is not a standard indicator overlay. It is:
Bound to the session range
Scaled relative to that session
Reset each session
Core mechanics:
Uses RSI-style calculation
Signal line = moving average of oscillator
Stored per bar within the session
Displayed as:
A mini panel under each session
With 30 / 50 / 70 reference levels
Example:
Interpretation:
Above 50 → bullish momentum within session
Below 50 → bearish momentum
30/70 → oversold/overbought zones
This gives you contextual momentum , not global momentum.
---
Why Session-Based Oscillators Matter
Standard oscillators ignore time segmentation.
This approach:
Resets momentum every session
Prevents carryover noise
Aligns signals with actual trading windows
So instead of:
“RSI is overbought”
You get:
“RSI is overbought within London session”
This is a much stronger contextual signal.
---
Labels & Range Statistics
Each session can display:
Session name (ASIA, LON, NY)
Range percentage
This helps quantify:
How much the market moved during that session
Which session is dominating volatility
---
Putting It All Together
This indicator gives you a full intraday map:
Where price moved (session boxes)
Where fair value sits (VWAP)
Where equilibrium lies (midline)
Where momentum stands (oscillator)
Where volatility expands (kill zones)
Where liquidity rests (extended highs/lows)
---
How to Use It
1) Identify the current session
Always start with:
Which session is active?
Each session behaves differently.
---
2) Use VWAP + midline for bias
Above VWAP + above mid → strong trend
Below VWAP + below mid → bearish control
Between → range
---
3) Watch kill zones for setups
Breakouts during kill zones are higher probability
Fake moves often occur just before them
---
4) Track previous session levels
Asia high/low often targeted during London
London extremes often targeted during NY
---
5) Use oscillator for confirmation
Momentum aligning with structure → stronger signal
Divergence → potential reversal
---
Strengths
Fully contextual intraday framework
Combines time, price, and volume-weighted logic
Visual and intuitive
Highly configurable
---
Summary
Trading Sessions Suite converts the trading day into a structured sequence of auctions. By combining session ranges, VWAP, kill zones, and a session-specific momentum engine, it provides a complete framework for understanding how price moves throughout the day. Instead of relying on static indicators, it aligns analysis with when liquidity actually enters the market, allowing for more precise timing, better context, and cleaner trade execution. 지표

Volume Bubble Levels [BackQuant]Volume Bubble Levels
Overview
Volume Bubble Levels is a volume-expansion and liquidity-mapping tool designed to identify statistically significant participation events and project them forward as actionable structural levels.
Instead of treating volume as a secondary confirmation metric, this indicator treats volume spikes as primary events and builds a framework around them:
Detect abnormal volume relative to a rolling baseline.
Classify those events into tiers based on intensity.
Visualize them directly on price using scalable “bubble” markers.
Project their high and low as forward levels (“naked levels”).
Track whether those levels remain untouched, get retested, or are invalidated.
The result is a system that highlights where meaningful participation occurred , and more importantly, whether the market has returned to those areas .
This shifts the focus from “what price did” to “where size traded and what has or hasn’t been revisited since.”
Core idea
Markets move through phases of normal participation and abnormal participation . Most bars are noise. Occasionally, a bar prints with volume significantly above its baseline, indicating:
Aggressive positioning,
Large order execution,
Liquidity events,
Absorption or distribution,
Forced flows (liquidations, stops, news reactions).
These events often leave behind structural footprints.
Volume Bubble Levels captures those footprints and answers:
Where did abnormal participation occur?
How strong was it relative to recent history?
Have those levels been revisited?
Are there still “untouched” zones where liquidity may remain?
Volume baseline and normalization
The first step is establishing what “normal” volume looks like.
The script computes a rolling moving average of volume:
volMa = MA(volume, volMaLen, volMaType)
You can choose the type:
SMA for stable baseline,
EMA for faster adaptation,
RMA for smoother response,
WMA for weighted emphasis on recent bars.
Then the script computes a ratio:
volRatio = volume / volMa
This is the key metric.
Interpretation:
volRatio ≈ 1 → normal participation.
volRatio > 1 → above-average participation.
volRatio >> 1 → abnormal participation.
Everything in the script is built off this ratio.
Tiered volume classification
Instead of treating all volume spikes equally, the script classifies them into three tiers:
Tier 1 — Elevated : moderate expansion above baseline.
Tier 2 — High : strong participation.
Tier 3 — Extreme : major volume event.
Defined as:
Tier 1: volRatio ≥ t1Mult
Tier 2: volRatio ≥ t2Mult
Tier 3: volRatio ≥ t3Mult
Each higher tier overrides the lower:
Tier 3 > Tier 2 > Tier 1
This creates a hierarchy of importance:
Tier 1 = “noticeable”
Tier 2 = “significant”
Tier 3 = “structural”
Directional context (bull vs bear volume)
Each volume event is also classified directionally:
Bull = close ≥ open
Bear = close < open
This matters because:
Bull volume spikes often represent aggressive buying or short covering.
Bear volume spikes often represent aggressive selling or long liquidation.
So every event carries two dimensions:
Magnitude (Tier 1 / 2 / 3)
Direction (bull / bear)
Bubble visualization (what the circles mean)
Volume events are plotted directly on price as circular “bubbles.”
Key properties:
Position: plotted at the closing price of the bar.
Color: determined by tier and direction.
Size: determined by how far the volume exceeds the threshold within its tier.
Size bucketing within tiers
Each tier is subdivided into five size buckets:
Tiny
Small
Normal
Large
Huge
This is done by splitting each tier’s range into equal steps.
Example:
Tier 1 spans from t1Mult → t2Mult.
That range is divided into 5 segments.
Higher volRatio within that tier = larger bubble.
So a large Tier 1 bubble may still be smaller than a small Tier 2 bubble, preserving hierarchy.
What bubbles represent in practice
Each bubble is a localized participation event .
Interpretation:
Cluster of bubbles → sustained participation.
Single large bubble → isolated liquidity event.
Tier 3 bubble → major structural event, often worth tracking.
They are not signals by themselves. They are markers of where something important happened .
Naked levels: projecting volume events forward
The core feature of this script is not the bubbles themselves, but what happens after them.
For every qualifying volume event, the script creates:
A horizontal line at the bar’s high.
A horizontal line at the bar’s low.
These are called naked levels .
Why both high and low:
High captures the upper boundary of the event.
Low captures the lower boundary.
Together, they define the full price range where abnormal volume occurred.
What “naked” means
A level is “naked” if:
Price has not yet traded back through it.
These are important because:
They represent unresolved areas.
Liquidity may still be resting there.
Market participants involved in the original event may still be positioned around that level.
Level lifecycle
1) Creation
On a volume event:
High line and low line are created.
Stored with metadata:
- price
- tier
- direction
- creation bar
2) Extension
Each level extends forward in time:
Updated every bar.
Projected to the right until resolved.
3) Takeout (resolution)
A level is considered “taken” when price trades through it:
High level taken when: high > level price
Low level taken when: low < level price
Once taken:
The line is terminated.
Removed from active tracking.
4) Expiry
Levels also expire after a fixed number of bars:
If (current bar - birth bar) > extendBars → level is removed.
This prevents infinite clutter and ensures relevance.
Why naked levels matter
These levels act like:
Liquidity magnets,
Revisit zones,
Areas of unfinished business.
In practice:
Price often returns to high-volume zones.
Untouched levels can act as targets.
Revisits can trigger reactions, pauses, or reversals.
This aligns with auction market theory:
Markets seek to revisit areas of high participation.
Unfinished auctions tend to get completed.
Tier-aware level significance
Not all levels are equal:
Tier 1 levels = weaker, more frequent.
Tier 2 levels = meaningful.
Tier 3 levels = major structural zones.
The script reflects this visually:
Tier 3 lines are thicker.
Colors differ by tier and direction.
So you can quickly identify:
Which levels matter most.
Color system
Each tier has separate bull/bear colors.
This allows:
Bullish volume zones vs bearish volume zones.
Visual distinction between accumulation-type and distribution-type activity.
Because:
A high-volume bullish bar and a high-volume bearish bar represent very different order flow contexts.
Line styling
You can choose:
Dotted
Dashed
Solid
This does not affect logic, only readability.
What this indicator is NOT
It is important to understand what this tool is not doing:
It is not a volume profile.
It does not aggregate volume by price level.
It does not measure cumulative delta.
It does not predict direction directly.
Instead, it is:
Event-based , not distribution-based.
Forward-projecting , not historical summarizing.
Structure-focused , not signal-focused.
How to use it
1) Identify important zones
Focus on:
Tier 2 and Tier 3 bubbles.
Clusters of bubbles.
These represent areas of significant participation.
2) Track naked levels
Watch:
Untouched levels ahead of price.
Levels near current price.
These often act as:
Targets,
Reaction zones,
Liquidity pools.
3) Watch level interactions
When price approaches a level:
Rejection → confirms level relevance.
Clean break → invalidates it.
Chop around level → absorption.
4) Combine with structure
This tool works best with:
Trend context,
Support/resistance,
Market structure,
Other flow indicators.
Example interpretations
Scenario 1: Strong bullish bubble cluster
Multiple Tier 2–3 bullish bubbles form.
Price moves away without revisiting.
Interpretation:
Strong accumulation zone.
Untouched lows may act as future support or targets.
Scenario 2: Price returns to naked level
Price revisits a previously untested level.
Interpretation:
Liquidity is being re-engaged.
Potential reaction point.
Scenario 3: Level invalidation
Price blows through a level with strong continuation.
Interpretation:
That level no longer holds structural significance.
Market has repriced beyond that participation zone.
Strengths
Highlights meaningful participation events.
Projects actionable forward levels.
Separates noise from structural volume.
Works across assets and timeframes.
Limitations
Depends on volume quality (less reliable on low-liquidity assets).
Does not indicate direction by itself.
Can produce many levels in volatile environments.
Requires interpretation, not plug-and-play signals.
Summary
Volume Bubble Levels transforms abnormal volume events into forward-projected structural levels. By measuring volume relative to its own baseline, classifying it into tiers, and projecting both the high and low of those events, the indicator builds a dynamic map of where meaningful participation occurred and whether those areas remain unresolved. The bubbles highlight the event, but the real value comes from the naked levels, which act as evolving liquidity zones that can influence future price behavior. 지표

Exponential Hull Momentum [BackQuant]Exponential Hull Momentum
Overview
Exponential Hull Momentum is a normalized momentum oscillator built from an Exponential Hull Moving Average -style transformation. Its purpose is to measure whether smoothed directional pressure is pushing toward the upper or lower end of its own recent range, while keeping the response faster and cleaner than a plain moving-average oscillator.
At a high level, the script does three things:
Builds a fast, low-lag smoothed series using an Exponential Hull-style calculation.
Normalizes that series against its own rolling high-low range so the output fits into a bounded oscillator-style scale centered around zero.
Optionally smooths the oscillator with a selectable moving average so you can use a secondary signal line or regime filter.
The final result is an oscillator that tries to answer:
Is momentum pushing toward the strong positive end of its recent range?
Is momentum collapsing toward the negative end?
Is the current move still expanding, or is it rolling over relative to its own smoothed state?
What this indicator is actually measuring
This indicator is not measuring raw returns, not measuring RSI-style up/down closes, and not measuring volatility. It is measuring the position of a low-lag smoothed price transform within its own recent rolling range .
That distinction matters.
It means:
Positive values indicate the Exponential Hull series is in the upper half of its recent normalized range.
Negative values indicate it is in the lower half of its recent normalized range.
Extreme positive values suggest strong upward momentum persistence.
Extreme negative values suggest strong downward momentum persistence.
Because it is normalized, the oscillator is less about absolute price level and more about relative momentum state .
Where the “Hull” idea comes from
The Hull Moving Average family exists to solve a classic moving-average problem:
If you smooth more, you reduce noise but increase lag.
If you smooth less, you reduce lag but increase noise.
Alan Hull’s core idea was to combine moving averages in a way that compensates for lag before applying a final smoothing stage. The classic HMA uses weighted moving averages. This script uses the same structural idea, but with EMAs instead , producing an Exponential Hull-style moving average .
So instead of a classic HMA, the script constructs:
A fast EMA on half-length input.
A slower EMA on full-length input.
A lag-compensated intermediate value using 2 * fast - slow.
A final EMA smoothing pass using sqrt(length).
This is why it is called Exponential Hull Momentum . The “Hull” part refers to the lag-reduction structure, the “Exponential” part comes from using EMA instead of WMA.
The EHMA calculation step by step
The core function is:
EHMA(_src, _length) =
EMA( 2 * EMA(_src, _length / 2) - EMA(_src, _length), round(sqrt(_length)) )
Let’s break that down.
1) Fast EMA on half length
EMA(_src, _length / 2)
This reacts quickly to recent price changes.
2) Slow EMA on full length
EMA(_src, _length)
This is smoother and more delayed.
3) Lag compensation
2 * fastEMA - slowEMA
This is the critical step. It pushes the result toward the faster average while subtracting part of the slower lagging component. Conceptually, it behaves like a “de-lagged” smoother. It is related in spirit to reduced-lag constructions like DEMA and TEMA, though implemented in a Hull-style framework.
4) Final smoothing
EMA(lag_compensated_series, sqrt(length))
This final pass cleans up the compensated series so it remains usable as a smooth momentum engine rather than a noisy de-lagged line.
So the oscillator’s underlying subject is not raw price, but this EHMA subject series .
Why use EHMA instead of a plain EMA or raw price
A raw price oscillator is often too noisy. A plain EMA oscillator is smoother, but can still lag too much. EHMA tries to balance:
Faster reaction than a standard EMA.
Cleaner shape than a raw de-lagged transform.
More sensitivity to directional bursts.
That makes it useful for momentum work, especially when you want:
Earlier momentum regime shifts.
Cleaner trend-state transitions.
A bounded oscillator rather than an overlay line.
Normalization: turning the EHMA into an oscillator
After computing the EHMA subject, the script normalizes it using its own rolling lowest and highest values over a user-defined normalization period:
lowest = lowest(subject, norm_period)
highest = highest(subject, norm_period)
plotosc = (subject - lowest) / (highest - lowest) - 0.50
This transforms the EHMA series into a bounded range centered around zero.
Interpretation:
If subject is near the rolling highest, plotosc approaches +0.5.
If subject is near the rolling lowest, plotosc approaches -0.5.
If subject is near the middle of the rolling range, plotosc is near 0.
So the oscillator is essentially:
Where is the current EHMA value sitting within its recent high-low envelope?
Why normalization matters
Without normalization, the EHMA value itself would still be in price units, which makes comparison harder across:
Different assets,
Different timeframes,
Different price regimes.
Normalization gives you a common scale:
-0.5 to +0.5, centered at 0
That makes the output much easier to use as a momentum state tool.
What the oscillator values mean
Near +0.5
The EHMA subject is pressing against the upper end of its rolling range. This usually means:
Strong bullish momentum,
Persistent upward movement in the smoothed series,
A possible “stretched” positive momentum condition.
Near -0.5
The EHMA subject is pressing against the lower end of its rolling range. This usually means:
Strong bearish momentum,
Persistent downward movement,
A possible stretched downside state.
Near 0
The EHMA subject is near the midpoint of its recent range. This can mean:
Momentum is neutral,
Momentum is transitioning,
The market is compressing or chopping relative to recent structure.
Important nuance about the oscillator scale
This is not a z-score . It is not measuring “standard deviations from mean.” It is a min-max style range normalization . That means:
The output depends on the recent highest and lowest subject values.
If the rolling range changes sharply, oscillator sensitivity can change too.
The same oscillator value does not imply the same statistical rarity across all contexts.
It is best read as a relative range-position momentum oscillator , not as a probabilistic metric.
Signal line / moving average layer
The script optionally applies a second smoothing layer directly to the oscillator:
sig_ma = MA(plotosc, malen, matype)
You can choose from many MA types:
SMA
EMA
DEMA
TEMA
RMA
WMA
HMA
T3
ALMA
LINREG
VWMA
This signal line is not required for the core oscillator to work. It is a secondary interpretation layer that can be used for:
Momentum confirmation,
Cross-based entry logic,
Smoothing out the oscillator for regime filtering,
Visual comparison between raw momentum and smoothed momentum.
The script note suggests that if you want to use the MA more like a signal histogram, you can change its style to columns in the style menu.
Why a selectable MA matters
Different traders want different signal characteristics:
SMA/EMA for classic smoothing,
DEMA/TEMA for lower lag,
HMA/T3/ALMA for smoother trend-state filtering,
LINREG for slope-sensitive behavior,
VWMA if you want volume-weighted smoothing.
This makes the indicator more flexible without changing the core EHMA oscillator.
Color gradient logic
The oscillator columns are colored using thresholded intensity zones rather than a continuous gradient function. The color changes as the oscillator moves further away from zero.
For positive values:
Weak positive: lighter cyan/green tones.
Moderate positive: stronger green.
Strong positive: bright green.
Extreme positive near +0.5: intense bright green.
For negative values:
Weak negative: orange/red tint.
Moderate negative: deeper red.
Strong negative: bright red.
Extreme negative near -0.5: intense red.
This means the plot does two jobs at once:
Direction from sign,
Relative momentum intensity from color saturation.
So even without reading the value numerically, you can see whether momentum is:
Barely positive,
Strongly positive,
Barely negative,
Or deeply negative.
Static levels and what they mean
The script draws fixed zones:
+0.5 and +0.4
-0.4 and -0.5
0 midline
These create:
An upper “overbought / strong positive momentum” zone from 0.4 to 0.5
A lower “oversold / strong negative momentum” zone from -0.4 to -0.5
A midline at 0 separating positive from negative momentum territory
Important:
These are momentum extreme zones , not traditional RSI overbought/oversold zones.
Strong trends can stay pinned near +0.5 or -0.5 for long periods.
Extreme readings do not automatically mean reversal.
The fill between the upper and lower static boundaries just makes those zones easier to identify visually.
Midline logic
The zero line is the most important structural level in the oscillator:
Above 0 = EHMA is in the upper half of its recent range, positive momentum regime.
Below 0 = EHMA is in the lower half of its recent range, negative momentum regime.
The alert conditions are built on this exact logic:
Long alert on crossover above 0
Short alert on crossunder below 0
So the core directional interpretation is midline-based.
How to interpret the indicator in practice
1) Momentum regime
The cleanest use is as a regime filter:
Above 0: positive momentum bias.
Below 0: negative momentum bias.
This alone can already be useful for:
Filtering entries,
Avoiding countertrend setups,
Aligning with the dominant smoothed momentum state.
2) Momentum intensity
The closer the oscillator moves toward +0.5 or -0.5, the stronger the recent momentum relative to its own normalized range.
This can help distinguish:
Weak trend drift,
Healthy trend continuation,
Momentum surge / expansion,
Potential exhaustion zones.
3) Transition behavior
Watch how the oscillator behaves around 0:
Fast thrust through 0 often signals a fresh momentum shift.
Repeated chop around 0 often signals indecision or sideways conditions.
A flattening oscillator after an extreme reading often shows momentum deterioration before price fully turns.
4) Using the moving average signal
If enabled, the MA of the oscillator can help identify:
When raw momentum is accelerating away from smoothed momentum,
When momentum is rolling over,
Whether the oscillator move is broad and sustained or only a short burst.
A common interpretation:
Oscillator above signal MA and above zero = strong bullish momentum structure.
Oscillator below signal MA and below zero = strong bearish momentum structure.
Divergence between oscillator and signal MA = momentum fading or transitioning.
What makes this different from RSI or stochastic-style oscillators
This script is structurally different from standard oscillators.
Compared to RSI
RSI is based on the ratio of average up closes to down closes. It measures directional internal strength of return behavior.
EHMA Momentum instead:
Starts from a low-lag smoothed price transform,
Then asks where that transform sits in its recent range.
So it is more “structure-relative momentum” than “up/down return balance.”
Compared to Stochastic
Stochastic asks where price closes relative to recent high-low range.
EHMA Momentum asks where the EHMA-smoothed subject sits relative to its own recent subject range.
That means:
It is less raw than stochastic,
More smoothed,
Potentially less noisy,
And more focused on directional structure than candle location.
Parameter behavior
Exponential Hull Calculation Period (len)
Controls how the EHMA subject is built.
Very low values make the subject extremely reactive.
Higher values smooth the subject more and reduce sensitivity.
Since the default is very small, this script is designed to be sharp and responsive by nature.
Normalization Period (norm_period)
Controls the rolling high-low range used to normalize the subject.
Higher values create a broader historical range and smoother normalization.
Lower values make the oscillator adapt faster, but it can become more jumpy and “range-reset” more often.
Signal MA Period and Type
Controls how smooth the optional secondary line is.
Shorter MA = faster cross behavior.
Longer MA = slower, steadier confirmation.
Strengths of this approach
Fast response because of the Exponential Hull construction.
Easy interpretation because of bounded normalized output.
Works well as a regime filter via the zero line.
Intensity is visually clear from both height and color.
Flexible because of optional multi-type signal smoothing.
Limitations and what to watch for
Because the oscillator is min-max normalized, extreme values can persist in strong trends.
A rolling highest/lowest normalization can make the oscillator “reset” as old extremes leave the window.
On very low lengths, the EHMA can become highly reactive and potentially noisy.
Zero-line crosses can whipsaw in sideways markets, especially if normalization is too short.
So this tool is best used with context:
Trend structure,
Market regime,
Higher timeframe bias,
Or combined with the signal MA and price action.
Summary
Exponential Hull Momentum is a normalized momentum oscillator built from an EMA-based Hull-style smoothing engine. It first creates a low-lag Exponential Hull series, then normalizes that series within its own rolling high-low range so the output oscillates around zero between roughly -0.5 and +0.5. Positive values indicate the EHMA subject is pressing into the upper half of its recent range, negative values indicate the lower half, and the distance from zero reflects relative momentum strength. Static zones highlight extreme positive and negative momentum states, while an optional multi-type moving average can be used as a secondary signal or smoothing layer. 지표

Gamma Exposure Levels [BackQuant]Gamma Exposure Levels
This indicator allows you to paste Gamma Exposure (GEX) level data directly into a text input on TradingView, automatically parsing the values and plotting them as labeled horizontal lines on your chart. It is designed for traders who use options-derived gamma exposure data as part of their technical analysis and want a fast, visual way to overlay those key price levels onto any chart and timeframe.
Rather than manually drawing lines for each level, this script reads a structured block of GEX output text, extracts every relevant dollar value, and draws color-coded, labeled levels across your chart. If two or more levels share the same price, their labels are automatically merged (for example, "Max Pain / Call Res $75,000") so the chart stays clean and readable.
What is Gamma Exposure (GEX)?
Gamma Exposure refers to the aggregate gamma held by options market makers (dealers) at each strike price. Gamma measures how much a dealer's delta (directional hedge) changes as the underlying price moves. When dealers hold large gamma positions, they must continuously hedge by buying or selling the underlying asset, which can either dampen or amplify price movement depending on the sign of that gamma.
When dealers are long gamma (positive GEX), they hedge against the prevailing trend: buying dips and selling rallies. This creates a stabilizing, mean-reverting effect around high-gamma strikes, making those levels act like magnets or support/resistance zones.
When dealers are short gamma (negative GEX), they hedge in the same direction as the move: selling into drops and buying into rallies. This amplifies volatility and can cause sharp, directional moves once a key gamma level breaks.
Understanding where these gamma levels sit gives traders a structural map of where options market makers are likely to add liquidity or accelerate a move.
How to Use This Indicator
Add the indicator to your chart.
Open the indicator settings and find the "Data Input" group at the top.
Paste your full GEX levels output into the text area. The indicator expects a structured text format (see the example format below).
The indicator will automatically parse all dollar values from the text and plot them as horizontal lines with labels.
Use the toggle checkboxes next to each level type to show or hide individual levels.
Customize colors, line style, line width, label size, label offset, and label position from the settings panel.
Expected Input Format
The indicator parses structured GEX output text. Below is an example of the expected format. Copy and paste a block like this directly into the text area input in the indicator settings:
GEX Levels - 04/03/2026, 12:17:19
All-Expiry Levels:
HVL: $72,000 +$1,841 (+2.62%)
Call Resistance: $75,000 +$4,841 (+6.90%)
Put Support: $60,000 $-10,159 (-14.48%)
0DTE Levels:
0DTE HVL: $68,000 $-2,159 (-3.08%)
0DTE Call: $71,000 +$841 (+1.20%)
0DTE Put: $66,000 $-4,159 (-5.93%)
Advanced:
Zero Gamma: $71,819 +$1,660 (+2.37%)
Max Pain: $74,000 +$3,841 (+5.47%)
Expected Move: $64,238 to $76,081
Flip Zones (All): $67,500
All-Expiry GEX Top 10 (by |gamma|):
1. $60,000 $-10,159 (-14.48%) | GEX: -20,711,741.86
2. $75,000 +$4,841 (+6.90%) | GEX: 18,876,578.2
3. $72,000 +$1,841 (+2.62%) | GEX: 17,530,960.01
4. $70,000 $-159 (-0.23%) | GEX: 17,494,795.02
5. $74,000 +$3,841 (+5.47%) | GEX: 13,573,146.08
6. $73,000 +$2,841 (+4.05%) | GEX: 10,380,107.7
7. $69,000 $-1,159 (-1.65%) | GEX: 10,341,883.98
8. $80,000 +$9,841 (+14.03%) | GEX: 8,636,674.83
9. $71,000 +$841 (+1.20%) | GEX: 7,962,084.65
10. $65,000 $-5,159 (-7.35%) | GEX: -7,257,124.01
0DTE GEX Top 10 (by |gamma|):
1. $69,500 $-659 (-0.94%) | GEX: 3,659,702.74
2. $70,500 +$341 (+0.49%) | GEX: 1,152,595.15
3. $69,000 $-1,159 (-1.65%) | GEX: 703,339.82
4. $72,000 +$1,841 (+2.62%) | GEX: 697,625.91
5. $73,000 +$2,841 (+4.05%) | GEX: 419,096.08
6. $68,000 $-2,159 (-3.08%) | GEX: 294,575.89
7. $74,000 +$3,841 (+5.47%) | GEX: 281,083.42
8. $75,000 +$4,841 (+6.90%) | GEX: 183,191.05
9. $66,000 $-4,159 (-5.93%) | GEX: -172,470.38
10. $68,500 $-1,659 (-2.37%) | GEX: 167,135.87
The indicator only extracts the dollar values from this text. The percentage changes, GEX magnitude values, and other metadata are informational context in the source data but are not plotted by this script.
Level Definitions
Below is a detailed explanation of every level this indicator can parse and plot. These are grouped the same way they appear in the indicator settings.
All-Expiry Levels
These levels are derived from gamma exposure aggregated across all option expiration dates.
HVL (High Volume Level) - The price with the highest total gamma exposure across all expirations. This is the strike where dealers hold the most aggregate gamma and therefore where hedging activity is most concentrated. Price tends to gravitate toward the HVL in positive gamma environments because dealer hedging creates a mean-reverting effect around this level. Think of it as the "center of gravity" for options-driven price action.
Call Resistance - The price level where call-side gamma creates overhead resistance. At this strike, the concentration of call gamma means that as price rises toward it, dealers who are long those calls must sell the underlying to stay delta-neutral. This selling pressure acts as a ceiling, making it harder for price to push through. Breaks above call resistance can signal a shift in positioning or the start of a gamma squeeze.
Put Support - The price level where put-side gamma creates downside support. At this strike, the concentration of put gamma means that as price falls toward it, dealers must buy the underlying to hedge. This buying pressure acts as a floor, cushioning the decline. A break below put support can accelerate selling as dealers flip from buying to selling, potentially triggering a sharp move lower.
0DTE Levels
These levels are derived exclusively from same-day (zero days to expiration) options. Because 0DTE options have extremely high gamma due to their proximity to expiration, they can dominate intraday price action even when their notional size is smaller than longer-dated positions.
0DTE HVL - The same-day high volume level. This is the intraday gamma center of gravity derived solely from options expiring today. It represents the strike where 0DTE dealer hedging is most concentrated and where intraday gamma polarity can flip. Particularly relevant for intraday traders, as 0DTE gamma effects intensify throughout the trading session and peak in the final hours before expiration.
0DTE Call - Same-day call resistance. The intraday ceiling created by 0DTE call gamma. Dealer hedging against these expiring calls creates selling pressure as price approaches this level. Because 0DTE gamma decays rapidly, this level can shift during the session and its strength increases as expiration approaches.
0DTE Put - Same-day put support. The intraday floor created by 0DTE put gamma. Dealer hedging against expiring puts creates buying pressure at this level. Like the 0DTE call level, its influence grows as the trading day progresses and gamma effects intensify near the close.
Advanced Levels
These levels provide additional structural context beyond the core support, resistance, and HVL framework.
Zero Gamma - The precise price where cumulative gamma across all strikes and expirations equals zero. This is one of the most important structural levels in gamma analysis. Above the Zero Gamma level, dealers are net long gamma and their hedging stabilizes price (buying dips, selling rallies). Below it, dealers are net short gamma and their hedging amplifies moves (selling into drops, buying into rallies). Crossing the Zero Gamma level often marks a regime change in how the market behaves, shifting from mean-reversion to trend-following dynamics.
Max Pain - The strike price at which the total value of all outstanding options (both calls and puts) would be minimized if the underlying expired at that price. In other words, it is the price where option holders collectively lose the most money. Max Pain theory suggests that there is a gravitational pull toward this level as expiration approaches, driven by dealers and market makers who benefit from options expiring worthless. It is most relevant in the final days before a major expiration.
Expected Move - The 1-sigma (one standard deviation) expected price range, plotted as two levels: Expected Move Upper and Expected Move Lower. This range represents the statistically expected boundaries of price movement based on current implied volatility. Roughly 68% of the time, price is expected to remain within this range. These levels help traders gauge whether the current price action is within normal bounds or represents an unusual move. A break beyond the expected move range can signal a volatility event or a shift in market regime.
Flip Zones - All price levels where gamma polarity changes sign. At these strikes, dealer hedging behavior transitions from stabilizing (long gamma) to destabilizing (short gamma) or vice versa. Flip zones act as transition boundaries. When price crosses a flip zone, the nature of dealer activity changes, which can lead to shifts in volatility, momentum, and the tendency for price to mean-revert or trend. Multiple flip zones in a narrow range can create a "no man's land" where positioning is mixed and price action becomes choppy.
GEX Top 10
The GEX Top 10 are the ten strike prices with the highest absolute gamma exposure, ranked by the magnitude of their gamma (|gamma|). These represent the strikes where dealer hedging activity is most significant, regardless of whether the gamma is positive (call-dominated, stabilizing) or negative (put-dominated, destabilizing).
The indicator provides a dropdown selector with five options for the GEX Top 10:
None - Do not plot any GEX Top 10 levels.
0DTE - Plot the Top 10 from same-day (0DTE) options only. Best for intraday analysis.
All Expiries - Plot the Top 10 from all expiration dates combined. Best for swing or multi-day analysis.
0DTE 1-5 - Plot only the top 5 from 0DTE options. Useful for reducing chart clutter while keeping the most significant intraday levels.
All Expiries 1-5 - Plot only the top 5 from all expiration dates. Useful for a cleaner multi-day view.
Each of the 10 GEX levels (GEX #1 through GEX #10) has its own individual toggle and color picker, so you can show or hide any specific rank and assign distinct colors to differentiate them.
Overlap Handling
It is common for multiple GEX levels to land on the same price. For example, Max Pain and Call Resistance might both be at $75,000, or a GEX Top 10 strike might coincide with the HVL. Rather than drawing overlapping lines and labels that clutter the chart, this indicator automatically detects when two or more levels share the same price (within a $0.50 tolerance). When a match is found, only one line is drawn at that price and the labels are merged with a "/" separator.
For example, if Max Pain is $75,000 and Call Resistance is also $75,000, the chart will show a single line labeled:
Max Pain / Call Res 75000
This keeps the chart clean and makes it immediately obvious when multiple structural levels converge at the same price, which often signals a particularly significant level.
Customization Options
The indicator provides extensive customization through its settings panel:
Per-Level Controls
Each level type has its own color picker and show/hide toggle on the same line.
GEX Top 10 levels (#1 through #10) each have individual color pickers and toggles.
A dropdown selector lets you choose which GEX Top 10 dataset to plot (0DTE, All Expiries, top 5 only, or none).
Line Style
Line Width: 1 to 4 pixels.
Line Style: Solid, Dashed, or Dotted.
Extend Lines: Both directions, Right only, Left only, or None.
Label Settings
Label Size: Tiny, Small, Normal, Large, or Huge.
Label Offset: Position the labels any number of bars to the right or left of the current bar (-200 to 500).
Label Side: Place labels on the Right or Left side of the chart.
Every toggle and input has a descriptive tooltip that appears on hover, explaining what the level represents and how it is used.
How the Parsing Works
The script uses Pine Script v6 string functions to scan the pasted text for known keywords (such as "HVL:", "Call Resistance:", "0DTE Call:", "Zero Gamma:", "Expected Move:", "Flip Zones:", etc.). For each keyword found, it locates the next "$" character and extracts the numeric value that follows, correctly handling both comma-separated thousands (e.g., $72,000) and decimal values (e.g., $71,819.50).
For the Expected Move, it parses both the lower and upper bounds from the "to" separator (e.g., "$64,238 to $76,081").
For Flip Zones, it scans for every "$" on the line and extracts each value, correctly distinguishing thousands-separator commas from delimiter commas between multiple zone values.
For the GEX Top 10 sections, it identifies the section header ("All-Expiry GEX Top 10" or "0DTE GEX Top 10") and parses the first dollar value from each numbered line, stopping when it hits a new section header or separator.
The indicator only draws on the last bar and uses a delete-and-redraw system to ensure that only one clean set of lines and labels exists at any time. Old drawings are removed before new ones are created on each update.
Important Notes
This indicator does not generate or calculate GEX data. It is a visualization tool that plots externally sourced gamma exposure levels onto your TradingView chart.
The indicator requires you to paste GEX data in the expected structured text format. If the text area is empty, nothing will be plotted.
GEX data is a snapshot in time. Options positioning changes throughout the trading day as new trades are opened and closed. Levels should be updated periodically for the most accurate representation of current dealer positioning.
GEX levels are not guaranteed support or resistance. They represent areas where dealer hedging activity is concentrated, which can influence price behavior but does not determine it. Always use GEX data as one component of a broader analysis framework.
지표

Trend Velocity Channel [BackQuant]Trend Velocity Channel
Overview
Trend Velocity Channel is a trend and momentum-acceleration overlay built around one idea, trend strength is the gap between a fast “lead” average and a slow “lag” average . When the lead line pulls away from the lag line, the market is accelerating in that direction. When that gap collapses, trend energy is fading and reversals become more likely.
Instead of using a single moving average slope or crossover, this indicator measures:
A leading trend line (DEMA) that reacts quickly.
A lagging trend line (slower EMA) that represents slower consensus value.
A normalized “velocity / crush” metric: the distance between them in ATR units .
A trend regime based on the sign of that velocity.
A dynamic channel defined by the lead line on one side and a padded lag boundary on the other.
A reversal level engine that marks flip bars and tracks retests and invalidations.
The result is a channel that visually answers:
Are we accelerating or decelerating?
How strong is the current acceleration relative to recent history?
Where is the “danger edge” where a reversal would be confirmed?
Which flip levels remain relevant and which got invalidated?
Concept: lead vs lag as a proxy for trend velocity
Markets trend when price doesn’t just move, it keeps moving faster than the slow baseline can follow . If a fast estimator (lead) separates from a slow estimator (lag), that separation is a practical proxy for “velocity”:
Lead above lag, bullish acceleration.
Lead below lag, bearish acceleration.
Lead converging back into lag, trend energy compressing.
This script calls that separation Crush , meaning the lead line is “crushing away” from the lag line.
Core components
1) Leading line: DEMA
The lead line is a Double Exponential Moving Average:
dema = DEMA(price, maLen)
Why DEMA:
It reduces lag relative to a standard EMA.
It reacts faster to genuine directional moves.
It still smooths noise enough to act as a structural line.
DEMA is used as the “inner” channel edge and the glow anchor.
2) Lagging line: Slow EMA
The lag line is a slower EMA:
lagMA = EMA(price, round(maLen * 1.5))
Why a slower EMA:
It represents a slower-moving consensus baseline.
It creates a meaningful “gap” against the lead line.
It is less sensitive to micro-chop, so separation signals are cleaner.
The lag line also becomes the basis for the channel’s outer edge.
3) Volatility normalization: ATR
Raw MA distance is not comparable across regimes. A 50-point gap might be huge in a low-vol market and nothing in a high-vol market. So the gap is normalized by ATR:
atr = ATR(14)
rawCrush = (dema - lagMA) / atr
Interpretation:
rawCrush = “how many ATRs the lead line is away from the lag line.”
This standardizes the signal across instruments and volatility states.
4) Crush smoothing
The gap can still jitter, especially in choppy markets. So it is EMA-smoothed:
crush = EMA(rawCrush, crushSmth)
Lower crushSmth:
Faster regime flips, more noise.
Higher crushSmth:
More stable regimes, slower reaction.
Trend regime and flips
Trend direction is derived directly from the sign of the smoothed crush:
trend = crush > 0 ? +1 : -1
flip = trend != trend
Meaning:
Bull regime: lead (DEMA) is above lag baseline in ATR units.
Bear regime: lead is below lag baseline.
Flip: the velocity sign changed, meaning acceleration has switched direction.
This is not a price crossover system, it is a lead-lag separation regime system .
Measuring strength: crushNorm
The script also grades how extreme current crush is relative to recent conditions:
crushAbs = abs(crush)
crushHigh = highest(crushAbs, 80)
crushNorm = crushHigh > 0 ? min(crushAbs / crushHigh, 1) : 0
Interpretation:
crushNorm near 0 means separation is small relative to recent extremes, trend is weak or compressing.
crushNorm near 1 means separation is near the largest seen recently, trend acceleration is strong.
This strength scale drives:
Color intensity (gradient)
Glow width
“Peak Crush” alert condition
Channel construction
Inner edge
The inner edge is the leading line:
inner = dema
This is the “fast structure” of the move.
Outer edge
The outer edge is built from the lag line plus an ATR padding:
outer = (bull) lagMA - atr * chanPad
outer = (bear) lagMA + atr * chanPad
This is important. The lag line sits behind price, so the script offsets it outward by a user-defined fraction of ATR. This creates a more realistic boundary that accounts for volatility.
Interpretation:
In bull regimes, the outer boundary is below lagMA, creating a support-like corridor beneath price.
In bear regimes, the outer boundary is above lagMA, creating a resistance-like corridor above price.
The channel is intentionally asymmetric
This channel is not “± ATR around a mean.” It is directional:
Inner edge hugs price via fast DEMA.
Outer edge is anchored to lagMA and padded outward.
So it behaves like a trend corridor where:
The inner edge shows where the trend is currently “being pulled.”
The outer edge shows the boundary where the trend would be meaningfully compromised if crossed.
Ribbon fill (3-layer depth)
Two midpoints are created between inner and outer:
mid1 = inner + (outer - inner) * 0.33
mid2 = inner + (outer - inner) * 0.66
Then the fill is layered:
inner → mid1 (most opaque)
mid1 → mid2
mid2 → outer (most transparent)
This creates a depth effect that visually communicates where price is sitting within the corridor. When the corridor is tight and strong, the ribbon looks concentrated. When it expands, the ribbon spreads and fades.
Color logic (trend + strength)
The indicator uses a gradient color where direction sets the palette and crushNorm sets intensity:
Bull: faint green → strong green as crushNorm increases
Bear: faint red → strong red as crushNorm increases
This means you can read two things instantly:
Direction (bull vs bear)
Acceleration strength (faded vs intense)
Glow engine on DEMA
Glow width scales with ATR and crushNorm:
glowW = atr * 0.07 * (0.5 + crushNorm)
So:
High acceleration = larger glow, more “energy” around the lead line.
Low acceleration = smaller glow.
Glow is built as multiple invisible plots above and below DEMA with layered fills, forming a halo around the lead line that encodes strength.
Flip-aware band breaking
The outer boundary line is broken on flips:
bandBrk = flip ? na : outer
plot(..., plot.style_linebr)
This prevents a misleading continuous line across regime changes, since the outer edge swaps sides on flip.
Crush reversal levels (flip levels engine)
This script includes a level system that plants a dashed horizontal level on every regime flip, then tracks:
Whether price retests it (first touch marker)
Whether price invalidates it (deletes it)
How long it extends forward
How many levels are kept
1) Level placement
On a flip:
If trend flips bullish, the level is placed at the flip bar’s low.
If trend flips bearish, the level is placed at the flip bar’s high.
That makes sense structurally:
Bull flip low is a “pivot low” candidate.
Bear flip high is a “pivot high” candidate.
Then a dashed line is drawn forward ~60 bars.
2) Level storage and maxLvls
Levels are stored in an array and capped by maxLvls. When the cap is exceeded, the oldest is deleted. This keeps the chart readable.
3) Level invalidation (broken logic)
Each level is monitored:
Bull flip level breaks if price closes far below it: close < level - atr * 2.5
Bear flip level breaks if price closes far above it: close > level + atr * 2.5
This is a volatility-scaled invalidation. If price pushes through a flip level by a large margin in ATR terms, it’s no longer acting like a meaningful reaction point.
4) Retest detection
A “touch” is detected when:
close is within 0.25 ATR of the level,
and close two bars ago was not close (distance > 0.5 ATR),
and the level hasn’t been marked retested yet.
On first retest, an “x” marker is printed and the level’s retested flag is set to true so it won’t spam.
What these levels represent
They are not generic support/resistance. They are regime pivot levels created by a change in lead-lag acceleration. In practice:
Untested flip levels can act like “memory zones” where price may react.
Retested levels become less special, still relevant but not “naked.”
Invalidated levels are removed to reduce noise.
Signals and alerts
The script provides:
Crush Bull: flip into bullish regime (crush crosses above 0 via smoothing logic)
Crush Bear: flip into bearish regime
Peak Crush: crushNorm > 0.85, meaning separation is near recent max, strong acceleration
Important: Peak Crush is not a reversal call. It flags strong trend energy. That can precede continuation or exhaustion, you use it as context, not a standalone trade trigger.
How to use it
Trend following framework
Stay aligned with the regime color.
In bull regime, treat the outer boundary as the “structure floor.”
In bear regime, treat the outer boundary as the “structure ceiling.”
The inner DEMA is your fast guide, the outer edge is your compromise boundary.
Acceleration read
Increasing color intensity and thicker glow imply acceleration is strengthening.
Fading color and shrinking glow imply acceleration is decaying and the move is losing energy.
A regime flip is a clean state change, not a micro-signal.
Using reversal levels
Treat naked flip levels as potential reaction zones.
Watch first retest behavior, clean rejection suggests the flip level is holding.
If the level invalidates by 2.5 ATR, it’s removed because structure has been overwritten.
Key inputs explained
MA Length (maLen)
Sets both the lead line length and the lag line length (scaled by 1.5). Lower values:
More sensitive, more flips.
Higher values:
Smoother, fewer flips, slower response.
Crush Smoothing (crushSmth)
Controls stability of the velocity signal. Lower:
Fast flips, noisier regime.
Higher:
More confirmation, later flips.
Channel Padding (chanPad)
Controls how much extra ATR space is added beyond lagMA. Higher padding:
Wider channel, fewer boundary touches.
Lower padding:
Tighter boundary, more reactive “risk edge.”
Max Levels
Controls how many historical flip levels are retained.
Summary
Trend Velocity Channel treats trend as lead-lag separation expressed in ATR units. A fast DEMA tracks the active move, a slower EMA defines baseline value, and their normalized gap (Crush) defines both direction and acceleration strength . That strength drives an adaptive visual language (gradient color, glow width, ribbon depth). The channel itself is directional, with the lead line as the inner edge and a volatility-padded lag boundary as the outer edge, acting as a structural “compromise line.” On every regime flip the script plants a pivot level, tracks retests, and deletes invalidated levels, giving you a clean map of acceleration-based reversal zones. 지표

Mean Deviation Trend [BackQuant]Mean Deviation Trend
Overview
Mean Deviation Trend is a structure-based trend and regime indicator that measures directional pressure as the market’s sustained deviation from a moving “mean,” then uses that pressure to drive an adaptive band , dynamic coloring, and a level engine that marks deviation peak extremes after momentum fades.
Most trend tools start with direction, for example slope or MA cross, then try to estimate strength later. This script does the reverse:
It first quantifies how far price is displaced from a central mean in volatility-adjusted units .
It then smooths and accumulates that deviation to determine trend direction and conviction .
Finally it converts conviction into a band that tightens when pressure is strong and widens when pressure is weak.
The result is a single framework that blends:
A mean anchor (EMA).
A signed deviation engine normalized by ATR.
A conviction score based on sustained deviation.
An adaptive band that behaves like dynamic support/resistance.
A “deviation peak” level system that plants levels at extremes after the push fades.
Optional glow, fills, candle coloring, and flip markers.
Core concept: deviation from mean as trend fuel
A trend is not just “price up” or “price down.” A trend is a persistent imbalance where price spends time displaced from fair value and keeps re-asserting that displacement. This indicator treats the mean as a moving fair value proxy, and it measures how aggressively price is departing from it.
Key idea:
If price stays above the mean and that displacement is sustained, bullish pressure is dominant.
If price stays below the mean and that displacement is sustained, bearish pressure is dominant.
If price keeps snapping back and deviation cannot sustain, regime is weak and uncertainty is high.
This is why the script doesn’t rely on a single moment like a cross. It cares about persistence .
Mean anchor (the “center of gravity”)
The mean is defined as an EMA of close:
mean = EMA(close, meanLen)
Why EMA:
It responds faster than SMA to regime changes.
It provides a stable anchor without overreacting to single bars.
The mean line is not just a moving average here, it is the reference line that deviation is measured against. Everything downstream depends on the mean being a consistent “center.”
Volatility normalization (why ATR is essential here)
Raw distance from mean is meaningless across volatility regimes. A $200 deviation on BTC might be noise one week and huge another week. To fix this, the script normalizes deviation by ATR:
atr = ATR(14)
rawDev = (close - mean) / atr
Interpretation:
rawDev is “how many ATR units price is away from the mean.”
This makes deviation comparable across timeframes and volatility states.
This is critical because it turns the indicator into a dimensionless pressure metric rather than a price-distance tool.
Deviation smoothing (instantaneous pressure vs noisy pressure)
Instantaneous deviation can spike on one candle and mean nothing. So the script applies EMA smoothing to raw deviation:
devSmooth = EMA(rawDev, devLen)
What this does:
Reduces single-bar spikes.
Keeps the sign and general magnitude of displacement.
Creates a cleaner “pressure line” that responds but does not jitter.
This is the first stage of filtering: “Are we meaningfully deviating, or just wicking?”
Deviation accumulation (turning pressure into conviction)
This is the part that makes the indicator behave like a trend conviction model rather than a simple oscillator.
The script computes:
cumDev = SMA(devSmooth, devAccum)
Even though it’s coded as an SMA, conceptually it behaves like a rolling accumulation of the deviation signal:
If devSmooth stays positive for multiple bars, cumDev rises and stays positive.
If devSmooth stays negative for multiple bars, cumDev drops and stays negative.
If devSmooth flips sign repeatedly, cumDev compresses toward zero.
This is the key “persistence detector.” It converts short-term deviation into a medium-term conviction read.
Trend direction and flips
Trend direction is derived purely from the sign of cumulative deviation:
tDir = cumDev > 0 ? +1 : -1
flip = tDir != tDir
Interpretation:
Bull regime means the market’s sustained deviation is above the mean (pressure up).
Bear regime means sustained deviation is below the mean (pressure down).
A flip marks a regime transition where the sustained bias changes sign.
This is intentionally simple because all the complexity is in how cumDev is built.
Measuring conviction: devNorm (adaptive strength scale)
The script measures absolute conviction:
devAbs = abs(cumDev)
Then it normalizes it relative to a rolling peak:
devHigh = highest(devAbs, 80)
devNorm = devHigh > 0 ? min(devAbs / devHigh, 1) : 0
Meaning:
devNorm is a 0..1 strength scale.
0 means current conviction is tiny relative to recent extremes.
1 means conviction is at the strongest level seen in the last ~80 bars.
This is not a z-score, it’s a “relative-to-recent-peak” normalization. That matters because it makes the band behavior adapt to each instrument’s recent character, not a fixed threshold system.
Adaptive band logic (tight when confident, wide when uncertain)
The band is built to behave differently depending on conviction. When conviction is strong, the band should hug price and act like a close structural guide. When conviction is weak, the band should widen and stop pretending it is precise.
This is done by interpolating between two ATR multipliers:
bandTight = ATR multiplier when devNorm is high
bandWide = ATR multiplier when devNorm is low
bandMult = bandWide - devNorm * (bandWide - bandTight)
bandW = atr * bandMult
Interpretation:
devNorm near 1 → bandMult approaches bandTight → band width shrinks.
devNorm near 0 → bandMult approaches bandWide → band width expands.
So the band width is not arbitrary. It is a direct function of trend conviction.
Active band placement (trend-aware support/resistance)
The “active band” is placed on the opposite side of the mean depending on direction:
If bullish: activeBand = mean - bandW
If bearish: activeBand = mean + bandW
So in bullish regimes, the band behaves like a dynamic support zone beneath the mean. In bearish regimes, it behaves like dynamic resistance above the mean.
Then it is smoothed:
activeBand = EMA(activeBand, 3)
This prevents the band from stepping too harshly when ATR shifts.
Outer band (secondary structure reference)
A second band is created at half width on the opposite side:
bull: outerBand = mean + bandW * 0.5
bear: outerBand = mean - bandW * 0.5
Then smoothed again. This outer line is not the main “stop band,” it is more of an additional structure marker to show where the mean plus/minus partial deviation zone sits. It can help visually gauge whether price is extended relative to the mean structure while still in the same regime.
Color system (strength-aware gradient)
The trend color is not binary. It is strength-weighted:
If bullish, devNorm drives a gradient from a faint bull tint to full bull.
If bearish, devNorm drives a gradient from a faint bear tint to full bear.
This gives you an immediate read:
Bright strong color = conviction high.
Faded color = conviction low, regime fragile.
It also ties into the glow and fill so the whole visual language matches the same underlying “pressure” variable.
Deviation peak level engine (how the script plants levels)
This indicator includes a separate mechanism that marks important extremes after a strong deviation push fades. The idea is:
When trend pressure peaks and then collapses, the extreme price printed at peak deviation often becomes a reaction level later.
This is similar in spirit to:
exhaustion extremes,
climactic deviation points,
distribution/accumulation turning zones,
but the script formalizes it using the deviation engine.
1) Track the strongest deviation peak
The script stores a running peak:
peakDev: maximum devAbs seen since last reset
peakPrice: the extreme price at that peak (high for bull, low for bear)
peakDir: direction at peak
peakBar: bar index of peak
When devAbs prints a new high, it updates those values.
2) Define “fade” (momentum has cooled)
A fade event triggers when:
peakDev is meaningfully large (peakDev > 0.3)
current devAbs drops below a fraction of the peak: devAbs < peakDev * fadeThr
fadeThr is the key user control. Lower fadeThr requires a deeper drop from peak before planting a level.
What “fade” means in practice:
A strong push happened (deviation expanded).
That push is no longer active (deviation contracted).
So the extreme created during the push is now “locked in” as a candidate level.
3) Plant a level at the extreme
When faded:
A dashed horizontal line is created at peakPrice.
The line is projected forward (bar_index + 60).
It is stored in an array with direction and retest state.
It also respects maxLvls by deleting the oldest levels to avoid clutter.
4) Maintain levels and delete invalid ones
Each bar, levels are checked:
If price breaks far beyond the level (by about 2 ATR in the wrong direction), the level is deleted.
That “broken” rule is a pragmatic invalidation filter. If price rips through a former deviation extreme by a large margin, the level is no longer acting like a meaningful reaction zone.
5) Detect retests and mark them
A retest is detected when:
close is within ~0.25 ATR of the level,
and two bars ago price was not near it (distance > 0.5 ATR),
and the level hasn’t already been marked as retested.
When that happens:
A diamond marker is printed (◆) above or below depending on approach.
The level is flagged as retested so it won’t spam markers.
So levels are not just static drawings. They have state: naked vs retested, and they get culled if invalidated.
Glow system (volatility-scaled aesthetic, strength-scaled intensity)
Glow is not random decoration here. Its width scales with devNorm:
glowMult = 0.4 + devNorm * 1.2
glowW = atr * 0.08 * glowMult
So in strong trends:
Glow band expands.
The mean core visually “radiates” more.
In weak trends:
Glow shrinks and becomes less prominent.
The glow is built using multiple invisible plots above and below the mean, then layered fills with different transparencies. It creates a soft gradient aura around the mean that encodes strength.
Band fill and line break behavior
The active band is plotted with plot.style_linebr and forced to break on flips:
bandBrk = flip ? na : activeBand
This prevents the band from drawing a misleading connecting line across a regime change. It visually resets when direction flips, which matters because the band swaps sides of the mean when regime changes.
Fill is drawn between:
the active band line
and hl2 (mid-price reference)
So you get a shaded zone that reflects the current regime color and strength.
Candles and flip labels
Candles can be colored by the same strength-weighted regime color, which makes the entire chart consistent.
On flips:
Bull flip prints ▲ at the low.
Bear flip prints ▼ at the high.
These are regime markers, not “entry signals” by default. They simply identify when the cumulative deviation sign changed.
How to read this indicator in practice
1) Regime and conviction
Direction comes from cumDev sign.
Conviction comes from devNorm intensity.
Bright color + stable band on one side means strong sustained pressure.
Faded color + widening band means weak sustained pressure and higher uncertainty.
2) Using the active band as structure
In a bullish regime, activeBand is below mean and can behave like:
dynamic support,
risk boundary,
trend “line in the sand.”
In bearish regime, it flips above mean and acts like dynamic resistance.
Because the band widens when conviction is low, it naturally tells you “do not treat this as a tight stop zone when the trend is weak.”
3) Using deviation peak levels
Peak levels represent exhaustion extremes after a strong deviation impulse faded:
If price returns to a naked level, that area can act as a reaction zone.
Once retested, the script marks it and treats it as less “special.”
If price breaks it by a wide margin, the script removes it as invalid.
This level engine is best viewed as “structural memory of deviation events,” not generic support/resistance.
4) Extreme deviation alert
devNorm > 0.85 means the current sustained deviation is near the strongest seen recently. That’s useful for:
identifying trend climax states,
detecting when continuation is strong but risk of snapback rises,
flagging conditions where mean reversion pressure is building.
It does not guarantee reversal, it flags “stretch.”
Inputs and what they actually change
Mean Length (meanLen)
Controls the anchor responsiveness:
Lower = mean follows price more closely, deviation shrinks, more frequent flips.
Higher = mean is slower, deviation grows, trend regimes last longer.
Deviation Smoothing (devLen)
Controls how noisy the deviation signal is:
Lower = faster response, more jitter.
Higher = smoother pressure, slower flips.
Deviation Accumulation (devAccum)
Controls persistence requirement:
Lower = trend conviction reacts quickly but can whipsaw.
Higher = requires sustained deviation, fewer flips, more confirmation.
Band Tight / Band Wide
These define the band behavior range:
bandTight: how close the band gets when conviction is strong.
bandWide: how far it drifts when conviction is weak.
If you want the band to behave more like a stop guide, reduce bandWide. If you want it to act more like a regime boundary, increase bandWide.
Fade Threshold + Max Levels
These shape the level engine:
fadeThr lower = requires bigger cooling before planting levels (fewer, more meaningful).
fadeThr higher = plants levels earlier (more levels, more noise).
maxLvls controls clutter and historical depth.
Alerts (what they represent)
Dev Bull / Dev Bear: regime flips, cumulative deviation changed sign.
Dev Faded: a deviation peak cooled enough to plant a level.
Extreme Dev: sustained deviation is near local maximum, stretch condition.
Summary
Mean Deviation Trend models trend as sustained, volatility-normalized displacement from a mean rather than simple direction. It smooths and accumulates signed deviation to extract regime and conviction, then converts that conviction into an adaptive ATR band that tightens when pressure is strong and widens when pressure is weak. On top of that, it tracks deviation peak extremes and plants forward levels only after deviation fades, creating a structured map of “where trend impulses peaked” and how price reacts when those zones are revisited. 지표

Parkinson Range Oscillator [BackQuant]Parkinson Range Oscillator
Overview
Parkinson Range Oscillator is a volatility regime indicator built around the Parkinson volatility estimator , a high-low based variance model originally proposed as a more statistically efficient alternative to close-to-close volatility. Instead of measuring volatility from closing returns, this script measures volatility from the intrabar price range using ln(H/L), then converts it into a normalized oscillator (z-score) so you can identify volatility expansion vs compression relative to the asset’s own history.
The indicator is designed to answer questions like:
Is volatility currently elevated or suppressed relative to its baseline?
Is volatility expanding (risk rising) or compressing (coiling)?
How extreme is the current vol state in percentile terms?
How does range-based vol compare to a more common ATR-based vol read?
It plots:
A Parkinson-based volatility z-score oscillator with gradient fills.
A signal line (EMA) for expansion/compression transitions.
An ATR-based z-score for context comparison.
A dashboard with current vol %, z-score, percentile rank, regime label, and ATR z-score.
Where Parkinson volatility comes from (origin and intuition)
The Parkinson estimator comes from academic finance and the study of volatility estimation. The key insight is simple:
The daily high and low contain more information about variability than the close alone.
Close-to-close volatility only uses one price per bar (the close), throwing away intrabar information. The high-low range captures the realized dispersion inside the bar, so under ideal assumptions it can estimate variance more efficiently.
The Parkinson model is derived assuming:
Price follows a continuous-time diffusion process (often framed like geometric Brownian motion).
No drift matters for the variance estimate over the interval.
No jumps and no microstructure distortions (idealized).
Even though real markets violate these assumptions (gaps, jumps, wicks from order flow), the estimator remains useful because:
Range is still a strong proxy for realized volatility.
It reacts to intrabar expansion earlier than close-based methods.
It is less dependent on where the bar closes.
Core Parkinson formula (what the script implements)
Parkinson variance for a window of n bars is:
Var = (1 / (4 * n * ln(2))) * Σ
This script computes it in the common rolling form:
logHL2 = (ln(high/low))²
parkVar = SMA(logHL2, n) / (4 * ln(2))
parkVol = sqrt(parkVar) * 100
Key details:
ln(H/L) makes the range scale-invariant (percent-like), so it behaves more consistently across price levels.
Squaring gives variance contribution.
The 1/(4 ln 2) constant comes from the expected distribution of high-low range under a Brownian diffusion.
sqrt converts variance to standard deviation (volatility).
*100 expresses it as a percentage for readability.
So parkVol is a “range-based realized volatility proxy” in percent terms.
Why range-based volatility behaves differently than ATR
ATR measures average true range, which is a linear range magnitude measure (high-low plus gaps). Parkinson uses ln(H/L) which is:
Log-scaled (closer to a return-based measure).
More directly tied to variance estimation theory.
In practice:
ATR can be driven by gaps and absolute range.
Parkinson is driven by proportional range and tends to emphasize how wide the bar is relative to its price level.
Parkinson often reacts sharply when wicks expand even if closes are stable.
Normalization into an oscillator (making it comparable through time)
Raw volatility values are hard to interpret across regimes because every market has different “normal.” This script normalizes Parkinson volatility against its own rolling baseline using a z-score:
parkMA = SMA(parkVol, baselineLen)
parkSD = stdev(parkVol, baselineLen)
osc = (parkVol - parkMA) / parkSD
Interpretation:
osc = 0 means current vol is at its baseline average.
osc = +1 means 1 standard deviation above normal (high vol).
osc = -1 means 1 standard deviation below normal (compressed).
osc > +2 flags extreme expansion states.
This is the core output. It turns “volatility” into “volatility regime” in standardized units.
Signal line and expansion/compression transitions
The oscillator is smoothed with an EMA to create a signal line:
signal = EMA(osc, signalLen)
Then transitions are defined as:
Expansion cross: crossover(osc, signal) and osc > 0
Compression cross: crossunder(osc, signal) and osc < 0
Why the extra osc > 0 and osc < 0 conditions:
It prevents treating small oscillations around zero as meaningful.
It forces expansion signals to occur in above-average volatility territory.
It forces compression signals to occur in below-average volatility territory.
So signals are regime-confirming, not constant cross spam.
Percentile rank (how extreme is vol relative to the past)
In addition to the z-score, the script computes the percentile rank of the raw Parkinson volatility:
pctRank = percentrank(parkVol, pctRankLookback)
Interpretation:
pctRank near 90–100 means current vol is among the highest levels seen in that lookback.
pctRank near 0–10 means it is among the lowest (compression).
Z-score tells you “how many SDs from mean.” Percentile tells you “how rare is this state historically.” Those are different but complementary.
ATR comparison line (context, not the main engine)
The indicator also computes an ATR-based volatility proxy and normalizes it in the same way:
atrVol = ATR(n) / close * 100
atrOsc = zscore(atrVol, baselineLen)
This gives you a direct visual comparison:
If Parkinson oscillator is high but ATR oscillator isn’t, range expansion may be happening in a way ATR is not emphasizing (or vice versa).
If both agree, you have stronger confirmation of a true volatility regime shift.
ATR is included as a “common benchmark,” not as the primary signal.
Regime classification (human-readable state mapping)
The script labels regimes from osc:
osc > 2.0 → EXTREME
osc > 1.0 → HIGH
osc > 0.0 → ABOVE AVG
osc > -1.0 → BELOW AVG
else → COMPRESSED
This is a practical mapping for dashboards and quick reads. It is not pretending that 2.0 is a universal constant, it is just a standardized “rare expansion” threshold.
Coloring follows the same logic:
More positive = more “expansion” coloring (bearCol).
More negative = more “compression” coloring (bullCol).
Note: the color naming is semantic here:
“Low Vol / Compression” is bullCol because compression often precedes trend expansion opportunities.
“High Vol / Expansion” is bearCol because high vol often implies risk, disorder, liquidation, or unstable conditions.
You can interpret those however you prefer, the tool is measuring volatility regime, not directional bias.
Plot design (why the oscillator is split into positive/negative)
The oscillator is split into two series:
oscPos = osc if osc > 0 else na
oscNeg = osc if osc < 0 else na
This is purely for visuals:
Positive region is drawn with expansion color and expansion gradient fill to zero.
Negative region is drawn with compression color and compression gradient fill to zero.
This makes it obvious at a glance which side of “normal volatility” you’re on.
How to interpret the indicator correctly
1) The oscillator is volatility regime, not price direction
High osc does not mean price will go down. It means the market is moving violently relative to its baseline. That can occur in:
Selloffs, liquidations, panic.
Breakouts and momentum expansions.
News-driven repricing.
Low osc does not mean price will go up. It means the market is quiet relative to baseline:
Ranges, coils, low realized movement.
Slow grind trends with suppressed pullbacks.
Pre-breakout compressions.
2) Compression regimes are often “setup states”
When osc is deeply negative (compressed), it often indicates that realized movement has collapsed. In many markets this precedes:
Breakouts (vol expansion from compression).
Trend acceleration.
Mean reversion bursts.
But compression can also persist. This is why the script includes signal crosses and percentile rank to judge when compression is shifting.
3) Expansion regimes are often “risk states”
When osc is positive and rising, the environment is more chaotic:
Stops are more likely to be hit.
Mean reversion can get violent.
Trend continuation can be strong but timing becomes harder.
In those regimes, the tool can be used to:
Reduce leverage.
Widen stops (if your system supports it).
Switch to volatility-aware sizing.
Wait for stabilization if you trade mean reversion.
4) Use percentile rank to identify “rare” volatility
Two markets can both show osc = +1, but one might be at the 95th percentile and the other at the 70th depending on distribution shape. Percentile tells you whether the current vol is truly rare in that lookback.
Cross dots (how to treat them)
ExpansionCross and CompressionCross are not buy/sell signals. They are “volatility phase change” markers:
ExpansionCross: vol regime moving up, above baseline, acceleration risk increases.
CompressionCross: vol regime moving down, below baseline, quieting environment.
These are useful for:
Strategy toggles (trend mode vs chop mode).
Sizing changes.
Timing filters (avoid entries during extreme expansion if your edge hates noise).
Dashboard (what it gives you at a glance)
The table summarizes everything that matters without you needing to interpret plots manually:
Parkinson Vol %: current raw range-based volatility level.
Z-Score: current standardized regime reading.
Percentile: rarity of current vol in the lookback.
Regime: discrete label based on z-score thresholds.
ATR Z-Score: comparison metric in standardized units.
The dashboard is positioned and sized via inputs so it can fit different chart layouts.
Parameter tuning guidance
Parkinson Length
Controls how quickly the raw Parkinson vol responds:
Shorter = more reactive to immediate range changes.
Longer = smoother volatility estimate, less noisy.
Baseline Length
Controls what “normal” means:
Long baseline (like 100) creates stable regime definitions.
Short baseline makes z-scores jump around and can overreact.
Signal Length
Controls how quickly you detect regime turning points:
Short signal = more crosses, earlier detection, more noise.
Long signal = fewer crosses, later detection, cleaner regime shifts.
Percentile Lookback
Controls rarity context:
252 approximates one trading year on daily charts.
On intraday, it becomes “252 bars,” so adjust to match your horizon.
Limitations and what to watch for
Parkinson assumes continuous diffusion. Jumps and gaps can distort it.
Wicks caused by illiquidity can inflate ln(H/L) and produce false “expansion.”
Z-score assumes the baseline distribution is reasonably stable. If volatility distribution shifts structurally, your z-scores can be biased until baseline catches up.
Percentile rank is lookback-dependent. Different lookbacks can change “rarity” classification materially.
Summary
Parkinson Range Oscillator converts a statistically grounded high-low volatility estimator into a regime oscillator by z-scoring Parkinson volatility against its own rolling baseline. It highlights expansion vs compression states with clear gradients, flags volatility phase changes via oscillator-signal crosses, ranks current volatility by percentile for rarity context, and overlays an ATR-based z-score for comparison. This makes it a practical tool for volatility-aware trading, regime filtering, sizing adjustments, and identifying compression-to-expansion transitions. 지표

LOWESS Adaptive Envelope [BackQuant]LOWESS Adaptive Envelope
Overview
LOWESS Adaptive Envelope is a nonparametric trend-fit and volatility envelope tool built around LOWESS (Locally Weighted Scatterplot Smoothing). Instead of smoothing price with a fixed-form moving average, this indicator performs a rolling set of local weighted linear regressions across a chosen historical window and stitches those local fits into a single smooth curve that adapts to changing market structure.
On top of the fitted curve, the script builds an adaptive envelope whose width is driven by the local magnitude of the model’s residuals (how far price deviates from the fit). That means the envelope automatically expands when the market is noisy or trending aggressively, and contracts when price is stable or mean-reverting cleanly.
The output is a complete “structure map”:
A LOWESS fitted centerline (trend estimate).
Upper and lower adaptive bands derived from smoothed residual spread.
A filled region that changes color based on where price sits relative to the fit.
Optional extrapolation of the fit and envelope into the future using last slope, with widening uncertainty.
An info label showing fit quality (R²), position inside the envelope, and direction.
Where LOWESS comes from (and why it is different from moving averages)
LOWESS (also written LOESS) is a classic statistical smoothing technique used in exploratory data analysis and robust curve fitting. It became popular because it can approximate complex shapes without assuming a single global model. Instead of forcing the entire window to follow one equation (like a single linear regression or a single moving average kernel), LOWESS fits many small local regressions , each one tailored to its neighborhood.
Key distinction:
A moving average is a fixed smoother, it applies the same weighting rule everywhere, regardless of whether the market is trending, chopping, or accelerating.
LOWESS is a locally re-fitted model, it re-estimates slope and intercept at each point based on nearby data.
In price terms:
LOWESS is better at “hugging structure” when the market curves or transitions.
It can follow gradual regime shifts without the same lag profile as long-window MAs.
It does not assume the trend is constant across the whole lookback, it assumes trend can vary locally.
What the indicator is modeling
Think of the lookback window as a dataset of points:
x = bar index (0..length-1 inside the window)
y = price
For every point i inside that window, the indicator estimates the best local line:
y ≈ a + b * x
But it does this using only nearby points, and it weights them by distance from i. So the fitted value at i is a locally weighted regression prediction.
The final fitted curve is the collection of those predictions across i = 0..length-1.
Core mechanics: local weighted linear regression
1) Neighborhood size (bandwidth)
The “locality” is controlled by a bandwidth parameter. In this script:
h = max(bandwidth * length / 2, 2)
Interpretation:
h acts like a radius measured in bars inside the fitting window.
Lower bandwidth → smaller h → more local fit (more responsive, can track curvature, more sensitive to noise).
Higher bandwidth → larger h → more global fit (smoother, more stable, more lag in transitions).
So bandwidth controls the bias-variance tradeoff:
Small bandwidth: low bias, high variance.
Large bandwidth: higher bias, lower variance.
2) Tricube kernel weighting
LOWESS requires a weight function that decays smoothly with distance. This script uses the classic tricube kernel :
For each candidate point j around target i:
u = |i - j| / h
If u < 1:
- w = (1 - u³)³
If u ≥ 1:
- w = 0
Why tricube:
Weights go to zero smoothly at the boundary (no sharp cutoff artifacts).
Nearby points dominate the fit, distant points contribute little or nothing.
It is a standard LOWESS choice because it produces stable smooth curves.
3) Weighted least squares fit
For each i, the script accumulates weighted sums over j in the neighborhood:
sumW, sumWX, sumWY, sumWXX, sumWXY
These correspond to the normal equations for weighted linear regression. From those, it computes:
denom = sumW * sumWXX - sumWX²
a and b derived from sums (intercept and slope)
fitted = a + b * i
If denom is too small (numerical instability, insufficient variation), it falls back to the raw price at that i.
This entire process is repeated for every i in the window, which is why it is done only on the last bar (performance).
Why it fits inside the window rather than a single line
A single regression across 200 bars assumes one slope b explains the whole move. Markets rarely do that. LOWESS allows the slope to drift through time, which is exactly what “trend structure” actually does in real price.
Residuals: turning model error into volatility structure
Once the LOWESS fitted curve is computed, the script measures the residual at each point:
res = price - fitted
Residuals are the model’s error. In trading terms, residual magnitude is a proxy for:
Local noise level.
Deviations from trend structure (overextension/underextension).
Regime instability (trend is less “explanatory”).
The script takes absolute residuals:
absRes = |res |
This is important because envelope width should reflect spread size regardless of direction.
R²: fit quality and regime information
The indicator also computes R² over the window:
ssRes = Σ(res²)
ssTot = Σ((price - meanPrice)²)
R² = 1 - ssRes/ssTot
Interpretation:
Higher R² means the LOWESS fit explains more of the variation inside the window.
Lower R² means price is behaving in a way the smooth trend model cannot explain well (chop, shocks, irregular volatility).
In markets, R² can be read as “how trend-like vs how noisy” the recent environment is, but remember it depends on your chosen length and bandwidth.
Adaptive envelope construction (what makes it “adaptive”)
A normal envelope uses a constant width (like ±k*ATR or ±k*stdev). This script does something different: it estimates a local envelope width based on smoothed residual magnitude.
1) Smooth residual magnitude locally
It computes a residual averaging window:
rWin = max(3, int(h * 0.8))
So the residual smoothing window is linked to the LOWESS locality. If the fit is local, the envelope adapts locally. If the fit is global, the envelope adapts more slowly.
Then for each i:
envW = mean(absRes over ) * envMult
Interpretation:
The envelope width is proportional to how much price typically deviates from the fit around that region.
envMult is your “how many spreads” multiplier.
This creates an envelope that expands and contracts along the curve, not a single constant band.
2) Upper and lower envelopes
For each i:
upper = fitted + envW
lower = fitted - envW
This is a model-driven channel. It is not ATR-based directly, it is “error-based.” That makes it very effective at responding to the actual behavior of the market relative to the fitted structure.
How to interpret the envelope
The centerline is the best local structural estimate. The envelope is the expected deviation range around that structure.
Typical readings:
Price near centerline: balanced relative to structure.
Price riding upper band: strong bullish pressure, trend continuation or overextension depending on context.
Price riding lower band: strong bearish pressure, continuation or overextension.
Repeated band rejections: mean-reversion regime around the structural fit.
Envelope widening: instability rising, volatility expanding, structure less reliable.
Envelope tightening: compression, cleaner trend or coiling behavior.
Because the band width is based on residuals, widening often coincides with “trend breaks” and regime transitions, not just higher ATR.
Color logic and visual encoding
The envelope fill color is based on price relative to the most recent fitted value:
If close > fitted , bullish color.
Else bearish color.
So color is a regime/bias cue, not a volatility cue. The bands themselves are drawn with translucent versions of the same regime color, while the fit line is a subtle white.
The fill polygon is constructed by:
Walking forward through upper points.
Then walking backward through lower points.
So the shape is closed and can be filled cleanly using polyline fills.
Extrapolation: forward projection with widening uncertainty
This script can project the fitted line into future bars. This is not forecasting in a statistical sense, it is a deterministic extension based on the current slope.
How it extrapolates
It takes:
slope = fitted - fitted
lastFit = fitted
Then for i = 1..extrapBars:
futureFit = lastFit + slope * i
This is a linear continuation of the most recent fit direction. It is meant as a visual guide for “if the current local trend continues.”
Why the forward envelope widens
The script also grows the envelope slightly with each projected bar:
envGrow = lastEnv * 0.01
futureEnv = lastEnv + envGrow * i
This is a simple uncertainty widening mechanism. As you move further into the future, you should assume less confidence. The envelope expansion encodes that visually without claiming statistical rigor.
Info label: what it reports and how to read it
When enabled, the label shows:
1) Direction arrow
It computes a slope over the last few fitted points:
recentSlope = fitted - fitted (or closest valid index)
▲ if slope >= 0
▼ if slope < 0
This gives a slightly more stable direction read than one-bar slope.
2) R²
Displayed as R²: 0.xxx, representing how well the LOWESS curve explains window variation.
3) Envelope Position (Env Pos)
It measures where the current close sits inside the latest envelope:
0% = at lower band
50% = at centerline
100% = at upper band
This is extremely useful as a normalized “over/under extension” metric because it is scaled by the adaptive band width, not raw price units.
How to use it properly
Trend structure and regime filtering
Use the fit line as structural trend direction.
Use the fill color as quick bias context.
Use R² as a “trend quality” read: high R² tends to mean cleaner structure, low R² tends to mean chop or instability.
Mean reversion vs continuation
This tool can support both styles, but interpretation differs:
Mean reversion framing
If market repeatedly returns to the fit line, the fit is acting like value.
Upper band touches can be “overbought relative to structure.”
Lower band touches can be “oversold relative to structure.”
Envelope position becomes your normalized stretch gauge.
Trend continuation framing
In strong trends, price can ride a band rather than revert to centerline.
Band riding plus rising fit slope suggests persistence.
A sudden failure to hold the band plus falling R² can flag transition risk.
Breakdown/transition identification
Because the envelope width is residual-driven:
If price starts producing large residuals, the envelope expands.
That expansion is often a signature of regime change, not just volatility.
Combine expansion with slope flattening to identify trend exhaustion.
Parameter tuning (what each input really does)
Length
Defines how much historical data is used for the full fit. Larger length:
More stable curve.
More computational load.
Tends to represent macro structure.
Bandwidth
Controls locality:
Low bandwidth (0.10–0.25): more reactive, tracks curvature and micro-structure, more sensitive to noise.
Higher bandwidth (0.30–0.50+): smoother, more stable, more lag in fast turns.
Envelope Width (envMult)
Scales how wide the adaptive band is relative to the local residual spread:
Lower values create a tighter channel, more band interactions.
Higher values create a wider channel, fewer touches, better for regime filtering.
Extrapolation Bars
Purely visual. More bars gives a longer projected structure line and uncertainty region.
Limitations and correct expectations
LOWESS is powerful, but it is not a magic predictor.
LOWESS is descriptive, it fits what happened, then projects linearly if extrapolation is enabled.
In sudden shocks or gaps, the fit will update only after the new data is inside the window.
Very small bandwidth can overfit local noise, producing misleading curvature.
Very large bandwidth can underfit, behaving like a slow regression and missing turning points.
R² is window-dependent, a low value does not mean “bad indicator,” it often means “market is not smooth right now.”
Summary
LOWESS Adaptive Envelope applies locally weighted linear regression (LOWESS) with a tricube kernel to build a smooth, structure-following fitted price curve that adapts to regime changes without relying on a fixed moving-average form. It then converts the model’s local residual spread into a dynamic envelope that expands and contracts with real deviation behavior, provides fit quality via R², normalizes price position inside the band, and optionally extrapolates the latest structural slope forward with widening uncertainty. The result is a robust trend-structure and deviation framework that is equally useful for regime filtering, mean-reversion context, and trend persistence assessment. 지표

Harmonic Frequency Visualizer [BackQuant]Harmonic Frequency Visualizer
Overview
Harmonic Frequency Visualizer is a cycle-analysis and cross-asset resonance tool that uses a simplified Discrete Fourier Transform (DFT) to measure how strongly specific cycle periods are present in price. It is not a “trend indicator” and it is not trying to predict direction by itself. Its job is to quantify rhythm: which repeating periods (in bars) are currently dominant, whether those cycles are expanding or contracting (phase direction), and whether multiple instruments are sharing the same dominant periods at the same time (resonance).
This indicator has two main output modes:
Spectrum : a frequency “snapshot” showing amplitude at each tested period for up to five instruments.
Spectrogram : a history heatmap showing how the spectrum evolves through time (for the chart instrument).
Spectrum
Spectrogram
On top of that, it produces a Dominant Cycle Oscillator derived from the dominant cycle’s phase, which gives a continuous cycle position metric (peak/trough style zones) without repainting.
This is designed for traders who want cycle context the same way they want volatility context: not as a magic signal, but as structure.
What “frequency” and “cycles” mean in trading terms
A cycle period (say 21 bars) means: “a repeating pattern that tends to complete one full oscillation every 21 bars.” If price contains such a pattern, the DFT will detect a strong correlation between price and a 21-bar sine/cosine wave.
Markets do not have perfectly stable periodic motion, but they often show:
Mean-reverting swings around value.
Trend pulses with pullback cadence.
Volatility clustering that creates rhythmic expansions and contractions.
Cycle tools are trying to measure those repeating components, and DFT is the standard mathematical way to do it.
Where DFT comes from (the core idea)
The Discrete Fourier Transform comes from Fourier analysis, a foundational signal processing concept:
Fourier’s idea : any sufficiently well-behaved signal can be expressed as a sum of sine and cosine waves at different frequencies, each with:
An amplitude (how strong that wave is).
A phase (where you are within the wave cycle).
In continuous math you get the Fourier Transform. In sampled data (like candles) you use the Discrete Fourier Transform. It converts a time series (price over time) into a frequency description (strength of different cycles).
In markets:
Time domain: candles and price series.
Frequency domain: cycle periods and their strengths.
Why sine and cosine, not just sine
A sine wave alone cannot represent every phase alignment cleanly. DFT uses both cosine and sine components because together they form an orthogonal basis that can represent any phase shift.
You can think of it like this:
Cosine component captures “in-phase” alignment with the cycle.
Sine component captures “quadrature” (90-degree shifted) alignment.
Combining them gives full information: amplitude + phase.
Mathematically, a single frequency component can be written as:
A * cos(ωt + φ)
But DFT estimates A and φ by separately accumulating cosine and sine projections.
How this script implements the DFT (and what it is actually measuring)
This is not a full-spectrum FFT across every frequency. It is a targeted DFT across a fixed set of cycle periods:
Tested periods
The script tests 8 predefined periods:
5, 8, 13, 21, 34, 55, 89, 120
These are Fibonacci-like cycle candidates commonly used in cycle/market structure work. The point is not that Fibonacci is magic. The point is that these represent a reasonable spread from short to long rhythms without needing hundreds of frequencies (which would be heavy in Pine).
Normalization step (important)
Before computing the DFT, the script normalizes the series:
mn = SMA(src, lookback)
sd = stdev(src, lookback)
norm = (src - mn) / sd (if sd != 0)
Why normalize:
DFT amplitude depends on the scale of the input series.
If you compare BTC and TLT raw prices, the magnitude is meaningless.
Z-score normalization makes amplitude more comparable across instruments and regimes.
So the spectrum is measuring “cyclical structure in standardized deviations,” not raw dollars.
Projection onto cosine and sine
For each tested period P:
ω = 2π / P (angular frequency for that period)
Compute:
- sCos = Σ(norm * cos(ωk))
- sSin = Σ(norm * sin(ωk))
Interpretation:
You are correlating the last window of normalized price with a cosine wave of period P.
And also correlating it with a sine wave of period P.
If the price has a strong P-bar rhythm, these sums grow in magnitude.
Window length detail
The script uses:
window = min(lookback - 1, 99)
So even if lookback is 200, the internal DFT accumulation caps at 100 bars for performance stability. This is a deliberate trade: stable computation in Pine, while still letting you define normalization lookback and overall context.
Amplitude computation
Once sCos and sSin are computed:
raw magnitude = sqrt(sCos² + sSin²)
This is the length of the vector (sCos, sSin). That vector length is the standard way to combine the orthogonal components into one strength metric.
Then it scales it into a 0–100 “display amplitude”:
amp = sqrt(sCos² + sSin²) / lookback * 100 * sensitivity
amp is capped to 100
So:
Higher amplitude means stronger alignment with that cycle period.
Sensitivity is a user control to amplify or damp the display scaling.
Important: amplitude here is not a probability, and it is not guaranteed “signal quality.” It is a standardized “how much of that cycle exists in the recent window” metric.
Phase computation
Phase is computed using atan2(sSin, sCos). That matters because:
A simple atan(sin/cos) fails in different quadrants.
atan2 correctly resolves the angle from -π to +π.
Phase tells you where you are within the cycle:
Two cycles can have same amplitude but opposite phase.
Phase is what lets you infer “approaching peak vs trough” behavior.
Dominant cycle selection
The script chooses the dominant cycle as the period with the highest amplitude among the tested periods:
domIdx = argmax(amp )
domAmp = max amplitude
domPhase = phase at domIdx
This dominant cycle is used for:
Spectrogram history matrix (chart symbol).
Dominant cycle oscillator.
Data window outputs (dominant period, oscillator value).
Spectrum View: what you see and how to read it
In Spectrum mode, the indicator draws a frequency snapshot for up to five instruments. Each instrument gets a spectrum line (or bars/area depending on style) plotted across the 8 periods on the x-axis, with amplitude (0–100) on the y-axis.
X-axis meaning
Each x position corresponds to a period (5 → 120 bars). You are not looking at “frequency in Hz.” You are looking at “period in bars,” which is more intuitive in trading.
Y-axis meaning
Amplitude is a scaled measure of how strongly that period is present in the recent normalized data. Higher means stronger.
Plot styles
Waveform: connects amplitude points into a continuous shape, best for seeing spectrum shape.
Bars: draws vertical bars per period, best for quick comparison.
Area: similar to waveform but filled toward baseline for emphasis.
Dominant peaks and phase direction labels
The script highlights dominant cycles per symbol (if enabled):
If max amplitude > 20, it labels that peak with the symbol name.
If Show Phase Direction is enabled, it appends ▲ or ▼.
Phase direction logic:
rising = sin(phase) < 0
▲ means cycle is in a “rising” phase segment
▼ means cycle is in a “falling” phase segment
This is not “price will rise now.” It is “the dominant cycle’s instantaneous phase suggests you are on the upward vs downward half of that oscillation.” In real markets, you use this as context, not as a standalone trade trigger.
It also draws small ▲/▼ markers on secondary peaks (amp > 15) to show phase direction of other meaningful cycles, giving you a richer picture than “one dominant period.”
Resonance Zones: cross-asset harmonic alignment
Resonance is where this tool becomes more than a single-chart curiosity.
What resonance means here
A resonance zone is flagged when at least 3 out of 5 instruments have strong amplitude at the same tested period. Mechanically:
For each period i:
- Count instruments with amp > 30
- If count >= 3, mark resonance at that period
When resonance is detected:
A vertical highlight box is drawn behind that period.
A ⚡ marker is printed at the top.
Interpretation:
Multiple assets are expressing a similar cycle length at the same time.
This can indicate macro rhythm, shared liquidity timing, or cross-market synchronization.
This is especially useful when your instrument set includes:
Rates proxy (TLT), commodities (oil, gold), and crypto indices.
You can visually spot when markets are “vibrating” together at a shared period.
Resonance is not automatically bullish or bearish. It is telling you “cycle length agreement,” which can help with timing models and contextual trade planning.
Spectrogram View: frequency over time
Spectrum mode is a snapshot. Spectrogram mode adds time evolution.
What a spectrogram is
A spectrogram is a 2D heatmap where:
Rows = different periods (frequency bands).
Columns = time history (bars ago → now).
Color = amplitude strength.
This allows you to see:
Which cycles are persistent vs fleeting.
When dominant cycle shifts occur (energy moves from one period to another).
Cycle regime transitions (short cycles dominating in chop vs longer cycles dominating in trend).
How the script builds the spectrogram matrix
It maintains a matrix with:
NUM_PERIODS rows (8 periods)
histBars columns (history length)
Each bar:
Remove the oldest column.
Append the newest amplitude array from chartSpec.
So the spectrogram is always a rolling history of the chart symbol’s cycle amplitudes. It does not attempt to store five symbols (too heavy), it focuses on the active chart for time evolution.
Heat coloring
Amplitude values map to a custom gradient:
Low = dark blue
Mid = blue/cyan to orange
High = yellow
This makes dominant energy bands visually obvious. A stable bright band means persistent cycle dominance.
Dominant Cycle Oscillator: phase mapped to a 0–100 oscillator
The oscillator is derived from the dominant cycle phase (chart symbol):
oscRaw = cos(domPhase)
oscValue = 50 + 50 * oscRaw (maps -1..1 into 0..100)
Interpretation:
When cos(phase) ≈ +1, oscillator near 100 (cycle peak zone).
When cos(phase) ≈ -1, oscillator near 0 (cycle trough zone).
Midline 50 corresponds to the quarter-cycle transition points.
It also colors the oscillator by phase direction:
oscRising = sin(domPhase) < 0
Rising phase = green-ish
Falling phase = red-ish
This gives you a clean timing reference:
The dominant period tells you the cycle length.
The oscillator tells you where you are within that cycle.
It is not forecasting price. It is telling you the current phase position of the strongest detected cycle component.
Alerts and practical timing usage
Alerts are based on the oscillator:
Cross above 80: dominant cycle entering peak zone.
Cross below 20: dominant cycle entering trough zone.
Cross 50: midline cross (phase transition).
In practice, you use these as “timing context” alerts, for example:
If your trend model is bullish and cycle oscillator enters trough zone, it can hint at a favorable pullback timing window.
If you are mean-reversion trading and cycle peak zone aligns with resistance, that confluence matters.
Again: cycle timing needs structure confirmation. The oscillator alone is not a trade system.
Multi-instrument design and non-repaint behavior
The indicator requests five external instruments via request.security. It uses:
close with lookahead_on
This forces the data to be “previous confirmed close” so the spectral calculations do not repaint intra-bar. That matters because cycle measures can change drastically within a bar if you let them use live values.
So:
Spectra for external symbols are based on confirmed historical closes.
Chart symbol spectrogram and oscillator are also stable in the sense they depend on confirmed series values (dominant phase updates bar-to-bar).
Key parameters and how they change behavior
Analysis Lookback
Affects normalization and the DFT window cap:
Higher lookback stabilizes mean/stdev normalization and reduces random shifts.
Lower lookback makes the tool more reactive but more prone to regime noise.
Because the inner DFT accumulation caps at 100 bars, very high lookback mostly affects normalization rather than the raw projection length.
Sensitivity
Scales displayed amplitude:
Higher sensitivity makes peaks stand out more.
Lower sensitivity compresses amplitude.
It is a display control, not a physics constant.
View Mode
Spectrum: cross-asset snapshot comparison, resonance detection.
Spectrogram: time evolution of cycle energy for chart symbol.
Show Phase Direction
Adds ▲/▼ markers derived from sin(phase). Useful for quick cycle position intuition, but do not treat ▲ as “buy.”
Show Resonance Zones
Marks periods where many instruments share strong energy. Useful for macro rhythm alignment.
Highlight Dominant Cycles
Labels peaks. If you disable it, the chart becomes cleaner but less informative.
Spectrogram History
Controls how many columns are stored. Higher makes a longer heatmap but costs more drawing.
Limitations and what not to assume
This tool is honest DSP applied to market data, but market data is not a stationary sine wave generator. Key limitations:
Cycles drift. Dominant period can shift as regime changes.
The tool only tests 8 candidate periods. If the true dominant period is 30, it will express as energy near 34 or distributed across neighbors.
Normalization helps comparability, but does not make amplitude “absolute truth.”
DFT assumes a stable frequency over the window. Markets often violate that.
Phase-based oscillators are timing aids, not predictors.
This is why the indicator is best used as:
Context for entries/exits, not a standalone system.
A way to see when cycle energy concentrates or disperses.
A way to detect when multiple markets share a timing rhythm.
How to use it properly (workflows)
1) Cycle regime identification
If short periods (5–13) dominate, market is often choppy, reactive, and mean-reverting.
If mid periods (21–55) dominate, market often shows swing structure.
If long periods (89–120) dominate, market can be in slower macro drift, trend legs, or compressed volatility regimes.
2) Timing layer for an existing strategy
Use your trend model to decide direction.
Use dominant cycle oscillator to decide timing within that direction.
Use spectrogram to avoid trading when dominant period is unstable or flipping rapidly.
3) Cross-asset confirmation
If you see resonance at a period, watch whether your main instrument is also showing strength there.
Resonance can justify holding a cycle-based timing thesis with more confidence because it is not isolated.
4) Expectation management
If the spectrum is flat (no peaks above threshold), that is information:
No clean dominant cycle, randomness dominates.
Cycle-based timing will be unreliable.
Summary
Harmonic Frequency Visualizer uses a targeted Discrete Fourier Transform across predefined cycle periods to measure amplitude and phase of cyclical components in price. It supports multi-instrument spectrum comparison, resonance detection when several markets share strong energy at the same periods, and a spectrogram heatmap for the chart instrument showing how cycle dominance evolves over time. A dominant cycle oscillator maps phase into a 0–100 timing readout with alerts for peak/trough/midline transitions. It is a cycle context engine designed to complement trend, structure, and risk models, not replace them. 지표
