OPEN-SOURCE SCRIPT

Kalman Quantum Drift [JOAT]

2 027
KALMAN QUANTUM DRIFT [JOAT]

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.

snapshot

The Kalman filter, properly

A single-state recursive Bayesian filter. At each bar:

  1. Predict: prior estimate = previous estimate. Prior variance = previous variance + Q.
  2. 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.

snapshot

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:

  1. 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.
  2. 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.
  3. σ 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

Aviso legal

As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.