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 TradingView 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 TradingView'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
TradingView 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 TradingView'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 TradingView'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 TradingView's data feed. The indicator requires a Premium or Ultimate TradingView 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 TradingView 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 TradingView.
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

Kalman VWAP Filter [BackQuant]Kalman VWAP Filter
A precision-engineered price estimator that fuses Kalman filtering with the Volume-Weighted Average Price (VWAP) to create a smooth, adaptive representation of fair value. This hybrid model intelligently balances responsiveness and stability, tracking trend shifts with minimal noise while maintaining a statistically grounded link to volume distribution.
If you would like to see my original Kalman Filter, please find it here:
Concept overview
The Kalman VWAP Filter is built on two core ideas from quantitative finance and control theory:
Kalman filtering — a recursive Bayesian estimator used to infer the true underlying state of a noisy system (in this case, fair price).
VWAP anchoring — a dynamic reference that weights price by traded volume, representing where the majority of transactions have occurred.
By merging these concepts, the filter produces a line that behaves like a "smart moving average": smooth when noise is high, fast when markets trend, and self-adjusting based on both market structure and user-defined noise parameters.
How it works
Measurement blend : Combines the chosen Price Source (e.g., close or hlc3) with either a Session VWAP or a Rolling VWAP baseline. The VWAP Weight input controls how much the filter trusts traded volume versus price movement.
Kalman recursion : Each bar updates an internal "state estimate" using the Kalman gain, which determines how much to trust new observations vs. the prior state.
Noise parameters :
Process Noise controls agility — higher values make the filter more responsive but also more volatile.
Measurement Noise controls smoothness — higher values make it steadier but slower to adapt.
Filter order (N) : Defines how many parallel state estimates are used. Larger orders yield smoother output by layering multiple one-dimensional Kalman passes.
Final output : A refined price trajectory that captures VWAP-adjusted fair value while dynamically adjusting to real-time volatility and order flow.
Why this matters
Most smoothing techniques (EMA, SMA, Hull) trade off lag for smoothness. Kalman filtering, however, adaptively rebalances that tradeoff each bar using probabilistic weighting, allowing it to follow market state changes more efficiently. Anchoring it to VWAP integrates microstructure context — capturing where liquidity truly lies rather than only where price moves.
Use cases
Trend tracking : Color-coded candle painting highlights shifts in slope direction, revealing early trend transitions.
Fair value mapping : The line represents a continuously updated equilibrium price between raw price action and VWAP flow.
Adaptive moving average replacement : Outperforms static MAs in variable volatility regimes by self-adjusting smoothness.
Execution & reversion logic : When price diverges from the Kalman VWAP, it may indicate short-term imbalance or overextension relative to volume-adjusted fair value.
Cross-signal framework : Use with standard VWAP or other filters to identify convergence or divergence between liquidity-weighted and state-estimated prices.
Parameter guidance
Process Noise : 0.01–0.05 for swing traders, 0.1–0.2 for intraday scalping.
Measurement Noise : 2–5 for normal use, 8+ for very smooth tracking.
VWAP Weight : 0.2–0.4 balances both price and VWAP influence; 1.0 locks output directly to VWAP dynamics.
Filter Order (N) : 3–5 for reactive short-term filters; 8–10 for smoother institutional-style baselines.
Interpretation
When price > Kalman VWAP and slope is positive → bullish pressure; buyers dominate above fair value.
When price < Kalman VWAP and slope is negative → bearish pressure; sellers dominate below fair value.
Convergence of price and Kalman VWAP often signals equilibrium; strong divergence suggests imbalance.
Crosses between Kalman VWAP and the base VWAP can hint at shifts in short-term vs. long-term liquidity control.
Summary
The Kalman VWAP Filter blends statistical estimation with market microstructure awareness, offering a refined alternative to static smoothing indicators. It adapts in real time to volatility and order flow, helping traders visualize balance, transition, and momentum through a lens of probabilistic fair value rather than simple price averaging.
Indicator

Kalman Adjusted Average True Range [BackQuant]Kalman Adjusted Average True Range
A volatility-aware trend baseline that fuses a Kalman price estimate with ATR “rails” to create a smooth, adaptive guide for entries, exits, and trailing risk.
Built on my original Kalman
This indicator is based on my original Kalman Price Filter:
That core smoother is used here to estimate the “true” price path, then blended with ATR to control step size and react proportionally to market noise.
What it plots
Kalman ATR Line the main baseline that turns up/down with the filtered trend.
Optional Moving Average of the Kalman ATR a secondary line for confluence (SMA/Hull/EMA/WMA/DEMA/RMA/LINREG/ALMA).
Candle Coloring (optional) paint bars by the baseline’s current direction.
Why combine Kalman + ATR?
Kalman reduces measurement noise and produces a stable path without the lag of heavy MAs.
ATR rails scale the baseline’s step to current volatility, so it’s calm in chop and more responsive in expansion.
The result is a single, intelligible line you can trade around: slope-up = constructive; slope-down = caution.
How it works (plain English)
Each bar, the Kalman filter updates an internal state (tunable via Process Noise , Measurement Noise , and Filter Order ) to estimate the underlying price.
An ATR band (Period × Factor) defines the allowed per-bar adjustment. The baseline cannot “jump” beyond those rails in one step.
A direction flip is detected when the baseline’s slope changes sign (upturn/downturn), and alerts are provided for both.
Typical uses
Trend confirmation Trade in the baseline’s direction; avoid fading a firmly rising/falling line.
Pullback timing Look for entries when price mean-reverts toward a rising baseline (or exits on tags of a falling one).
Trailing risk Use the baseline as a dynamic guide; many traders set stops a small buffer beyond it (e.g., a fraction of ATR).
Confluence Enable the MA overlay of the Kalman ATR; alignment (baseline above its MA and rising) supports continuation.
Inputs & what they do
Calculation
Kalman Price Source which price the filter tracks (Close by default).
Process Noise how quickly the filter can adapt. Higher = more responsive (but choppier).
Measurement Noise how much you distrust raw price. Higher = smoother (but slower to turn).
Filter Order (N) depth of the internal state array. Higher = slightly steadier behavior.
Kalman ATR
Period ATR lookback. Shorter = snappier; longer = steadier.
Factor scales the allowed step per bar. Larger factors permit faster drift; smaller factors clamp movement.
Confluence (optional)
MA Type & Period compute an MA on the Kalman ATR line , not on price.
Sigma (ALMA) if ALMA is selected, this input controls the curve’s shape. (Ignored for other MA types.)
Visuals
Plot Kalman ATR toggle the main line.
Paint Candles color bars by up/down slope.
Colors choose long/short hues.
Signals & alerts
Trend Up baseline turns upward (slope crosses above 0).
Alert: “Kalman ATR Trend Up”
Trend Down baseline turns downward (slope crosses below 0).
Alert: “Kalman ATR Trend Down”
These are state flips , not “price crossovers,” so you avoid many one-bar head-fakes.
How to start (fast presets)
Swing (daily/4H) ATR Period 7–14, Factor 0.5–0.8, Process Noise 0.02–0.05, Measurement Noise 2–4, N = 3–5.
Intraday (5–15m) ATR Period 5–7, Factor 0.6–1.0, Process Noise 0.05–0.10, Measurement Noise 2–3, N = 3–5.
Slow assets / FX raise Measurement Noise or ATR Period for calmer lines; drop Factor if the baseline feels too jumpy.
Reading the line
Rising & curving upward momentum building; consider long bias until a clear downturn.
Flat & choppy regime uncertainty; many traders stand aside or tighten risk.
Falling & accelerating distribution lower; short bias until a clean upturn.
Practical playbook
Continuation entries After a Trend Up alert, wait for a minor pullback toward the baseline; enter on evidence the line keeps rising.
Exit/reduce If long and the baseline flattens then turns down, trim or exit; reverse logic for shorts.
Filters Add a higher-timeframe check (e.g., only take longs when the daily Kalman ATR is rising).
Stops Place stops just beyond the baseline (e.g., baseline − x% ATR for longs) to avoid “tag & reverse” noise.
Notes
This is a guide to state and momentum, not a guarantee. Combine with your process (structure, volume, time-of-day) for decisions.
Settings are asset/timeframe dependent; start with the presets and nudge Process/Measurement Noise until the baseline “feels right” for your market.
Summary
Kalman ATR takes the noise-reduction of a Kalman price estimate and couples it with volatility-scaled movement to produce a clean, adaptive baseline. If you liked the original Kalman Price Filter (), this is its trend-trading cousin purpose-built for cleaner state flips, intuitive trailing, and confluence with your existing
Indicator

Algorithmic Kalman Filter [CRYPTIK1]Price action is chaos. Markets are driven by high-frequency algorithms, emotional reactions, and raw speculation, creating a constant stream of noise that obscures the true underlying trend. A simple moving average is too slow, too primitive to navigate this environment effectively. It lags, it gets chopped up, and it fails when you need it most.
This script implements an Algorithmic Kalman Filter (AKF), a sophisticated signal processing algorithm adapted from aerospace and robotic guidance systems. Its purpose is singular: to strip away market noise and provide a hyper-adaptive, self-correcting estimate of an asset's true trajectory.
The Concept: An Adaptive Intelligence
Unlike a moving average that mindlessly averages past data, the Kalman Filter operates on a two-step principle: Predict and Update.
Predict: On each new bar, the filter makes a prediction of the true price based on its previous state.
Update: It then measures the error between its prediction and the actual closing price. It uses this error to intelligently correct its estimate, learning from its mistakes in real-time.
The result is a flawlessly smooth line that adapts to volatility. It remains stable during chop and reacts swiftly to new trends, giving you a crystal-clear view of the market's real intention.
How to Wield the Filter: The Core Settings
The power of the AKF lies in its two tuning parameters, which allow you to calibrate the filter's "brain" to any asset or timeframe.
Process Noise (Q) - Responsiveness: This controls how much you expect the true trend to change.
A higher Q value makes the filter more sensitive and responsive to recent price action. Use this for highly volatile assets or lower timeframes.
A lower Q value makes the filter smoother and more stable, trusting that the underlying trend is slow-moving. Use this for higher timeframes or ranging markets.
Measurement Noise (R) - Smoothness: This controls how much you trust the incoming price data.
A higher R value tells the filter that the price is extremely noisy and to be more skeptical. This results in a much smoother, slower-moving line.
A lower R value tells the filter to trust the price data more, resulting in a line that tracks price more closely.
The interaction between Q and R is what gives the filter its power. The default settings provide a solid baseline, but a true operator will fine-tune these to perfectly match the rhythm of their chosen market.
Tactical Application
The AKF is not just a line; it's a complete framework for viewing the market.
Trend Identification: The primary signal. The filter's color code provides an unambiguous definition of the trend. Teal for an uptrend, Pink for a downtrend. No more guesswork.
Dynamic Support & Resistance: The filter itself acts as a dynamic level. Watch for price to pull back and find support on a rising (Teal) filter in an uptrend, or to be rejected by a falling (Pink) filter in a downtrend.
A Higher-Order Filter: Use the AKF's trend state to filter signals from your primary strategy. For example, only take long signals when the AKF is Teal. This single rule can dramatically reduce noise and eliminate low-probability trades.
This is a professional-grade tool for traders who are serious about gaining a statistical edge. Ditch the lagging averages. Extract the signal from the noise. Indicator
