Trender [IQ]IQ Trender - TradingIQ
🔹 OVERVIEW
IQ Trender is a non-repainting trend rail built around one simple visual language:
Flat = range. Ramp = trend. Brightness = conviction.
Most trend tools try to follow every movement in price. In sideways conditions, that can leave you reading a line that bends, twitches, and changes direction inside the same noise you were trying to filter.
IQ Trender is designed to behave differently. While the market remains inside its adaptive hold zone, the rail stays deliberately flat. When the underlying trend evidence becomes strong enough, it commits to a rising or falling leg and moves in one direction until that condition genuinely changes.
The result is a clean distinction between three market states:
Holding - the rail is flat and the market is being treated as a range or consolidation.
Rising - the rail has committed to an upward leg.
Falling - the rail has committed to a downward leg.
Direction is shown by color. Conviction is shown by color intensity and glow. The Trender Radar explains the current state numerically, while the Ghost Forecast extends the rail's present trajectory into a fading uncertainty cone.
This is a trend-reading and visualization tool, not a signal service. It does not issue buy or sell calls, and it makes no claim of profitability or predictive certainty.
🔹 THE ONE-LINE MENTAL MODEL
The fastest way to read IQ Trender is to ignore the mathematics at first and watch the shape of the rail:
A flat rail means the model is holding through noise.
An upward ramp means the model has committed to a rising leg.
A downward ramp means the model has committed to a falling leg.
A stronger glow means the estimated trend is showing greater statistical conviction.
This is the same sequence demonstrated in the walkthrough: a directional leg can flatten during a pause, pullback, or consolidation, then recommit if the broader move resumes. The bearish interpretation is the mirror image - falling leg, flat hold, then a renewed falling leg if downside evidence returns.
The flat section is important. It is not a prediction that a breakout is about to happen. It is the indicator saying that current movement has not earned a directional commitment.
🔸 HOW THE ENGINE WORKS
IQ Trender combines three separate jobs: estimating the trend beneath price, deciding whether that trend is statistically meaningful, and drawing a rail that cannot wiggle backward within a committed leg.
Track the underlying trend
A robust local-linear Kalman filter estimates the level and slope beneath the candles. Unlike a conventional moving average that applies a fixed weighting pattern, this is a state-estimation model: it updates its estimate from the difference between expected and observed price.
Large isolated deviations are reduced with a robust update, so a single wick cannot directly yank the rail to a new location. The model also adapts its measurement-noise estimate as conditions change.
⬞
Measure the uncertainty
The filter calculates an innovation deviation - a live estimate of how much movement is normal relative to its current model. IQ Trender uses that value to size the hold band.
When conditions are noisy, the tolerance can widen. When conditions are calmer, it can tighten. This lets the same mental model adapt across different symbols, price levels, and timeframes without using one fixed distance everywhere.
⬞
Test for commitment and change
The estimated slope is compared with its own uncertainty to produce conviction. Hysteresis uses separate thresholds for entering and leaving a committed trend, helping prevent repeated state changes near one boundary.
A two-sided cumulative change test also monitors standardized price surprises. That evidence helps the rail distinguish a genuine opposing change from ordinary counter-movement when a leg is already active.
⬞
Draw the rail
The visible rail is a separate, slew-limited ratchet guided by the Kalman center. Once an upward leg begins, the rail can only move upward until a valid reversal or hold condition is reached. Once a downward leg begins, it can only move downward.
That monotone-within-leg behavior is what creates IQ Trender's signature geometry: flat holds connected by clean directional ramps instead of a line that bends around every candle.
🔹 THE ADAPTIVE HOLD BAND
The shaded band is the rail's live range corridor.
While the rail is holding, the band opens around it to show the volatility-adjusted area in which price can move without forcing a directional leg. When the rail commits to a trend, the displayed band eases shut onto the rail because the model has left its holding state. When the rail becomes flat again, the band gradually reopens.
The band should be read as a model tolerance, not as conventional support and resistance. Price moving within it means the model can continue to hold. Movement beyond it contributes evidence for a new leg, but it is not, by itself, a guaranteed breakout or trade entry.
🔸 COLOR, GLOW & CONVICTION
IQ Trender communicates direction and commitment through one coordinated visual system:
Rising color - active upward leg.
Falling color - active downward leg.
Holding color - neutral, flat state.
Glow intensity - visual emphasis derived from the current conviction reading.
Conviction measures how strongly the estimated slope differs from zero relative to the model's uncertainty. It is a statistical strength reading, not the probability that a trade will win.
The palette is generated in the Oklab perceptual color space. Hue, lightness, and vibrancy can be adjusted as a coordinated system, while out-of-gamut colors are compressed toward neutral instead of clipping harshly.
Accessibility controls include deuteranopia, protanopia, and tritanopia modes, plus automatic contrast correction against the chart background. A selectable contrast target helps keep the rail and directional Radar accents legible across light and dark themes.
🔹 TRENDER RADAR
The Trender Radar is the live scorecard in the corner of the chart. It reports:
State - HOLDING, RISING, or FALLING.
Conviction - normalized trend commitment from 0-100%.
Slope - the rail's current rate of change per bar.
Hold Band - the current full width of the adaptive range corridor.
Behavior - the active Speed and Pursuit combination.
With Log Geometry enabled, slope is displayed as a percentage per bar and band width is expressed as a percentage of the rail. With linear geometry, both are shown in price units.
The Radar can be moved to any chart corner or disabled entirely.
🔸 GHOST FORECAST
The Ghost Forecast is a translucent forward projection of the rail's current slope.
Its centerline extends the rail's recent trajectory. The surrounding cone widens with distance to communicate increasing uncertainty, then fades away toward the horizon. Two growth modes are available:
√h - tighter near the live bar, then gradually widening like a random-walk spread.
Linear - uncertainty expands at a constant rate.
The forecast is rebuilt only at the live edge and never painted into historical bars. It can also be displayed while the rail is holding, where its centerline remains flat.
This feature is a trajectory read, not a price target. It answers, Where is the rail currently heading if its present slope persists? It does not answer, Where will price trade?
🔹 FLIP MARKERS & ALERTS
Optional markers identify confirmed changes in rail state:
▲ - committed to a rising leg.
▼ - committed to a falling leg.
◇ - flattened back into a hold, when hold markers are enabled.
Markers are created only on confirmed bars. Once printed, they do not move.
Matching alert conditions are included for:
Trender committed to a rising trend.
Trender committed to a falling trend.
Trender flattened into a hold.
These alerts report state changes in the model. They are not automated trade recommendations and should be interpreted in the context of the symbol, timeframe, market structure, and the user's own risk process.
🔸 SPEED - THE OVERALL TEMPO
Speed changes the rail's pursuit rate and the width of its hold zone together:
Glacier - calm, structural behavior for slower or higher-timeframe reading.
Slow - patient swing behavior with a wider hold zone.
Balanced - the recommended reference setting, balancing hold and tracking.
Fast - more reactive behavior for shorter intraday movement.
Scalp - the tightest and quickest micro follower.
Slower settings generally require more displacement and move the rail more gradually. Faster settings use a tighter band and pursue price more aggressively. A faster preset is not automatically better: responsiveness and noise rejection are opposing trade-offs.
🔸 PURSUIT - HOW A COMMITTED LEG MOVES
Pursuit changes the shape of an active leg without changing the underlying trend evidence:
Steady - a constant-speed ramp established when the leg begins.
Eased - pursuit speed scales with conviction and feathers toward the estimated center.
Snap - the most decisive pursuit, with a higher movement rate and faster conviction scaling.
On slower Speed presets, Snap can appear more step-like. Steady produces the cleanest constant ramps, while Eased creates a softer approach.
🔹 HOW TO READ IQ TRENDER
Start with state
Flat rail means the model is holding. Rising or falling rail means it has committed directionally. This gives the chart an immediate range-versus-trend read before any number is considered.
⬞
Weigh the leg
Use conviction, glow, and slope together. A bright rail with firm slope represents stronger model commitment. Fading conviction says the trend estimate is becoming less distinct from noise; it does not guarantee an immediate reversal.
⬞
Watch the sequence
One useful continuation framework is:
Rising rail.
Flat hold during consolidation or pullback.
New rising marker and renewed upward rail.
The bearish sequence is the inverse. This is a way to organize market context, not a complete entry system.
⬞
Keep the forecast in its proper role
Use the Ghost Forecast to visualize current trajectory and uncertainty. Do not treat the cone edge or centerline as a promised future level.
⬞
Confirm with your own process
IQ Trender can be combined with price structure, volume, liquidity, momentum, or a trader's existing risk framework. No single state, marker, or Radar value should replace position sizing and independent confirmation.
🔸 INPUTS
Behavior
Speed
Pursuit
Source & Geometry
Price Source
Use Log Geometry
Close with Log Geometry enabled is the recommended general-purpose setup for ordinary positive price series. Log mode keeps slope and band behavior proportional across different price levels.
Rail, Band & Glow
Hold Band on/off
Band transparency
Rail Glow on/off
Glow intensity
Glow spread
Rail line width
Colors
Rising, Falling, and Holding anchors
Global hue rotation
Lightness adjustment
Vibrancy adjustment
Conviction Color response
Accessibility
Color-Blind Mode
Auto Contrast
Contrast Ratio
State Readout
Show Trender Radar
Radar location
Forecast
Ghost Forecast on/off
Horizon in bars
√h or Linear cone growth
Show While Holding
Markers
Flip Markers on/off
Optional hold markers
Marker size
🔹 NON-REPAINTING BEHAVIOR
IQ Trender is calculated causally with no future-bar lookahead.
Confirmed historical rail values and confirmed flip markers remain where they were calculated. The current, still-open bar can update as new price arrives, as any live indicator can. The Ghost Forecast is intentionally rebuilt at the live edge because it represents the rail's current slope and uncertainty; it does not rewrite historical bars.
What was confirmed in history stays confirmed. What is still live remains live.
🔸 LIMITATIONS & HONEST NOTES
IQ Trender is an indicator, not a validated trading strategy. It makes no performance, win-rate, profit, or edge claim.
Kalman filtering is still a causal estimation process. It reduces noise but cannot remove lag, uncertainty, or false transitions.
Faster settings react sooner but can respond to more noise. Slower settings filter more movement but can confirm later.
A Holding state identifies insufficient directional commitment in this model; it does not guarantee that price will remain inside a range or that a breakout is imminent.
Conviction measures the strength of the estimated slope relative to uncertainty. It is not a probability of future direction or trade success.
The Ghost Forecast extrapolates the rail, not price. It is a visual scenario if the current trajectory persists, not a target or prediction.
Alerts and markers identify model state transitions only. They should not be treated as standalone entries or exits.
Results depend on symbol behavior, timeframe, data quality, and the selected Speed/Pursuit combination.
IQ Trender is built to make one difficult market question easier to see:
Is the market still ranging, or has a trend actually committed?
One rail. Three states. No hindsight redraws.
Indicator

TA4j Kalman FilterMany "Kalman" indicators available on PulseWire are actually static Alpha-Beta filters with fixed-gain moving averages that lack dynamic state estimation.
This indicator is a direct port of the 1D Discrete Kalman Filter from TA4j's KalmanFilterIndicator . Instead of relying on a static "length" or arbitrary smoothing multiplier, this script acts as a probabilistic state estimator. It calculates dynamic error covariance on every bar to constantly weigh which is more trustworthy: the ongoing trend (Prior State) or the newest price bar (Measurement).
How to Tune Q and R
Because this is a true Kalman Filter, it does not use a standard "lookback length." Instead, it is tuned using two distinct variance parameters. The behavior of the filter is dictated entirely by the ratio between these two numbers.
• Process Noise (Q) - "How fast is the true trend changing?"
• This represents your baseline expectation of actual, structural price movement.
• Increase Q if you want the filter to be highly responsive and hug the price action closely.
• Trader Translation: High Q = Fast/Low-Lag Moving Average.
• Measurement Noise (R) - "How chaotic is the current market?"
• This represents your expectation of standard market noise, chop, and fake-outs.
• Increase R if you believe the asset is highly erratic and you want the filter to ignore sudden price spikes, trusting the underlying trend instead.
• Trader Translation: High R = Slow/Smooth Moving Average.
The Golden Rule of Tuning:
If you set $Q$ and $R$ to identical values (e.g., $Q = 0.01$ and $R = 0.01$), the filter balances the two equally.
• To filter out heavy volatility (crypto/low-timeframes), make $R$ significantly larger than $Q$ (e.g., $Q = 0.0001, R = 0.01$ ).
• To track momentum breakouts closely, make $Q$ larger than $R$.
Technical Caveat:
Because this is a steady-state 1D implementation with constant $Q$ and $R$ inputs, the Kalman Gain will be highly dynamic during the initial chart history but will mathematically converge to a steady state.
Indicator

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.
Indicator

Apex Turn v4APEX TURN v4: Kalman Snapback with Fee Gate, Trend Guard and Fair Value Take Profit
Apex Turn is a mean reversion tool that hunts exhausted moves and trades the snap back to fair value. It was designed for crypto perpetual futures but works on any liquid market.
HOW IT WORKS
The script runs an adaptive Kalman filter on log price to estimate fair value, drawn as the orange line. The gap between price and fair value is normalized into a z score over a rolling window. When the z score stretches beyond the entry threshold (2.8 by default) and then hooks back toward the mean while still deeply stretched, the engine looks to trade against the extreme. Longs trigger at washed out lows and shorts trigger at blow off highs.
THREE GATES PROTECT EVERY SIGNAL
Gate one is the chop filter. The Kaufman Efficiency Ratio must confirm a ranging market before any mean reversion entry is allowed.
Gate two is the fee gate. The script projects the reward from current price to fair value, converts your maker and taker fees into R units based on the stop distance, and blocks any signal that would not cover all fees plus a minimum net gain of 0.35R. Blocked signals print as small gray crosses so you can see exactly what fees would have eaten.
Gate three is the strong trend guard. Fair value drift is measured in ATR per bar. When drift is strong, counter trend signals are suppressed until the market prints a release event: a momentum divergence on the z score, volume absorption at the extreme, or both together depending on the mode you select. Trend blocked signals print as orange squares and release events print as aqua diamonds.
EXITS
On entry the script freezes the current fair value as the take profit target, plotted in green, and places the stop in red at 1.5 ATR from entry. The default exit mode assumes you rest a reduce only limit order at the target so your winning exit pays the lower maker fee. Mean touch and overshoot exit modes are also included in the settings. A time stop closes stale positions after 45 bars.
ADAPTIVE ATR
The ATR length is anchored to real time rather than a fixed bar count. It always measures roughly 112 minutes of volatility, so stops, targets and fee math stay consistent whether you chart 30 seconds or 4 hours.
ALERTS
Four webhook ready alerts are included. Entry alerts carry the close price, the stop, the frozen take profit and the projected net R, so an automated system can place the full bracket the moment a position is born. Exit alerts fire for stop, target and time stop events.
SUGGESTED USE
Developed and tested for the 8 minute chart on liquid perpetual pairs. The 30 minute and 1 hour charts also suit the logic well. Timeframes under 5 minutes are not recommended because trading fees consume most of the edge there. Set the maker and taker fee inputs to match your own exchange tier before trusting the fee gate.
Signals are evaluated at bar close and do not repaint. Nothing in this script is financial advice and past behavior in testing does not guarantee future results. Always size positions responsibly and manage your own risk. Indicator

KRT Kalman Regime Tricolor# 📊 KRT — Kalman Regime · Tricolor
**Designed and statistically validated for 🥇 GOLD and Ξ ETHEREUM.** A regime compass, not a buy signal: KRT reads the market on three layers — background regime, trend, your candle — and shows you which way the wind blows at every moment: 🟢 long · 🔴 short · 🔵 wait.
**⚡ ZERO lookahead, ZERO repaint.** Every signal appears in real time using only the information available at that moment, and whatever is printed at a bar close never changes afterwards. Many indicators look perfect because they quietly redraw the past — KRT is built for the opposite: what you see in replay is exactly what you would have seen live.
## ⚡ Quick start (30 seconds)
The colored BACKGROUND = the underlying regime.
Green 🟢 = bull regime installed → longs carry. Red 🔴 = bear regime installed → shorts carry. No color = no regime → caution.
The CURVE trails price like a stop line: below the candles in an uptrend, above them in a downtrend. Price crossing the curve = the reversal.
The curve's intensity = the strength of the authorization.
BRIGHT = trend aligned with the regime. Pale = secondary bias only. Blue = wait.
THE MARKERS — one single rule:
SOLID green or red marker (big triangle OR diamond) = GO. Blue = wait. Small = provisional.
🟢▲ / 🔴▼ BIG triangle — GO: reversal confirmed AND regime aligned.
🟢◆ / 🔴◆ Diamond — Deferred GO: the regime installs while the trend already points that way (often follows a big blue triangle). Same strength as a big colored triangle.
🔵▲ / 🔵▼ BIG blue triangle — reversal confirmed but no regime behind it → wait (a diamond will tell you if it becomes a GO).
▵▿ Small triangles (any color) — early alerts on your chart, ahead of confirmation. Provisional.
No thinking required: solid + colored = apply your strategy · blue = patience · small = not yet.
Drop it on gold or Ethereum, chart timeframe 5m–15m. Run YOUR strategy on top: KRT gives the direction, you handle entries, stops and exits.
## ⚠️ Before you use it
This is an indicator, NOT a strategy: it provides no entry or exit points.
Validated with permutation tests on gold and Ethereum. On Bitcoin the detection displays but the statistical edge is not demonstrated; on major forex pairs it is absent. Test it yourself before using it elsewhere.
The background regime changes slowly (weeks): that is by design — it filters, it does not scalp.
## 🔍 Understanding the display (going deeper)
THE THREE LAYERS
Regime (background, default 8H) — a slow Kalman trend filter with hysteresis: the background only colors once the regime is installed (default 3 days, adjustable). Locked at its own bar close: it does not flicker and does not repaint.
Trend (curve, default 1H) — the exact price level that would flip the trend filter, computed in advance: the distance between price and curve measures the strength of the trend.
Your candle (the chart) — the curve is monitored at your chart's granularity: you see the flip before the 1H close (small triangles), the close confirms it (big triangles).
HOW TO READ IT
Green background + bright green curve + GO = every layer agrees: the most favorable long context. Mirror in red for shorts.
Pale green curve = uptrend without an installed regime — weak bias.
Pale red curve = intraday "breather" (recurring windows of weakness inside an uptrend) — a short-lived bias, not an invitation to swing short.
Blue = no statistical edge. The best trade is often no trade.
After a bullish GO, price often retests the curve before continuing: aim for the retest rather than the impulse.
TIMEFRAMES & SETTINGS
Chart from 1m to 1H (5m–15m recommended).
Trend TF / Regime TF: the only settings an advanced user may change (swing trading: 4H/D).
Regime installation age (default 72h): higher = rarer, more reliable background; lower = more reactive, more false regimes.
Everything else (q values, thresholds, windows): the calibrated and validated core of the model — keep the defaults.
---
KRT is a decision-support tool based on historical data. Past performance does not guarantee future results. Manage your risk. Indicator

Kalman Quantum Drift [JOAT]KALMAN QUANTUM DRIFT
A trend-and-envelope engine built on the cleanest pair of state-space tools in quantitative finance: a Kalman filter for the centreline (Bayesian, adaptive, mathematically optimal under linear-Gaussian assumptions) and a GARCH(1,1) conditional-variance model for the envelope (the institutional standard for time-varying volatility). The script reads price as a noisy observation of an unobservable true state; the Kalman filter estimates that state recursively; GARCH estimates the noise's volatility; the envelope = mid ± k · σ_GARCH. A signal engine layered on top detects Collapse events (>3σ excursions) and Tunnel events (gap-throughs of the envelope) — the quantum analogues of state collapse and quantum tunnelling.
The Kalman filter, properly
A single-state recursive Bayesian filter. At each bar:
Predict : prior estimate = previous estimate. Prior variance = previous variance + Q.
Update : Kalman gain = prior variance / (prior variance + R). New estimate = prior + gain × (observation − prior). New variance = (1 − gain) × prior variance.
The two tuning knobs are:
Q (process noise) — how much the script trusts new observations. Higher Q = faster, noisier mid-line.
R (measurement noise) — how much the script trusts the model. Higher R = slower, smoother mid-line.
This is the Bayesian-optimal smoother for linear-Gaussian state-space data. Real markets are not perfectly linear-Gaussian, but the Kalman estimate is robust enough to be the cleanest mid-line you can build without going into heavy non-linear filtering.
GARCH(1,1) envelope
The envelope around the Kalman mid is not ATR or stdev — it is GARCH(1,1) :
σ²_t = ω + α · ε²_{t−1} + β · σ²_{t−1}
ω is the long-run variance baseline, α is the reaction to last shock squared (ARCH term), β is the persistence of past variance (GARCH term). For stationarity, α + β < 1 (the script's α/β defaults respect that). Optional log returns (default ON) and a warm-up window seed the variance from realised returns.
The envelope is mid ± k · σ_GARCH , rendered as a gradient (configurable number of nested fills, each at progressive transparency from edge to core).
Three-signal engine
Collapse — fires when price travels more than collapse threshold (default 3.0) σ-units from the Kalman mid. The "state collapse" event — price has decisively departed the filter's expected band. Bull or bear depending on direction.
Tunnel — fires when a bar gaps through the entire envelope from one side to the other. The "quantum tunnel" event — a discontinuous jump that bypasses the band gradient.
Buy / Sell crosses — fire when price crosses the Kalman mid from one side. Optional Collapse confirmation gate (default ON) — Buy / Sell only fires when a Collapse occurred within the configurable lookback window. This dramatically improves signal quality.
A configurable signal cooldown (default 5 bars) prevents stacking.
Visual system
Kalman mid-line — coloured by its own slope (bull / bear), configurable width.
Gradient envelope — nested fills (configurable steps, default 6) using the same base hue with progressive transparency from edge to core. Strict two-hue discipline (bull cyan / bear pink only).
Price bar colouring by mid slope (toggleable).
Background tint on extremes — subtle bgcolor when price is at envelope edge (toggleable, default 92 transparency).
Event glyphs — C (Collapse) and T (Tunnel) markers at the event bar. Configurable size.
A locked Quantum palette (cyan bull / pink bear / muted cyan mid on a deep violet-black) gives the chart a distinctive quant-physics identity.
Dashboard
Monospaced table positionable to any of nine corners. Surfaces:
Current Kalman mid value with slope direction.
σ_GARCH value and the envelope half-width.
Distance of price from mid in σ-units.
Last Collapse / Tunnel / Buy / Sell event with bar age.
Q / R settings in use.
GARCH ω / α / β confirmation.
Alerts
Six alert conditions, each independently controllable:
Collapse Up / Down (>kσ excursion)
Tunnel Up / Down (envelope gap-through)
Slope Flip (Kalman mid changes direction)
Sigma Spike (σ_GARCH exceeds its own recent baseline)
How to read it
Three reads, in order of conviction:
Buy/Sell after a Collapse (the script's intended signal) — the cleanest trend-entry the engine produces. A Collapse means price decisively departed expected range; the subsequent mid-line cross confirms the new direction with the strongest possible context. This is the highest-conviction read.
Tunnel — an exceptional, rare event. When a single bar jumps the entire envelope, the market has experienced a discontinuity (news, large block, exchange dislocation). Often produces the day's largest moves; almost always followed by elevated volatility.
σ Spike alert without a directional event — a regime warning. Volatility just expanded without a directional commitment yet. The next signal that fires is statistically more likely to be meaningful than the one before the spike.
Suggested settings
Defaults (Q = 0.02, R = 1.5, GARCH ω=2e-6 / α=0.10 / β=0.85, k = 2.5, gradient steps 6) are tuned for 15m–1H on liquid markets. For lower timeframes drop k to 2.0. For HTF raise R to 3.0 (more model trust on smoother data). The GARCH α/β defaults are the institutional standard; α + β remains under 1 for stationarity.
Originality
Kalman filtering and GARCH(1,1) are textbook quantitative-finance methods — both decades-old, both well-documented. The implementation here — the single-state recursive Kalman with exposed Q/R, the GARCH(1,1) variance recursion with warm-up window, the gradient-envelope render using strict two-hue alpha-only variation, the three-signal engine (Collapse / Tunnel / Cross), the optional Collapse-confirmed Buy/Sell gating, the event glyph markers, and the background tint on extremes — is JOAT-original. No third-party code reused. The pairing of Kalman + GARCH + quantum-inspired signal naming is the original presentation.
Limitations
The Kalman filter assumes linear-Gaussian state dynamics — real markets violate this, especially around news and gaps. The Q / R tuning is exposed precisely because no single setting is universally correct; tune to your instrument's noise profile. GARCH's α/β must sum to less than 1 for stationarity — the defaults respect this; if you push them too aggressively the variance can explode. Collapse and Tunnel events are confirmed on bar close (non-repainting).
—
-made with passion by jackofalltrades
Indicator

Adaptive Regression Channel Fit-Gated & CalibratedAdaptive Regression Channel — Multi-Engine, Fit-Gated & Calibrated
What it is
A regression channel that lets you choose the estimator, measures its own goodness-of-fit, and refuses to be trusted when that fit is poor. Four centerline engines, seven volatility engines for the bands, a kurtosis fat-tail multiplier, an honest √-horizon uncertainty cone, a ride-vs-revert detector, and a past-only calibration tracker that asks whether tagging the band actually precedes reversion on this symbol — measured against an unconditional base rate, in R.
Why these components belong in ONE script (not a stack of indicators)
They are the parts of one estimator, each covering a failure mode of the others:
Centerline engine. OLS is the baseline but lags at the right edge and is fragile to spikes. LOESS fixes the endpoint lag (local-linear, tricube-weighted). Theil-Sen fixes spike fragility (median of pairwise slopes). Kalman removes the window entirely (recursive level + trend). You choose the trade-off.
Adaptive window (Kaufman efficiency ratio). A fixed window is wrong in both trends and chop; the length stretches when price is efficient and contracts when it is noisy, so the channel tracks the live swing.
Volatility engine. The bands are only meaningful if their width reflects the real residual distribution: EWMA (recency), Yang-Zhang (drift-robust OHLC range), GARCH(1,1) (clustering), MAD (spike-resistance), asymmetric semidev (skew), quantile (empirical containment) — plus a kurtosis fat-tail multiplier so the stated containment actually holds.
Fit-quality gate. A channel drawn on a bad fit is noise dressed as structure. The centerline only draws solid and only emits events when it explains at least r2Gate of variance; below that it greys to dashed.
Ride-vs-revert. A band touch is ambiguous. Consecutive closes beyond the band ("walking the band") mark continuation, not reversion — so the channel does not fade a trend that is running.
Calibration. The edges are a hypothesis. Each trusted band tag is resolved forward against an unconditional same-horizon base rate, in R, so you see whether the band adds anything over noise — not a naked win-rate.
The centerline says where the mean is, the volatility engine says how wide the normal range is, the fit gate says whether to believe any of it, ride-vs-revert says fade or follow, and calibration keeps it honest. Remove any layer and the channel loses a check it cannot recover.
How it works (mechanics)
The selected engine fits the centerline in (optionally log) price space, on a window that can be fixed, ER-adaptive, or pivot-anchored to the current segment. Residual dispersion drives the bands through the chosen volatility engine, widened by the fat-tail multiplier. The fit metric is the explained-variance fraction of the residuals; below the gate the channel is shown as untrusted and emits nothing. On a trusted channel, each band tag is queued on bar close and resolved horizon bars later — a win if price moved moveATR·ATR in the reversion direction — and tallied per class (UTAG / LTAG) against the unconditional base rate.
Non-repaint: fits on confirmed closes, pivots confirmed, calibration on bar close. The drawn channel updates live (a rolling regression always does — that is description, not a signal); the calibrated events are confirmed-bar only.
How to use
Read the dashboard: FIT% and TRUSTED / LOW-FIT come first. If the fit is low, treat the channel as description only.
On a trusted channel, a band tag is a reversion hypothesis — the calibration rows tell you whether that class has actually paid on this symbol (Hit% vs Base%, Edge with a 95% star, MFE/MAE in R).
WALK means the band is being ridden (trend) — do not fade it.
The cone is an uncertainty fan (√-horizon growth), not a target.
Everything here is descriptive, probabilistic context — never an instruction.
Use on any market
The Data Source inputs (Close / High / Low) drive the fit, the band tags and the calibration, so the channel runs on any series (standard candles, Heikin-Ashi, etc.) and any market. All thresholds are ATR-relative. Defaults are set for NIFTY index-futures intraday; change the source or lengths for other assets.
Originality
The contribution is the closed loop: a selectable estimator whose fit is measured and gated, bands whose width is chosen from seven rigorous volatility models and fat-tail-corrected, a ride-vs-revert guard, and a per-class forward calibration against an unconditional base rate. Most channels draw a line and a ±σ band and stop; this one tells you whether to believe the line and whether the band has historically meant anything here.
Credits
Least squares & local regression (LOESS) — Gauss / Legendre; W. S. Cleveland
Theil-Sen estimator — H. Theil & P. K. Sen
Recursive level+trend (Kalman) filter — R. E. Kálmán
Efficiency Ratio (adaptive window) — Perry Kaufman
EWMA / RiskMetrics variance — J.P. Morgan
Yang-Zhang OHLC volatility — Dennis Yang & Qiang Zhang
GARCH(1,1) — Engle & Bollerslev
The fit-quality gate, the band-walk ride-vs-revert logic and the forward-calibration framework are the author's original implementation.
Limitations (honest)
The calibration is in-sample, close-to-close at a fixed horizon, with no costs, slippage or stops — a study aid, not a backtest, and not a probability of future results. A rolling regression updates every bar; the drawn channel is descriptive, and only the confirmed-bar tag events are calibrated. Theil-Sen is O(n²) in pairs (capped for speed). Past behaviour does not assure future behaviour.
Disclaimer
Educational / informational study for chart analysis only. NOT financial advice, NOT a strategy, NOT a recommendation. It places no orders and guarantees no outcome. Markets carry risk; do your own research and manage your own risk. Paper-trade before risking real money. Indicator

Kalman Auction Ribbon [JOAT]Kalman Auction Ribbon is an open-source Pine Script v6 overlay that builds a six-layer adaptive ribbon from a zero-lag source and Kalman-style velocity smoothing. The goal is to show trend alignment, slope strength, deviation zones, and confirmed retest behavior in one restrained chart layer.
The script focuses on auction behavior around a dynamic ribbon. When the ribbon layers align and slope together, the state becomes directional. When price stretches beyond the deviation envelope and then returns, the script can mark supply or demand zones for later retests.
Core Concepts
1. Zero-Lag Source
The source is adjusted by comparing current price with a half-length historical value. This produces a more responsive input for the ribbon calculations.
zeroLagOffset = math.max(1, int(math.round(baseLength * 0.50)))
zeroLagSource = src + (src - nz(src , src))
2. Kalman-Style Velocity Estimate
Each ribbon layer uses a compact velocity smoother that maintains an estimate and speed component. The speed term helps the estimate respond to directional movement without relying on future bars.
prior = na(estimate ) ? value : estimate + nz(speed ) * gain
error = value - prior
speed := nz(speed ) * (1.0 - alpha * 0.50) + error * alpha * gain
estimate := prior + error * alpha
3. Six-Layer Ribbon Alignment
The script calculates six different ribbon lengths. Alignment and slope scores are combined into a trend score from -100 to +100. This score controls the ribbon color and dashboard power reading.
4. Deviation Zones
Upper and lower deviation levels are built around the ribbon midpoint using ATR. If price pushes beyond a deviation level and closes back inside, the script creates a compact supply or demand zone.
5. Retest Logic
Retest signals occur when price interacts with a live zone or the ribbon itself while the ribbon state remains directional. These signals are confirmed on closed bars.
Features
Six-layer adaptive ribbon: Multiple Kalman-style layers reveal alignment and spread
Velocity weighting: Gain input changes how aggressively the smoother responds
Deviation envelope: ATR-based upper and lower zones around the ribbon midpoint
Soft supply and demand boxes: Created only on confirmed deviation rejection behavior, with overlap suppression so the chart does not stack redundant boxes
Labeled deviation boxes: Supply and Demand Deviation boxes include midpoint guide lines and fade after invalidation
Confirmed buy/sell markers: Compact BUY and SELL dots appear only after confirmed ribbon or zone retest behavior
Trend-state candles: Optional bar coloring by ribbon state
Dashboard: Shows state, power, distance, and retest status
Alerts: Confirmed buy, confirmed sell, lower deviation zone, and upper deviation zone
Input Parameters
Core:
Source: Price source used by the ribbon
Base Length: Main length from which all ribbon layers are derived
Velocity Weight: Strength of the speed component
Deviation ATR Length: ATR length for deviation zones
Deviation Width: ATR multiplier for the envelope
Zones:
Show Deviation Zones: Toggles supply and demand boxes
Zone Extension Bars: How far active boxes extend to the right
Maximum Zones Per Side: Caps active supply and demand boxes
Signals:
Show Confirmed Buy/Sell: Toggles compact confirmed signal dots
Signal Spacing Bars: Minimum spacing between signal markers
Zone Extension Bars: Forward box extension length
Maximum Zones Per Side: Object cap for zone storage
Visual:
Palette: Selects the color pair
Show Ribbon: Toggles ribbon plots and fill
Trend-State Candles: Enables candle coloring
Dashboard: Shows the top-right panel
How to Use This Indicator
Step 1: Read Ribbon Alignment
A strongly stacked ribbon with a high dashboard power value indicates directional alignment. A mixed ribbon shows a less decisive state.
Step 2: Watch Deviation Zones
Zones are created when price rejects beyond an ATR deviation envelope. These boxes represent areas where price stretched away from the ribbon and returned.
Step 3: Use Retests With Context
Retest dots identify confirmed interactions with the ribbon or zones. They should be evaluated with trend state, market structure, and risk placement.
Indicator Limitations
Kalman-style smoothing is reactive and does not know future price direction
Strong news bars can move through deviation zones without meaningful retests
Object limits require older zones to be removed when the maximum is exceeded
The ribbon can compress during range conditions and produce mixed readings
Originality Statement
Kalman Auction Ribbon is original in its combination of zero-lag preprocessing, six independent Kalman-style layers, ATR deviation boxes, and confirmed retest tracking. It uses public Pine primitives in a custom structure and does not paste or disguise another author's source.
Disclaimer
This script is provided for educational and informational use only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Ribbon states and zones can fail during unusual volatility or thin liquidity. Always use independent analysis and proper risk management.
-Made with passion by jackofalltrades
Indicator

Kalman Flow TrailKalman Flow Trail
Kalman Flow Trail is a clean trend-following and market structure overlay designed to help traders read market direction, structural shifts, protected levels, liquidity targets, and higher-timeframe alignment from one chart.
The script combines an adaptive Kalman-based trail with market structure logic, live strong/weak range levels, POI supply and demand zones, optional MSS/MSB guides, higher-timeframe confirmation, flip markers, and a compact Flow Dashboard.
Core Features
1. Adaptive Kalman Flow Engine
At the centre of the script is a dual Kalman smoothing engine designed to filter market noise while tracking directional flow.
Unlike a standard moving average with fixed behaviour, the trail adapts using market structure activity and volatility. When price action becomes more active, the trail can respond faster. When price is choppy or compressed, the trail becomes smoother to reduce unnecessary noise.
The engine also includes a structure-bias filter to help reduce overreaction when Kalman momentum and market structure are not aligned.
2. MSS / MSB Structure Guides
Kalman Flow Trail includes optional structure guides for traders who want to see internal market structure directly on the chart.
MSS = Market Structure Shift
MSB = Market Structure Break
These guides can be toggled on or off depending on whether the trader wants a detailed structure view or a cleaner visual layout.
3. Live Strong & Weak Range Levels
The script automatically tracks swing structure and highlights strong protected levels and weak target levels.
Strong levels represent the protected side of the current range.
Weak levels represent likely liquidity targets.
When a weak target is swept, the level can roll forward live with the current extreme until a new confirmed pivot forms. This helps keep the range logic responsive during strong continuation moves.
4. POI Supply & Demand Zones
The script can draw POI zones from important structural pivot areas.
In a bullish range, the POI highlights a potential demand area around the protected strong low.
In a bearish range, the POI highlights a potential supply area around the protected strong high.
The zones use theme-adaptive colours and dashed borders for a cleaner and more professional chart style.
5. Higher-Timeframe Confirmation
The optional HTF Kalman Basis allows traders to compare current chart flow with a selected higher timeframe.
For example, traders can view a 1H Kalman basis while analysing a 5-minute or 15-minute chart. This helps identify whether lower-timeframe price action is aligned with the broader market direction.
6. Flow Dashboard
The built-in Flow Dashboard gives a compact read of current market conditions:
Trail Direction
Kalman Momentum
HTF Alignment
Range State
This allows traders to quickly check whether the current flow, momentum, higher timeframe, and range structure are aligned.
7. Trail Flip Markers
Diamond markers appear when the Kalman Flow Trail changes direction.
These Trail Flip markers are designed to highlight possible shifts in directional flow. They are not standalone buy or sell signals, but they can help traders identify when market conditions are changing.
8. Proximity Star
The live trail star follows the active trail level.
When price moves close to the trail, the star changes into a warning state. This can help traders see when price is approaching a possible reaction area, mean-reversion zone, or potential trail breach.
Visual Themes
Kalman Flow Trail includes multiple built-in colour themes:
Lucid Neon
Ember Pulse
Arctic Signal
Violet Flux
Mono Current
Custom Theme
Users can also toggle trail glow, trail fill, trail boundaries, flip diamonds, live trail star, HTF basis, POI zones, MSS/MSB guides, and candle colouring.
How Traders Can Use It
Trend Continuation
Look for price respecting the trail and holding above protected demand areas in bullish conditions, or below protected supply areas in bearish conditions.
Trail Flip
Use diamond markers as visual alerts that directional flow may be shifting.
Strong / Weak Range Logic
Use strong levels as protected structure and weak levels as potential liquidity objectives.
HTF Alignment
Higher-quality conditions generally occur when Trail Direction and HTF Alignment point in the same direction.
POI Zones
Use POI Demand and POI Supply zones as structural areas of interest for reactions, continuation, or invalidation.
Best Use Cases
Trend-following analysis
Market structure reading
Liquidity target mapping
Higher-timeframe confirmation
Clean visual trend tracking
Crypto, Forex, Indices, Stocks, and Commodities
Notes
This indicator is designed as an analytical tool. It does not predict the future and should not be used as a standalone trading system. Traders should combine it with their own market context, confirmation process, and risk management.
Disclaimer
Trading involves risk. This script is for educational and analytical purposes only and does not constitute financial advice.
Indicator

Gatev Relative Value Arbiter [JOAT]Gatev Relative Value Arbiter
Introduction
Gatev Relative Value Arbiter studies relative value between the chart symbol and a selected peer using beta spread, z-score, stationarity, Kalman residuals, and OU speed.
This open-source indicator is designed as a context tool, not a standalone trading system. It focuses on explaining the current market state with restrained visuals and confirmed-bar logic where signals are used.
Core Concepts
1. Rolling Beta Spread
The chart log price is modeled against the peer log price with rolling beta and alpha.
2. Spread Z-Score
Residual spread is normalized to identify cheap and rich dislocations.
3. Kalman Residual
A recursive residual estimate adapts to changing pair behavior.
4. Stationarity and OU Speed
Correlation, beta drift, skew, kurtosis, and OU-style speed grade pair quality.
spread = logChart - (alpha + beta * logPeer)
Features
Peer relative-value model
Rolling beta and spread z-score
Kalman residual z-score
Stationarity and cointegration energy proxies
Cheap, rich, prime, broken, and fair-value states
Input Parameters
Peer symbol
Rolling beta and z-score lengths
Entry and exit z thresholds
Minimum correlation
Cooldown and display toggles
How to Use This Script
Choose a logically related peer. Cheap and rich states are most meaningful when pair validity and stationarity remain acceptable.
Limitations
The script uses historical OHLCV data and cannot know future prices.
Signals and states can be late during fast reversals because confirmed-bar logic is used to reduce repainting.
Model outputs should be interpreted with market context, risk controls, and independent analysis.
No visual state should be treated as a certain trade outcome.
Originality Statement
GRA is original in combining rolling beta arbitrage logic, Kalman residuals, OU speed, and stationarity grading.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any financial instrument. All calculations are derived from historical market data and may produce inaccurate readings in some market conditions. No indicator can predict future market behavior. Use proper risk management and independent judgment.
-Made with passion by jackofalltrades
Indicator

Library

Indicator

OBV with Kalman Filter Improv [TechnicalZen]Reversals, Breakouts & Re-Entries: OBV with Kalman Filter Improv
What This Indicator Does
This indicator transforms On-Balance Volume into a visual momentum instrument. Raw OBV is normalized to a 0-100 scale, rendered as stair-step candles with a continuous color gradient, and overlaid with a dual Kalman-filtered ribbon that tracks the flow trend with adaptive precision.
The result is a single pane that answers three questions at a glance: Is volume flow accumulating or distributing? How strong is the conviction? Where are the reversal, breakout, and re-entry points?
No footprint data required. No premium subscription needed. Pure price action and volume.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Why OBV Matters More Than Raw Volume
Raw volume bars tell you how much traded. They do not tell you which direction the volume was pushing. A high-volume bar during a selloff looks identical to a high-volume bar during a breakout rally.
On-Balance Volume assigns direction. When price closes up, the bar's volume is added. When price closes down, it is subtracted. The running total — OBV — reveals the persistent pressure beneath the surface. Rising OBV with flat price means accumulation. Falling OBV with rising price means distribution. These divergences are invisible on a standard volume histogram.
This indicator takes OBV further by normalizing it into a bounded oscillator, smoothing it for clarity, and applying Kalman filtering for adaptive trend detection.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How It Works
The indicator processes OBV through four stages.
Stage 1 — Normalize to 0-100
Raw OBV is an unbounded cumulative number that grows indefinitely. This makes it difficult to compare across time periods or instruments. The indicator applies a rolling min-max normalization over a configurable lookback window (default 100 bars), mapping OBV into a 0-100 scale.
At 100, OBV is at its highest point within the lookback. At 0, its lowest. At 50, it sits at the midpoint of its recent range. This creates a bounded oscillator from a trending series.
Stage 2 — Stair-Step Candles
The normalized OBV is rendered as candles where each bar's open equals the previous bar's close. This creates seamless stair-step blocks with no gaps and no overlaps. The candles show the direction and magnitude of each bar's contribution to the flow — a tall green block means a strong volume push upward, a tall red block means aggressive selling pressure.
Stage 3 — Position-Based Color Gradient
Candle color is determined by where the candle sits in the 0-100 range, not merely whether it went up or down:
Bright green (above 70) — strong bullish accumulation zone
Yellow-green (50-70) — moderate bullish flow
Yellow (around 50) — neutral, transition zone
Orange (30-50) — weakening flow, bearish lean
Red (below 30) — strong bearish distribution zone
This gradient reveals the market's volume state at a glance. Candles clustered at the top in green signal sustained accumulation. Candles dropping through yellow into red signal a regime shift.
Stage 4 — Dual Kalman Ribbon
Two Kalman-filtered lines track the normalized OBV at different speeds:
Short KF (default 20) — responsive to recent flow shifts
Long KF (default 80) — tracks the underlying flow trend
When the short line is above the long line, the ribbon fills bullish. When below, bearish. The Kalman filter adapts its responsiveness automatically — smoothing through noise while responding quickly to genuine regime changes. This is fundamentally superior to any fixed-length moving average.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Reading the Three Signals
Reversals
A reversal signal appears when candles have been clustered at one extreme (above 70 or below 30) and begin migrating toward the midline. The color gradient shifts — green fading to yellow, or red fading to orange. The Kalman ribbon begins to narrow as the short line approaches the long line. When the ribbon flips color, the reversal is confirmed by volume flow, not just price action.
Breakouts
A breakout appears as a large candle that punches through the 70 or 30 threshold line with expanding body size. The Kalman ribbon is already aligned in the breakout direction (short above long for bullish, below for bearish). This confirms that volume flow is supporting the price move — not just a wick or a fake breakout.
Re-Entries
After a breakout, price often pulls back. During a healthy pullback, the candles dip toward the midline (50) but the Kalman ribbon stays in the trend direction . Candles may turn yellow briefly but do not reach the opposite extreme. When candles resume their original color and move away from the midline, that is the re-entry — volume flow confirms the trend is intact.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Why Kalman Filtering — Not EMA, SMA, or Hull
Traditional moving averages apply a fixed smoothing recipe regardless of market conditions. In a quiet market, they lag. In a volatile market, they whipsaw. The trader is forced to manually change the length setting as conditions change.
The Kalman filter solves this structurally. It maintains an internal estimate of both the value and its uncertainty . On every bar, it computes a gain that automatically balances between trusting the new data and trusting its prediction. When data is noisy, the gain drops and the filter smooths aggressively. When a genuine shift occurs, the gain rises and the filter responds immediately.
Two parameters control this behavior:
R (Measurement Noise) — how much noise is expected in each bar's data. Higher values produce smoother output.
Q (Process Noise) — how quickly the underlying trend is expected to change. Higher values allow faster adaptation.
The dual-line ribbon (short KF vs long KF) combines the adaptive smoothing with trend direction detection. The crossover of two Kalman-filtered lines is more reliable than traditional MA crossovers because the filter has already absorbed the noise before the crossover happens.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Reading the Indicator
The Candles
Green blocks at top — strong sustained buying pressure. Trend is healthy.
Red blocks at bottom — strong sustained selling. Downtrend confirmed by volume.
Yellow/orange blocks at midline — indecision. Flow is balanced. Wait for direction.
Color transition — the gradient shift (green to yellow, or red to orange) often leads price by several bars.
The Kalman Ribbon
Green fill (short above long) — volume flow trend is bullish
Red fill (short below long) — volume flow trend is bearish
Ribbon narrowing — trend weakening, potential flip ahead
Ribbon widening — trend conviction increasing
The Threshold Lines
70 line — overbought in volume flow terms. Sustained presence above = strong trend, not necessarily a sell signal.
50 line — equilibrium. Transitions through this level signal regime changes.
30 line — oversold in volume flow terms. Sustained presence below = strong downtrend.
Line colors match the candle gradient — they shift with the regime.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Key Settings
Normalization Lookback (default: 100)
Rolling window for min-max scaling. Higher values produce smoother oscillation with fewer extremes. Lower values make the indicator more reactive to recent volume changes.
HA Smoothing Passes (default: 1)
Number of additional smoothing passes on the normalized OBV. 1 = standard stair-step. 2-3 = smoother candles with less noise.
Short KF / Long KF Length (default: 20 / 80)
Controls the responsiveness of the two Kalman lines. The gap between them determines how quickly the ribbon detects trend changes.
Measurement Noise R (default: 0.01)
Higher = smoother Kalman output. Lower = more reactive to each bar.
Process Noise Q (default: 0.10)
Higher = faster adaptation to regime shifts. Lower = more rigid trend following.
Upper / Lower Threshold (default: 70 / 30)
Defines the overbought/oversold boundaries for the volume flow oscillator.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Divergence — The Most Powerful Signal
When price makes a new high but the OBV candles fail to reach the upper zone (or are falling), volume is not confirming the move. This bearish divergence often precedes reversals by several bars. The Kalman ribbon will begin narrowing before the price chart shows any weakness.
Conversely, when price makes a new low but OBV candles hold above the lower zone or begin rising, that is bullish divergence — accumulation is happening beneath the surface.
The gradient coloring makes these divergences immediately visible. Price may look strong, but if the candles are orange instead of green, the volume story disagrees.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
What This Indicator Is Not
It does not generate automated buy or sell signals . It provides visual regime information for the trader to interpret.
It does not use footprint or order flow data . It is built on standard OBV which infers direction from price close. For actual bid/ask decomposition, a footprint-based indicator is required.
It does not predict future price direction . It reveals the current state and trend of volume flow. What the market does with that flow is never guaranteed.
It is not a standalone trading system . It is a confirmation and divergence detection tool designed to complement price action analysis.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, and it does not constitute a recommendation to buy, sell, or hold any financial instrument.
All trading involves risk. Past performance of any signal, regime detection system, or volume analysis mechanism does not guarantee future results. The normalized OBV readings, Kalman-filtered trend lines, and color gradient zones represent a computational assessment of publicly available price and volume data. They are not predictions and should not be treated as certainties.
On-Balance Volume assigns all of a bar's volume to one direction based solely on whether the close was higher or lower than the previous close. This is an approximation. A bar that closes up by one tick with heavy selling throughout will register as entirely bullish volume in OBV. Traders should be aware of this limitation.
The Kalman filter parameters (R and Q) affect responsiveness. Poorly tuned parameters can produce either excessive lag or excessive noise. The default values are designed for general use but may require adjustment for specific instruments or timeframes.
No indicator, algorithm, or model can account for all market variables including liquidity events, news-driven gaps, exchange outages, or sudden regime changes. Traders should always use independent risk management, position sizing, and their own judgment before entering any trade.
By using this indicator, you acknowledge that you are solely responsible for your own trading decisions and that the authors accept no liability for any losses incurred.
Indicator

Footprint Interpreter [TechnicalZen]Footprint Interpreter
⚠ Requires PulseWire Premium or Ultimate subscription. This indicator uses request.footprint() which is not available on free or Essential plans.
What This Indicator Does
The Footprint Interpreter reads real order flow — actual buy-side and sell-side execution data from PulseWire's footprint engine — and translates it into a visual language that reveals what the market is doing beneath the surface of price action.
You do not need the footprint chart open. You do not need to read bid/ask ladders, decode volume profiles, or interpret heat maps. The indicator extracts the essential signal from footprint data and presents it as candles, a Kalman-filtered trend ribbon, and a regime engine — all in a single pane.
The core question it answers: "Where is the real money flowing, and is it accelerating or decelerating?"
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Why Footprint Data Matters
Price tells you where the market went. Volume tells you how much participated. But neither tells you who was the aggressor .
Every trade has a buyer and a seller. Footprint data decomposes each bar's volume into buy-side executions (orders hitting the ask) and sell-side executions (orders hitting the bid). The difference — the delta — reveals which side was actively pursuing fills.
This matters because:
Absorption — Price goes sideways while one side relentlessly absorbs the other's aggression. Invisible on a price chart. Clearly visible in footprint delta.
Pre-breakout accumulation — Before a move begins, aggressive buying or selling often builds in the delta while price hasn't yet responded. The Footprint Interpreter catches this divergence.
Exhaustion — A strong price trend continues but the delta weakens. The aggressive side is running out of conviction. The indicator's regime engine detects this deceleration.
Confirmation — Price breaks a level and the delta confirms with expanding aggression in the same direction. Confidence in the move increases.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How It Works
The indicator runs three engines simultaneously, each operating on raw footprint data — no price-derived inputs.
Engine 1 — Footprint Delta (FPD) Candles
The cumulative footprint delta is computed bar by bar: each bar's buy volume minus sell volume, accumulated over time. This running total is detrended by subtracting a slow moving average so the display oscillates around zero rather than growing indefinitely.
The result is plotted as candles. Green candles mean the FPD rose during that bar (net buying pushed the cumulative total higher). Red candles mean it fell. The candle body directly represents the flow direction and magnitude.
Engine 2 — Dual Kalman Ribbon
Two Kalman-filtered lines track the FPD at different speeds:
Short KF (default length 20) — responsive, tracks recent flow shifts
Long KF (default length 80) — stable, tracks the underlying flow trend
When the short KF is above the long KF, the ribbon fills bullish. When below, bearish. The ribbon's width indicates the strength of the directional conviction — a wide ribbon means the fast and slow flow assessments strongly agree.
Engine 3 — Volume-Native DX/ADX Regime
The regime engine is a faithful translation of the classic Directional Movement system into the volume domain. Every component has a proper analog:
Directional Movement — Instead of comparing today's high vs yesterday's high, it compares today's buy volume vs yesterday's buy volume. Is buying expanding ? Is selling expanding? Only the winning side scores — the same competitive logic as the price-based original.
True Range — Instead of max(high-low, |high-close |, |low-close |), it uses max(totalVol, |buyVol-delta |, |sellVol+delta |). This captures both the bar's flow range and the gap from the previous bar's net settlement — detecting sudden flow reversals the way price TR detects overnight gaps.
DI+, DI-, DX, ADX — computed identically to the price version, but fed entirely by volume data.
The result is a four-state regime: Bull Strong, Bull Weak, Bear Strong, Bear Weak — telling you not just which side dominates but whether that dominance is accelerating or fading .
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Why Kalman Filtering — Not Hull, EMA, or SMA
The Kalman filter is fundamentally different from traditional moving averages. A moving average is a fixed recipe: take N bars, weight them, output a number. It has no concept of whether the data it is processing is noisy or clean, fast-moving or stable.
The Kalman filter is an adaptive estimator . It maintains two quantities internally:
State estimate — its current best guess of the true value
Uncertainty estimate — how confident it is in that guess
On every bar, it computes a Kalman gain that automatically balances between trusting the new measurement and trusting its prediction. When the data is stable, the gain drops and the filter smooths heavily. When the data shifts, the gain rises and the filter responds quickly.
This matters for footprint data specifically because volume flow is inherently noisier and burstier than price. A single large institutional order can spike the delta for one bar and vanish the next. Hull or EMA will whipsaw on these spikes. The Kalman filter recognizes the spike as high-uncertainty data and dampens its response — unless the spike is sustained, in which case it adapts.
The two tunable parameters — R (measurement noise) and Q (process noise) — give precise control over this behavior without changing the filter's length or structure.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
What It Reveals — Hidden Price Action
The most powerful use of this indicator is seeing what price alone cannot show:
Divergence Between Price and Flow
Price is rising but the FPD candles are falling or flat. This means the price advance is happening on declining aggressive buying — the move is running on fumes. The Kalman ribbon will begin to narrow and eventually flip before price confirms the reversal.
Pre-Breakout Energy
Price is consolidating in a tight range. The FPD candles begin trending directionally with expanding bodies. Aggressive flow is building on one side before the breakout occurs. The regime engine shifts from weak to strong. This gives the trader a heads-up — not a prediction, but evidence of building pressure.
Absorption Detection
Price pushes into a level and stalls. The FPD shows persistent negative delta despite bullish price action — sellers are absorbing every push. The Kalman short line begins diverging from the long line in the opposite direction of price. The regime stays weak or flips. The breakout attempt is likely to fail.
Trend Confirmation
Price breaks out and the FPD confirms: expanding candles in the same direction, both KF lines aligned and rising, regime at Bull Strong. This is the highest-confidence scenario — price and flow agree, and flow is accelerating.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Reading the Indicator
The Candles
Green body — FPD rose during this bar (net buying dominated)
Red body — FPD fell (net selling dominated)
Body size — magnitude of the net flow shift
Position relative to zero — above zero = cumulative flow above its recent average; below = below average
The Kalman Ribbon
Thin line (Short KF) — fast flow tracker, colored by slope
Thick line (Long KF) — slow flow trend, colored by direction
Ribbon fill — bullish when short above long, bearish when below
Ribbon width — wider = stronger conviction, narrower = indecision or transition
The Dashboard
Regime — four-state flow regime (Bull Strong / Bull Weak / Bear Strong / Bear Weak)
Kalman — current Kalman ribbon direction
FPD Position — whether FPD is above or below the fast Kalman line
Vol DX — signed directional strength from the volume DM engine
Bar Delta — this bar's net buy minus sell volume
Buy / Sell Vol — raw buy-side and sell-side execution volumes
Imbalance — ratio of dominant side to weak side
FPD — cumulative footprint delta total
When footprint data is unavailable (instrument or plan limitation), the dashboard title turns red with a warning indicator.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Key Settings
DX/ADX Period (default: 25)
Smoothing length for the directional movement engine. Higher values produce more stable regime readings at the cost of responsiveness.
Detrend Period (default: 50)
Length of the SMA subtracted from FPD for display centering. Does not affect any calculations — purely visual. Higher values show longer-term flow trends. Lower values focus on recent action.
Short KF / Long KF Length (default: 20 / 80)
Controls the responsiveness of the two Kalman-filtered lines. Shorter = more reactive. Longer = more stable. The gap between them determines how quickly the ribbon responds to flow reversals.
Measurement Noise R (default: 0.01)
How much the Kalman filter trusts new data versus its own prediction. Higher = smoother. Lower = more reactive to each bar.
Process Noise Q (default: 0.10)
How quickly the Kalman filter allows its internal state to change. Higher = adapts faster to regime shifts. Lower = more rigid model.
Ticks Per Row (default: 1)
Resolution of the footprint histogram. 1 = maximum precision. Increase for very high-volatility instruments if you encounter data limits.
Value Area % (default: 70)
Percentage of total volume that defines the Value Area in the footprint data. Industry standard is 70%.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Requirements
PulseWire Premium or Ultimate plan (required for request.footprint())
Instruments with footprint data available (most major futures, equities, and crypto pairs)
Pine Script v6
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
What This Indicator Is Not
It is not a replacement for the footprint chart. It is a complementary interpretation layer. Traders who read raw footprint data will find additional context here. Traders who do not will gain access to footprint intelligence without needing to learn footprint chart reading.
It does not generate buy or sell signals . It provides directional regime information, flow momentum, and divergence detection. Trade decisions remain with the trader.
It does not predict price direction. It reveals the state of aggressive order flow and how that flow is evolving. What the market does with that information is never guaranteed.
It is not a volume indicator in the traditional sense. It does not use the standard volume series. It uses decomposed bid/ask execution data from PulseWire's footprint engine — a fundamentally different and richer data source.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, and it does not constitute a recommendation to buy, sell, or hold any financial instrument.
All trading involves risk. Past performance of any signal, regime detection system, or flow analysis mechanism does not guarantee future results. The regime states, Kalman-filtered trend readings, and flow analysis displayed represent a computational assessment of order flow data available through PulseWire's footprint engine. They are not predictions and should not be treated as certainties.
Footprint data availability and accuracy depend on the instrument, exchange, and PulseWire's data feed. The indicator requires a Premium or Ultimate PulseWire subscription. Data gaps, exchange outages, or instruments without footprint support will produce missing or incomplete readings. The dashboard provides a visual warning when footprint data is unavailable.
No indicator, algorithm, or model can account for all market variables including liquidity events, news-driven gaps, exchange outages, dark pool activity, or sudden regime changes. Order flow data represents only the visible portion of market activity — significant volume may execute through channels not captured by footprint data.
Traders should always use independent risk management, position sizing, and their own judgment before entering any trade.
By using this indicator, you acknowledge that you are solely responsible for your own trading decisions and that the authors accept no liability for any losses incurred.
Indicator

Triple Derivative EngineMost momentum indicators tell you where the price is. The Triple Derivative Engine tells you how fast it's getting there, whether that speed is increasing or fading, and whether the acceleration itself is changing direction — three layers of motion analysis extracted from a single smoothed price signal, all normalized to a common ±100 scale so every layer is directly comparable at a glance.
How It Works
Step 1 — Smoothing
Raw price is too noisy to differentiate reliably. TDE first passes your source through one of three selectable filters to extract the underlying motion curve before computing any derivatives.
Savitzky-Golay (default) fits a 2nd-order polynomial to a moving window of bars using Gram polynomial coefficients. Unlike a moving average, it preserves the shape of peaks and troughs rather than smoothing them away. Window sizes of 5, 7, 9, 11, 13, and 15 are supported, each with exact integer coefficients — no approximation. This gives the best phase response of the three filters: signals appear earlier and with less distortion.
Gaussian weights each past bar by a bell-curve function of its distance from the current bar. Sigma controls how quickly the weights fall off. Softer and more trailing than SG, useful when you want a cleaner curve at the cost of a slight lag.
Kalman is a single-state recursive filter that continuously estimates the "true" price by balancing how much it trusts the new measurement (R) versus how much the underlying process is expected to move (Q). It adapts bar-to-bar, making it the most responsive of the three with the least lag, but also the most sensitive to sharp moves.
Step 2 — Finite Difference Derivatives
Once the smoothed signal sm is computed, three derivatives are calculated using standard finite difference formulas:
Velocity (1st derivative): sm − sm — the rate of change of price. Positive means price is rising, negative means it is falling. The magnitude tells you how fast.
Acceleration (2nd derivative): sm − 2·sm + sm — the rate of change of velocity. Positive means momentum is building; negative means it is fading, even if price is still moving in the same direction.
Jerk (3rd derivative): sm − 3·sm + 3·sm − sm — the rate of change of acceleration. A leading indicator of acceleration reversals. When jerk crosses zero, acceleration is about to change direction.
Step 3 — Normalization
Each derivative is divided by its rolling peak absolute value over the normalization lookback window, then scaled to ±100. This keeps all three series on the same axis and comparable to each other, regardless of the instrument's price level or volatility. A velocity reading of +80 and an acceleration reading of +80 carry equivalent relative meaning within their own histories.
Signals
Zero Crosses
Every time a derivative crosses the zero line, a marker appears at the top or bottom of the panel. Each derivative has a distinct shape to avoid confusion:
Velocity (Circle): Bottom (bullish) / Top (bearish)
Acceleration (Diamond): Bottom (bullish) / Top (bearish)
Jerk (Square): Bottom (bullish) / Top (bearish)
Each set of markers is independently gated by its visibility toggle, so you only see the crosses for the series you have enabled.
Velocity cross — the most direct signal. When velocity crosses above zero, price momentum has turned positive on the source timeframe. Below zero, it has turned negative.
Acceleration cross — a timing tool, not a trend signal. When acceleration crosses above zero while velocity is still positive, the move is re-accelerating. When acceleration crosses below zero while velocity is still positive, the move is losing steam — the trend continues, but is starting to exhaust. Acceleration reversals frequently precede velocity reversals by several bars.
Jerk cross — the earliest signal in the chain. Jerk crossing zero means acceleration is about to change direction. By itself, jerk is noisy, but when it aligns with acceleration near a zero cross, it can give a meaningful early warning.
Divergence Markers (Triangles)
Divergence fires when acceleration crosses zero while velocity is still extreme — specifically when |vn| > 30. This combination means the move has been strong enough to be considered extended, but the underlying force driving it is already reversing.
Bear divergence (▼ triangle, top): Acceleration crosses below zero while velocity is still elevated above +30. The upswing's engine is cutting out while the price is still high. Historically, this precedes deceleration into a stall or reversal.
Bull divergence (▲ triangle, bottom): Acceleration crosses above zero while velocity is still depressed below −30. The downswing is losing power from the bottom. Historically, this precedes a deceleration of selling and a potential recovery.
Divergence markers are rarer than zero crosses by design. They represent a specific confluence, not a general crossover signal.
Regime Background
The panel background is tinted to reflect the current momentum regime:
Velocity > 0 and Acceleration > 0: Accelerating bull - Cyan tint
Velocity < 0 and Acceleration < 0: Accelerating bear - Red tint
No tint: Decelerating or mixed - Neutral
The regime is also displayed in the info table with four states: ▲ Accelerating, ↗ Decelerating, ↘ Recovering, ▼ Falling.
Signal Line
An EMA of velocity (default length 9) is plotted as a thin white line over the velocity histogram. Velocity crossing its own signal line is an additional early entry cue, analogous to the MACD signal cross but applied directly to the derivative layer.
Settings
⏱ Timeframe
Source Timeframe — the timeframe on which the smoothed signal is computed before derivatives are taken. Options: Auto, Chart, 5m, 15m, 1H, 4H, 1D, 1W.
Auto scales to a fixed higher timeframe based on your current chart: below 5m → 15m, below 15m → 1H, below 1H → 4H, below 4H → 1D, otherwise 1W. This allows the indicator to show higher-timeframe derivative structure on any intraday chart without manual adjustment.
The chart uses the same timeframe as the chart is on. Useful when you want the derivatives of the chart's own bars rather than a higher context.
🔬 Smoothing Filter
Filter — selects the smoothing method: Savitzky-Golay (recommended), Gaussian, or Kalman.
SG Window (SG only) — odd integer from 5 to 15. Controls the width of the polynomial fitting window. Larger windows produce smoother derivatives with (window−1)/2 additional bars of lag. Window 9 is the default and a good general-purpose choice. Use 5 or 7 for faster signals on volatile instruments; 13 or 15 for cleaner derivatives on smooth trends.
Gaussian Length (Gaussian only) — number of bars in the weighted sum. Longer = smoother.
Gaussian Sigma (Gaussian only) — controls the standard deviation of the bell curve. Lower values concentrate weight on recent bars; higher values spread it more evenly.
Kalman Q — Process Noise (Kalman only) — how much the filter expects the price to move on its own each bar. Higher Q makes the filter track price more closely with less smoothing. Range 0.0001–1.0, default 0.01.
Kalman R — Measurement Noise (Kalman only) — how much the filter distrusts the raw price measurement. Higher R produces more smoothing and more lag. Range 0.01–50.0, default 1.0.
📈 Derivatives & Display
Price Source — the input series to smooth and differentiate. Defaults to close. Can be set to any source, including hl2, ohlc4, or another indicator's output via the source selector.
Normalization Lookback — the rolling window (in bars) over which each derivative is scaled to ±100. Shorter windows (e.g., 50) make the indicator more responsive to recent extremes; longer windows (e.g., 200–500) provide a more stable baseline. Default 100.
Signal EMA Length — the length of the EMA applied to normalized velocity to produce the signal line. Default 9.
Velocity (1st deriv) — show/hide the velocity histogram and line, and its zero-crossing markers.
Acceleration (2nd deriv) — show/hide the acceleration line and its zero-cross diamond markers.
Jerk (3rd deriv) — show/hide the jerk line and its zero-crossing square markers. Hidden by default as it is primarily useful for advanced analysis.
Signal Line on Velocity — show/hide the EMA signal line overlay on velocity.
Divergence Markers — show/hide the bear/bull divergence triangle markers.
🎨 Colors
All seven colour elements are individually configurable: Velocity (up/down), Acceleration (up/down), Jerk (up/down), and the Signal line.
Alerts
Eight alert conditions are available:
Velocity → Positive: Velocity crosses above zero
Velocity → Negative: Velocity crosses below zero
Momentum Trough: Acceleration crosses above zero
Momentum Peak: Acceleration crosses below zero
Jerk → Positive: Jerk crosses above zero
Jerk → Negative: Jerk crosses below zero
Bullish Divergence: Acceleration recovers while velocity is below −30
Bearish Divergence: Acceleration rolls over while velocity is above +30
Reading the Indicator Together
The three layers are designed to be read in sequence, from slowest to fastest signal:
Check velocity for trend direction — is the move positive or negative?
Check acceleration for conviction — is the move building or fading?
Check jerk for early warning — is acceleration about to change?
A high-confidence setup aligns all three: velocity positive, acceleration positive and rising, jerk positive. As a move matures, acceleration will peak and roll over first, while velocity remains elevated — that is the divergence condition. Velocity eventually follows. Jerk will often signal the peak of acceleration one step earlier still.
No single cross is a trade signal on its own. TDE is a momentum structure tool. It is most useful when combined with price structure, support/resistance levels, and a defined higher timeframe bias. Indicator

Kalman Volume Trend [BigBeluga]🔵 OVERVIEW
Kalman Volume Trend is an advanced trend-following system that combines the predictive power of a Kalman Filter with real-time volume delta analysis. Unlike standard moving averages that suffer from significant lag, the Kalman Filter uses a recursive mathematical algorithm to estimate the "true" trend by filtering out market noise.
The indicator not only identifies directional regimes but also visualizes the intensity of buying and selling pressure directly on the trend line, providing a multi-dimensional view of market conviction.
🔵 CONCEPT
Kalman Filter Logic — A state-space model that predicts price movement and then corrects itself based on new data, resulting in a smoother yet more responsive trend line than traditional EMAs.
Adaptive ATR Bands — The trend direction is determined by price breaking through volatility-adjusted bands, reducing whipsaws in sideways markets.
Volume-Weighted Trend Lines — The indicator plots "Volume Bars" extending from the trend line, where the length and color represent the relative strength of the volume delta.
Cumulative Trend Statistics — It tracks the total buy volume, sell volume, and net delta from the exact moment a new trend begins.
🔵 HOW IT WORKS (IN-DEPTH)
1️⃣ The Kalman Filtering Process
The script utilizes two primary parameters: Process Noise (Q) and Measurement Noise (R) .
It calculates a "State Estimate" (the trend) by balancing its previous prediction against the current price.
If the price is "jittery" (high R), the filter smooths the line; if the trend is moving decisively (low Q), it tracks the price more aggressively.
2️⃣ Trend Direction & Volatility Bands
Two bands are projected around the Kalman line based on a multiplier of the Average True Range (ATR) .
A Bullish trend is triggered when price closes above the upper band.
A Bearish trend is triggered when price closes below the lower band.
Once a trend is established, the opposite band acts as the trailing "Trend Line" to provide a clear buffer for price fluctuations.
3️⃣ Volume Delta Visualization
Small vertical candles ("Volume Bars") are plotted along the trend line.
These bars represent the Normalized Volume Delta (Close vs. Open and Volume intensity).
Large bars indicate high-conviction participation, while small bars suggest waning interest or consolidation.
4️⃣ Extreme Volume & Cumulative Dashboard
When volume exceeds 1.5x its recent average, an "X" label appears on the chart to mark an Exhaustion or Ignition point.
A bottom-right dashboard displays a vertical histogram showing the balance of power (BUY vs. SELL vs. DELTA) for the current trend only .
🔵 KEY FEATURES
Recursive Kalman Algorithm: High-accuracy trend tracking with minimal lag.
Integrated Volume Profiling: See volume delta without needing a separate sub-window.
Dynamic Trend Dashboard: Automatically resets at every trend flip to show fresh volume stats.
Volatility-Aware: Uses 200-period ATR to ensure bands adapt to changing market conditions.
Volume Extreme Alerts: Identifies high-volume spikes that often precede trend reversals.
🔵 DASHBOARD METRICS
BUY — Total volume accumulated on bullish candles since the trend started.
SELL — Total volume accumulated on bearish candles since the trend started.
DELTA — The net difference between buying and selling pressure.
TOTAL VOLUME — The total "fuel" spent during the current directional regime.
🔵 HOW TO USE
Riding the Trend: Stay in the trade as long as the Kalman line color remains consistent.
Spotting Weakness: If the Kalman line is Bullish (Blue) but the Volume Bars are consistently negative or shrinking, the trend may be losing steam.
High-Volume Breakouts: Look for the "X" labels at the start of a trend shift; this confirms institutional participation in the new direction.
Dashboard Confirmation: Use the vertical histogram to confirm if the buyers or sellers are truly in control during a pullback to the trend line.
🔵 CONCLUSION
Kalman Volume Trend offers a sophisticated approach to trend analysis by merging high-level signal processing with raw volume data. By focusing on "clean" price data and weighting it with volume delta, it helps traders filter out market noise and focus on high-conviction movements. Indicator

Regime-Adaptive kNN Breakouts + Kalman Predictor [TechnicalZen]Regime-Adaptive kNN Breakout Classifier + Kalman Price Predictor
Why This Indicator Exists
Most breakout indicators treat every compression pattern equally. In reality, a volatility contraction forming during a high-ADX trending environment with surging volume behaves very differently from the same pattern in a choppy, low-volume consolidation.
This indicator addresses that gap by combining three distinct analytical engines:
Multi-Period Compression Detection — Scans across multiple bar periods to find the tightest range relative to recent history, identifying genuine volatility contraction zones where expansion is statistically likely.
Regime-Adaptive kNN Classification — A machine learning gate that evaluates the market regime surrounding each compression zone using Kalman-filtered features. Only setups with sufficient similarity to historically successful breakouts are allowed through.
Kalman Price Predictor — A state-space estimator tracking price position and velocity, enabling forward projection with a widening uncertainty cone.
The result is an indicator that learns which market conditions produce successful breakouts and provides a probabilistic price forecast — not just pattern detection.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW IT WORKS
1. Multi-Period Compression Detection
The engine evaluates bar ranges across 2 to 20 periods, computing each period's range (highest high minus lowest low) and comparing it against the minimum range observed within an adaptive lookback window. When the current range is tighter than any historical range in the window, a compression zone is identified. The smallest qualifying period is selected — representing the most extreme volatility contraction.
An optional Inside Bar filter adds a complementary signal when the current bar's range is entirely contained within the prior bar.
2. ADX-Adaptive Lookback Window
The comparison window dynamically adjusts based on trend strength:
High ADX (strong trend) — shorter lookback, more responsive to compression during momentum phases
Low ADX (ranging market) — longer lookback, requiring more extreme contraction before triggering
This prevents the indicator from being too sensitive in trending markets or too sluggish in ranging conditions.
3. Kalman-Filtered Feature Space
Four market regime features are computed on every bar and smoothed through independent Kalman filters using a position + velocity state-space model. The Kalman filter reduces noise while tracking each feature's rate of change — achieving smoothing without the lag penalty of traditional moving averages.
The kNN classifier operates entirely on these Kalman-filtered features:
Relative Volume — Volume / SMA(Volume, 100) — captures participation surge or drought, Kalman-smoothed to filter out single-bar volume spikes
Relative ATR — ATR(14) / SMA(ATR, 100) — captures volatility expansion vs contraction regime, Kalman-smoothed for stable regime identification
ADX Normalized — ADX / 50 — measures trend strength (direction-agnostic), Kalman-smoothed to track trend momentum
Distance from MA — (Close - Trend MA) / ATR — price position relative to trend, Kalman-smoothed to reduce whipsaw noise
By filtering the feature space through the Kalman estimator before classification, the kNN operates on cleaner, denoised regime signals rather than raw noisy measurements. This is the critical link between the Kalman filter and the kNN — the classifier's accuracy depends on the quality of its input features.
4. kNN Breakout Classification
When a compression zone triggers a breakout, the classifier:
Constructs a feature vector from the four Kalman-filtered regime features
Scans the history buffer using Manhattan distance to find similar past regime conditions
Selects the k-nearest resolved neighbors — only TP (take-profit) and SL (stop-loss) outcomes vote; pending and time exits are excluded entirely
Computes a distance-weighted classification score where closer neighbors have proportionally more influence
Compares the score against the user-defined confidence threshold
If the score falls below the threshold, the setup is silently skipped. The classifier has learned which combinations of volume regime, volatility regime, trend strength, and price position tend to produce winning breakouts.
Key design choices:
Adaptive k — k = floor(sqrt(resolved outcomes)), clamped between user-defined min/max. The number of neighbors consulted grows naturally as the classifier accumulates experience, preventing overfitting to sparse early data.
Warmup phase — During the first N resolved outcomes, all setups pass through to build the training set. The classifier only begins filtering after accumulating sufficient data.
Feedback loop — Every exit writes its outcome back to the history buffer. TP exits score 1.0, SL exits score 0.0. The classifier genuinely learns from the specific chart and timeframe it is applied to.
Distance-weighted voting — Prevents outlier neighbors from distorting the classification. A very close TP neighbor outweighs several distant SL neighbors, producing more nuanced probability estimates.
5. Kalman Price Predictor
A fifth Kalman filter runs on price itself, maintaining three estimates simultaneously:
Filtered position — optimal smoothed price estimate
Velocity — estimated rate of price change per bar
Covariance matrix — estimation uncertainty and cross-correlations
The velocity component enables forward projection: Predicted Price = Filtered Position + Velocity x Projection Bars . The uncertainty cone is scaled by ATR and widens proportionally to the square root of the projection horizon — reflecting the theoretical uncertainty growth of price over time.
Projection trail: The last 5 projections are displayed with graduated transparency (50% to 90%), creating a visual history of how the forecast has evolved. A consistent, parallel trail suggests strong directional conviction; a diverging or oscillating trail signals uncertainty.
6. Trend-Aware Exit System
The exit system uses four complementary mechanisms, each feeding outcomes back to the kNN:
Take Profit — R-multiple target (default 2R, where R = compression zone range). Scored as 1.0 in kNN feedback.
Stop Loss — Opposite side of compression zone, optionally requiring price to also be wrong-side of the Trend MA. This trend-aware condition reduces whipsaw stops in strong trends. Scored as 0.0 in kNN feedback.
Trailing Stop — Activates after 1R profit, trails by ATR x multiplier. Dynamic protection that locks in gains.
Time Exit — Maximum bars in trade before forced exit. Scored as 0.5 (neutral) — neither rewarding nor penalizing the kNN for inconclusive setups.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
VISUAL GUIDE
Chart Elements
Compression boxes — Colored zones marking detected volatility contraction (green = bullish breakout, red = bearish)
Extended levels — Dotted lines projecting the high and low of each compression zone forward
Entry labels — Direction and kNN confidence percentage (e.g., "Long 72.5%")
Exit labels — TP / SL / T markers with R-multiple detail in tooltip
Projection line — Dashed line extending forward from Kalman-filtered price
Uncertainty cone — ATR-scaled filled area widening into the future
Projection trail — 5 fading historical projections showing forecast evolution
Kalman price line — Optional smoothed price curve (off by default)
Dashboard (bottom-right)
Win Rate — Percentage of resolved trades hitting TP (tinted green or red)
Trades — Win / Loss count
Mode — Distance-weighted classification
Phase — Warmup (building data) or Active (filtering enabled)
k — Current adaptive k value
Score — Latest kNN confidence score
History — Buffer fill level (e.g., 45/60)
Projection — Predicted price with directional arrow
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SETTINGS GUIDE
Detection
Enable Inside Bar (default: On) — Include Inside Bar patterns alongside compression detection
Adaptive kNN
Enable kNN Filter (default: On) — Toggle the ML classification gate
k Min / k Max (default: 2 / 10) — Bounds for adaptive k. Auto-scales with sqrt of resolved outcomes
Confidence Threshold (default: 0.25) — Minimum kNN score to accept a setup. Lower values are more permissive; higher values are more selective
Min Resolved to Activate (default: 15) — TP/SL outcomes needed before the classifier begins filtering
History Buffer Size (default: 60) — Maximum stored breakout patterns for comparison
Kalman Filter
Process Noise Q (default: 0.01) — Controls how much the filter expects the underlying signal to change between bars. Higher values make the filter more responsive but noisier
Measurement Noise R (default: 0.10) — Controls how much the filter distrusts each new measurement. Higher values produce smoother output with more lag
Show Price Projection (default: On) — Display the forward projection line and uncertainty cone
Projection Bars (default: 10) — How far forward to project price
Projection Color (default: Aqua) — Color for all projection elements
Show Uncertainty Cone (default: On) — Display the ATR-scaled confidence band
Cone Width (default: 1.0 ATR) — Width multiplier for the uncertainty cone. Adjustable per instrument
Show Kalman Price Line (default: Off) — Display the smoothed Kalman price estimate on chart
Trend Filter
Enable Trend Filter (default: On) — Restrict breakouts to trend-aligned direction only
Trend MA Mode (default: Adaptive) — Static = fixed MA length; Adaptive = MA length scales dynamically with the compression lookback
MA Type (default: EMA) — Exponential or Wilder's (RMA) moving average
Adaptive Multiplier (default: 2.0) — Lookback x Multiplier = MA length in adaptive mode
Static MA Length (default: 200) — Fixed MA length when in static mode
Adaptive Look Back
Look Back Mode (default: ADX Adaptive) — Static = fixed comparison window; ADX Adaptive = window scales with trend strength
ADX Length (default: 14) — Period for ADX calculation
ADX Low / High (default: 10 / 35) — ADX range mapped to lookback bounds. Higher ADX compresses the lookback
LB Min / LB Max (default: 20 / 120) — Minimum and maximum lookback window size
Exits
TP (R-multiple target) (default: On) — Take-profit at R-multiple of compression zone range
SL (opposite side) (default: On) — Stop-loss at opposite boundary of compression zone
Target R (default: 2.0) — Take-profit distance as multiple of range
Trend-Aware SL (default: On) — SL only triggers when price is also wrong-side of Trend MA
Trailing Stop (default: On) — Trails by ATR x multiplier after 1R profit
Trail ATR Multiplier (default: 1.5) — Trail distance = ATR(14) x this value
Time Exit (default: On, 50 bars) — Force exit after maximum bars in trade
Visual Settings
Bull / Bear / Time colors — Customizable directional colors
Box Fill / Border Transparency — Compression zone box appearance
Extend Levels (default: 50 bars) — Forward projection distance for compression zone levels
Level Width / Style — Line appearance for projected levels
Max Patterns Kept (default: 120) — Maximum drawing objects maintained on chart
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
THE KALMAN-kNN PIPELINE
The two ML components are not independent — they form a pipeline:
Kalman filters denoise the four regime features on every bar, producing clean estimates of volume regime, volatility regime, trend strength, and price position
kNN classifier operates on these Kalman-filtered features, comparing the current denoised regime against historically successful and unsuccessful breakout conditions
Kalman price filter independently tracks price dynamics, projecting the estimated trajectory forward with quantified uncertainty
The classifier's accuracy fundamentally depends on the quality of its input features. By feeding Kalman-filtered signals rather than raw measurements, the kNN compares regime states rather than noisy observations — producing more stable and meaningful similarity assessments.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CREDITS AND ACKNOWLEDGMENTS
This indicator builds upon concepts from two published works:
Smart NR2–NR20 and Inside Bar by Zeiierman — multi-period compression detection, adaptive lookback via ADX, and breakout trigger architecture
kNN Market Architecture by LuxAlgo — application of k-nearest neighbors classification to filter market signals using relative volatility and volume features
Original contributions in this indicator:
Kalman filter state-space estimation for feature smoothing (position + velocity model with full covariance tracking)
Kalman-to-kNN pipeline — classifier operates on denoised regime features, not raw measurements
Regime-adaptive kNN classification with distance-weighted voting on resolved outcomes only
Real-time feedback loop where exit outcomes update the kNN training data
Adaptive k scaling based on accumulated classifier experience
Kalman price predictor with forward projection and ATR-scaled uncertainty cone
Graduated projection trail showing forecast evolution
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This indicator is for educational and informational purposes only. It does not constitute financial advice. All investments involve risk, and past performance does not guarantee future results. The kNN classifier learns from historical patterns on the specific chart and timeframe it is applied to — its effectiveness may vary across different instruments and market conditions. Always conduct your own analysis and risk management.
Indicator

Indicator

Indicator

Kalman Hull Trend Score [BackQuant]Kalman Hull Trend Score
Overview
Kalman Hull Trend Score is a trend-strength and regime-evaluation indicator that combines two ideas, Kalman filtering and Hull-style smoothing, then measures persistence of that filtered trend using a rolling score. The goal is to produce a cleaner, more stable trend read than typical moving average tools, while still reacting fast enough to be practical in live markets.
Instead of treating a moving average as a simple line you cross, this indicator turns the filtered trend into an oscillator-like score that answers: “Is the smoothed trend consistently progressing, or is it stalling and degrading?”
Core idea
The indicator is built from two components:
A Kalman-based smoothing engine that estimates price state and reduces noise adaptively.
A Hull-style construction that uses multiple Kalman passes to create a responsive, low-lag trend filter.
Once the Kalman Hull filter is built, a persistence score is calculated by comparing the current Kalman Hull value to many past values. The result is a trend score that rises in sustained trends and compresses or flips during deterioration.
Why Kalman instead of standard smoothing
Traditional moving averages apply fixed smoothing rules regardless of market conditions. A Kalman filter behaves differently, it is designed to estimate an underlying state in noisy data, adjusting how much it “trusts” new price information versus prior estimates.
This script exposes that behavior through two key controls:
Measurement Noise: how noisy the observed price is assumed to be.
Process Noise: how much the underlying state is allowed to evolve from bar to bar.
Together, these settings let you tune the balance between smoothness and responsiveness without relying on blunt averaging alone.
Kalman filter mechanics (conceptual)
Each update cycle follows the classic structure:
Prediction: assume the state continues, and expand uncertainty by process noise.
Update: compute Kalman Gain, then blend the new price observation into the estimate.
Correction: reduce uncertainty based on how much the filter accepted the new information.
When measurement noise is higher, the filter becomes more conservative, smoothing harder. When process noise is higher, the filter adapts faster to regime changes, but can become more reactive.
Check out the original script:
Kalman Hull construction
The “Hull” component is not a standard HMA built from WMAs. Instead, it recreates the Hull idea using Kalman filtering as the smoothing primitive. The structure follows the same intent as HMA, reduce lag while keeping the line smooth, but does it with Kalman passes:
Apply Kalman smoothing over multiple effective lengths.
Combine them using the Hull-style weighting logic.
Run the combined output through another Kalman pass to finalize smoothing.
The result is a Kalman Hull filter that aims to track trend with less jitter than raw price, and less lag than slow averages.
Another Kalman Hull with Supertrend
Trend scoring logic
The trend score is computed by comparing the current Kalman Hull value to past Kalman Hull values over a fixed lookback range (1 to 45 bars in this script):
If current kalmanHMA > kalmanHMA , add +1
If current kalmanHMA < kalmanHMA , add -1
This produces a persistence score rather than a simple direction signal. Strong trends where the filter keeps advancing will accumulate positive comparisons. Weak trends, chop, or reversals will cause the score to flatten, decay, or flip negative.
Interpreting the score
Read the score as trend conviction and persistence:
High positive values: bullish persistence, the filtered trend is progressing consistently.
Low positive values: trend exists but is fragile, progress is slowing.
Near zero: indecision, range behavior, frequent challenges to structure.
Negative values: bearish persistence or sustained deterioration in the filtered trend.
The rate of change matters:
Score expansion suggests trend is gaining traction.
Score compression often signals consolidation or exhaustion.
Fast flips usually accompany regime transitions.
Signal thresholds and regime transitions
User-defined thresholds convert the score into regimes:
Long threshold: score must exceed this level to confirm bullish persistence.
Short threshold: a crossunder of the score triggers bearish regime transition.
This is intentionally conservative. Long bias is maintained while the score holds above the long threshold. Short transitions are event-triggered on breakdown via crossunder, helping avoid constant flipping during minor noise.
Signals are only plotted on regime changes (first bar of the flip), keeping them clean for alerts and backtests.
Visual presentation
The indicator provides multiple layers depending on how you want to use it:
Kalman Hull Trend Score oscillator, color-coded by active regime.
Optional Kalman Hull filter plotted on the price chart for structure context.
Optional threshold reference lines for quick regime mapping.
Optional candle coloring and background shading for instant readability.
You can run it as a pure score panel or as a combined panel + on-chart trend overlay.
How to use in practice
Trend filtering
Favor long setups when the score remains above the long threshold.
Reduce directional aggression when score compresses toward zero.
Treat a short-threshold breakdown as a regime risk event, not just a signal.
Trend quality assessment
Rising score supports continuation trades and adds confidence to breakouts.
Flat or falling score warns that trend persistence is fading.
If price trends but score fails to expand, trend may be weak or liquidity-driven.
Trade management
Use the Kalman Hull line as dynamic structure reference on chart.
Use score deterioration to scale out before a full regime flip.
Use regime flips as confirmation for bias shifts rather than prediction.
Tuning guidelines
Measurement Noise
Higher: smoother filter, fewer false shifts, slower to adapt.
Lower: more responsive, more sensitive to microstructure noise.
Process Noise
Higher: adapts quicker to sudden changes, but can become twitchy.
Lower: steadier state estimate, but slower during sharp regime transitions.
A practical approach is to first tune measurement noise until the Kalman Hull line matches the “clean trend structure” you want, then adjust process noise to control how quickly it reacts when the regime genuinely changes.
Summary
Kalman Hull Trend Score transforms a Kalman-based Hull-style trend filter into a quantified persistence oscillator. By combining adaptive Kalman smoothing with low-lag Hull logic and a rolling comparison score, it provides a cleaner read on trend quality than basic moving averages or single-condition trend tools. It is best used as a regime filter, trend strength gauge, and structure-aware trade management layer.
Indicator

Kalman Absorption/Distribution Tracker 3-State EKFQuant-Grade Institutional Flow: 3-State EKF Absorption Tracker
SUMMARY
An advanced, open-source implementation of a 3-State Extended Kalman Filter (EKF) designed to track institutional Order Flow. By analyzing 1-second intrabar microstructure data, this script estimates the true Position, Velocity, and Volatility of the Cumulative Volume Delta (CVD), revealing hidden Absorption and Distribution events in real-time.
INTRODUCTION: THE SIGNAL AMIDST THE NOISE
In the world of technical analysis, noise is the enemy. Traditional indicators rely on Moving Averages (SMA, EMA) to smooth out price and volume data. The problem is the "Lag vs. Noise" paradox: to get a smooth signal, you must accept lag; to get a fast signal, you must accept noise.
This indicator solves that paradox by introducing aerospace-grade mathematics to the PulseWire community: The 3-State Extended Kalman Filter (EKF).
Unlike moving averages that blindly average past data, a Kalman Filter is a probabilistic state-space model. It constantly predicts where the order flow "should" be, compares it to the actual measurement, and updates its internal model based on the calculated uncertainty of the market.
This script is not just another volume oscillator. It is a full microstructure analysis engine that digests intrabar data (down to 1-second resolution) to track the true intent of "Smart Money" while filtering out the noise of retail chop.
THE INNOVATION: WHY 3 STATES?
Most Kalman Filters found in public libraries are "1-State" (tracking price only) or occasionally "2-State" (tracking price and velocity). This script introduces a highly advanced 3-State EKF.
The filter tracks three distinct variables simultaneously in a feedback loop:
State 1: Position (The True CVD)
This is the noise-filtered estimate of the Cumulative Volume Delta. It represents the actual inventory accumulation of aggressive buyers versus sellers, stripped of random noise.
State 2: Velocity (The Momentum)
This tracks the rate of change of the order flow. Is buying accelerating? Is selling pressure fading even as price drops? This provides a leading signal before the cumulative value even turns.
State 3: Volatility (The Adaptive Regime)
This is the game-changer. The filter estimates the current volatility of the order flow (Log-Volatility). In high-volatility environments (like news events), the filter automatically widens its uncertainty bands (Covariance) and reacts faster. In low-volatility environments (chop), it tightens up and ignores minor fluctuations.
THE LOGIC: DETECTING ABSORPTION AND DISTRIBUTION
The core philosophy of this indicator is based on Wyckoff Logic: Effort vs. Result.
-- Effort: Represented by the CVD (Buying/Selling pressure).
-- Result: Represented by Price Movement.
When these two diverge, we have an actionable signal. The script uses the EKF Velocity state to detect these moments:
Absorption (Bullish)
This occurs when the EKF detects high negative Velocity (aggressive selling), but Price refuses to drop. The "Smart Money" is absorbing the sell orders via limit buys. The indicator highlights this as a Blue Event in the dashboard.
Distribution (Bearish)
This occurs when the EKF detects high positive Velocity (aggressive buying), but Price refuses to rise. Limit sellers are capping the market. The indicator highlights this as an Orange Event.
TECHNICAL DEEP DIVE: UNDER THE HOOD
For the developers and quants, here is how the Pine Script is architected using the "type" and "method" features of Pine Script v5.
1. Data Ingestion (Microstructure)
The script uses "request.security_lower_tf" to pull intrabar data regardless of your chart timeframe. This allows the script to see "inside" the bar. A 5-minute candle might look green, but the microstructure might reveal that 80% of the volume was selling absorption at the wick. This script sees that.
2. Tick Classification
Standard CVD assumes that if Price Close is greater than Price Open, all volume is buying. This is often flawed. This script offers three modes of tick handling, including a "High-Low Distribution" method that statistically apportions volume based on where the tick closed relative to its high and low.
3. The EKF Mathematics
The script implements the standard Extended Kalman Filter equations manually. It calculates the Jacobian matrix to handle the non-linear relationship between volatility and price. The "Process Noise Matrix" (Q) is dynamically scaled by the Volatility State. This means the mathematics of the indicator literally "breathe" with the market conditions—expanding during expansion and contracting during consolidation.
THE DASHBOARD & VISUALS:
The indicator features a professional-grade HUD (Heads Up Display) located on the chart table.
-- EKF State Vector: Displays the real-time Position, Velocity, and Volatility values derived from the matrix.
-- Ease of Movement (Wyckoff): Calculates how much price moves per 1,000 contracts of CVD. For example, if Price moves +5 points per 1k Buy CVD, but only -2 points per 1k Sell CVD, the "Path of Least Resistance" is clearly UP.
-- Session State: Tracks cumulative confirmed Bullish vs. Bearish events for Today, Yesterday, and the Day Before (3-Day Profile).
-- Bias Summary: An algorithmic conclusion telling you if the day is "Confirmed Bullish," "Accumulating," or "Neutral."
HOW TO TRADE THIS INDICATOR
Strategy A: The Reversal (Absorption Play)
Look for price making a Lower Low.
Look for the EKF Velocity (Histogram) to be Deep Red (High Selling Pressure).
Watch the Dashboard "Absorption" count increase.
SIGNAL: When EKF Velocity crosses back toward zero and turns grey/green, the absorption is complete. This indicates sellers are exhausted and limit buyers have control.
Strategy B: The Trend Continuation (Ease of Movement)
Check the Dashboard "Ease of Movement" section.
If "Price per +1K CVD" is significantly higher than "Price per -1K CVD", buyers are efficient.
Wait for a pullback where EKF Velocity hits the "Neutral Zone" (Gray).
SIGNAL: Enter Long when Velocity ticks positive again, aligning with the dominant Ease of Movement stats.
CONFIGURATION GUIDE:
Because this is a quant-grade tool, the settings allow for fine-tuning the physics of the filter.
-- Velocity Decay: Controls how fast momentum resets to zero. Set high (0.98) for trending markets, or lower (0.85) for mean-reverting chop.
-- Volatility Persistence: Controls how "sticky" volatility regimes are.
-- Process Noise: Increase this if the filter feels too laggy; decrease it if the filter feels too jittery (noisy).
-- Measurement Noise: Increase this to trust the Mathematical Model more than the Price Data (smoother output).
WHY OPEN SOURCE?
Complex statistical filtering is often sold behind closed doors in expensive "Black Box" algorithms. By releasing this 3-State EKF open source, the goal is to raise the standard of development on PulseWire.
I encourage the community to inspect the code, specifically the "ekf_update_3state" function, to understand how matrix operations can be simulated in Pine Script to create adaptive, self-correcting indicators. And also update me for improvements.
DISCLAIMER:
This tool analyzes microstructure volume data. It requires a subscription plan that supports Intrabar inspection (Premium/Pro recommended for best results). Past performance of the Kalman Filter logic does not guarantee future results. Volume analysis is subjective and should be used as part of a comprehensive strategy.
SUGGESTED SETTINGS
-- Timeframe: Works best on 1m, 3m, or 5m charts (Intrabar data is fetched from 1S).
-- Asset Class: Highly effective on Futures (ES, NQ, BTC) and high-volume Forex/Crypto pairs where volume data is reliable.
-- Background: Dark mode recommended for Dashboard visibility.
WHAT IS A KALMAN FILTER?
Imagine driving a car into a tunnel where your GPS signal is lost.
Prediction: Your car knows its last speed (Velocity) and position. It predicts where you are every second inside the tunnel.
Update: When you exit the tunnel, the GPS connects again. The system compares where it thought you were versus where the satellite says you are.
Correction: It corrects your position and updates its estimate of your speed.
Now apply this to trading:
-- The Tunnel: Market Noise, wicks, and Fake-outs.
-- The Car: The True Market Trend.
-- This Indicator: The navigation system that tells you where the market actually is, ignoring the noise of the tunnel.
Enjoy the indicator and trade safe!
Dr. Jay Desai
(Investment Management & Derivatives Area, Gujarat University)
Indicator

Kalman Hull Kijun [BackQuant]Kalman Hull Kijun
A trend baseline that merges three ideas into one clean overlay, Kalman filtering for noise control, Hull-style responsiveness, and a Kijun-like Donchian midline for structure and bias.
Context and lineage
This indicator sits in the same family as two related scripts:
Kalman Price Filter
This is the foundational building block. It introduces the Kalman filter concept, a state-estimation algorithm designed to infer an underlying “true” signal from noisy measurements, originally used in aerospace guidance and later adopted across robotics, economics, and markets.
Kalman Hull Supertrend
This is the original script made, which people loved. So it inspired me to create this one.
Kalman Hull Kijun uses the same core philosophy as the Supertrend variant, but instead of building a Supertrend band system, it produces a single structural baseline that behaves like a Kijun-style reference line.
What this indicator is trying to solve
Most trend baselines sit on a bad trade-off curve:
If you smooth hard, the line reacts late and misses turns.
If you react fast, the line whipsaws and tracks noise.
Kalman Hull Kijun is designed to land closer to the middle:
Cleaner than typical fast moving averages in chop.
More responsive than slow averages in directional phases.
More “structure aware” than pure averages because the baseline is range-derived (Kijun-like) after filtering.
Core idea in plain language
The plotted line is a Kijun-like baseline, but it is not built from raw candles directly.
High level flow:
Start with a chosen price stream (source input).
Reduce measurement noise using Kalman-style state estimation.
Add Hull-style responsiveness so the filtered stream stays usable for trend work.
Build a Kijun-like baseline by taking a Donchian midpoint of that filtered stream over the base period.
So the output is a single baseline that is intended to be:
Less jittery than a simple fast MA.
Less laggy than a slow MA.
More “range anchored” than standard smoothing lines.
How to read it
1) Trend and bias (the primary use)
Price above the baseline, bullish bias.
Price below the baseline, bearish bias.
Clean flips across the baseline are regime changes, especially when followed by a hold or retest.
2) Retests and dynamic structure
Treat the baseline like dynamic S/R rather than a signal generator:
In uptrends, pullbacks that respect the baseline can act as continuation context.
In downtrends, reclaim failures around the baseline can act as continuation context.
Repeated back-and-forth around the line usually means compression or chop, not clean trend.
3) Extension vs compression (using the fill)
The fill is meant to communicate “distance” and “pressure” visually:
Large separation between price and baseline suggests expansion.
Price compressing into the baseline suggests rebalancing and decision points.
Inputs and what they change
Kijun Base Period
Controls the structural memory of the baseline.
Higher values track broader swings and reduce flips.
Lower values track tighter swings and react faster.
Kalman Price Source
Defines what data the filter is estimating.
Close is usually the cleanest default.
HL2 often “feels” smoother as an average price.
High/Low sources can become more reactive and less stable depending on the market.
Measurement Noise
Think of this as the main smoothness knob:
Higher values generally produce a calmer filtered stream.
Lower values generally produce a faster, more reactive stream.
Process Noise
Think of this as adaptability:
Higher values adapt faster to changing conditions but can get twitchy.
Lower values adapt slower but stay stable.
Plotting and UI (what you see on chart)
1) Adaptive line coloring
Baseline turns bullish color when price is above it.
Baseline turns bearish color when price is below it.
This makes the state readable without extra panels.
2) Gradient “energy” fill
Bull fill appears between price and baseline when above.
Bear fill appears between price and baseline when below.
The goal is clarity on separation and control, not decoration.
3) Rim effect
A subtle band around price that only appears on the active side.
Helps highlight directional control without hiding candles.
4) Candle painting (optional)
Candles can be colored to match the current bias.
Useful for scanning many charts quickly.
Disable if you prefer raw candles.
Alerts
Long state alert when price is above the baseline.
Short state alert when price is below the baseline.
Best used as a bias or regime notification, not a standalone entry trigger.
Where it fits in a workflow
This is a context layer, it pairs well with:
Market structure tools, BOS/MSB, OBs, FVGs.
Momentum triggers that need a regime filter.
Mean reversion tools that need “do not fade trends” context.
Limitations
No baseline eliminates chop whipsaws, tuning only manages the trade-off.
Settings should not be copy pasted across assets without checking behavior.
This does not forecast, it estimates and smooths state, then expresses it as a structural baseline.
Disclaimer
Educational and informational only, not financial advice.
Not a complete trading system.
If you use it in any trading workflow, do proper backtesting, forward testing, and risk management before any live execution.
Indicator

VWAP Kalman FilterOverview
This indicator applies Kalman filtering techniques to Volume Weighted Average Price (VWAP) calculations, providing a statistically optimized approach to VWAP analysis. The Kalman filter reduces noise while maintaining responsiveness to genuine price movements, addressing common VWAP limitations in volatile or low-volume conditions.
Technical Implementation
Kalman Filter Mathematics
The indicator implements a state-space model for VWAP estimation:
- Prediction Step: x̂(k|k-1) = x̂(k-1|k-1) + v(k-1)
- Update Step: x̂(k|k) = x̂(k|k-1) + K(k)
- Kalman Gain: K(k) = P(k|k-1) / (P(k|k-1) + R)
Where:
- x̂ = estimated VWAP state
- K = Kalman gain (adaptive weighting factor)
- P = error covariance
- R = measurement noise
- Q = process noise
- v = optional velocity component
Core Components
Dual VWAP System
- Standard VWAP: Traditional volume-weighted calculation
- Kalman-filtered VWAP: Noise-reduced estimation with optional velocity tracking
- Real-time divergence measurement between filtered and unfiltered values
Adaptive Filtering
- Process Noise (Q): Controls adaptation to price changes (0.001-1.0)
- Measurement Noise (R): Determines smoothing intensity (0.01-5.0)
- Optional velocity tracking for momentum-based filtering
Multi-Timeframe Anchoring
- Session, Weekly, Monthly, Quarterly, and Yearly anchor periods
- Automatic Kalman state reset on anchor changes
- Maintains VWAP integrity across timeframes
Features
Visual Components
- Dual VWAP Lines: Compare filtered vs. unfiltered in real-time
- Dynamic Bands: Three-level deviation bands (1σ, 2σ, 3σ)
- Trend Coloring: Automatic color adaptation based on price position
- Cloud Visualization: Highlights divergence between standard and Kalman VWAP
- Signal Markers: Crossover and band-touch indicators
Trading Signals
- VWAP crossover detection with Kalman filtering
- Band touch alerts at multiple standard deviation levels
- Velocity-based momentum confirmation (optional)
- Divergence warnings when filtered/unfiltered values separate
Information Display
- Real-time VWAP values (both standard and filtered)
- Trend direction indicator
- Velocity/momentum reading (when enabled)
- Divergence percentage calculation
- Anchor period display
Input Parameters
VWAP Settings
- Anchor Period: Choose calculation reset period
- Band Multipliers: Customize deviation band distances
- Display Options: Toggle standard VWAP and bands
Kalman Parameters
- Length: Base period for calculations (5-200)
- Process Noise (Q: Higher values increase responsiveness
- Measurement Noise (R): Higher values increase smoothing
- Velocity Tracking: Enable momentum-based filtering
Visual Controls
- Toggle filtered/unfiltered VWAP display
- Band visibility options
- Signal markers on/off
- Cloud fill between VWAPs
- Bar coloring by trend
Use Cases
Noise Reduction
Particularly effective during:
- Low volume periods (pre-market, lunch hours)
- Volatile market conditions
- Fast-moving markets where standard VWAP whipsaws
Trend Identification
- Cleaner trend signals with reduced false crosses
- Earlier trend detection through velocity component
- Confirmation through divergence analysis
Support/Resistance
- Filtered VWAP provides more stable S/R levels
- Bands adapt to filtered values for better zone identification
- Reduced false breakout signals
Technical Advantages
1. Optimal Estimation: Mathematically optimal under Gaussian noise assumptions
2. Adaptive Response: Self-adjusting to market conditions
3. Predictive Element: Velocity component provides forward-looking insight
4. Noise Immunity: Superior noise rejection vs. simple moving average smoothing
Limitations
- Assumes linear price dynamics
- Requires parameter optimization for different instruments
- May lag during sudden volatility regime changes
- Not suitable as standalone trading system
Mathematical Background
Based on control systems theory, the Kalman filter provides recursive Bayesian estimation originally developed for aerospace applications. This implementation adapts the algorithm specifically for financial time series, maintaining VWAP's volume-weighted properties while adding statistical filtering.
Comparison with Standard VWAP
Standard VWAP Issues Addressed:
- Choppy behavior in low volume
- Whipsaws around VWAP line
- Lag in trend identification
- Noise in deviation bands
Kalman VWAP Benefits:
- Smooth yet responsive line
- Fewer false signals
- Optional momentum tracking
- Statistically optimized filtering
Alert Conditions
The indicator includes several pre-configured alert conditions:
- Bullish/Bearish VWAP crosses
- Upper/Lower band touches
- High divergence warnings
- Velocity shifts (if enabled)
---
This open-source indicator is provided as-is for educational and trading purposes. No guarantees are made regarding trading performance. Users should conduct their own testing and validation before using in live trading. Indicator
