OPEN-SOURCE SCRIPT

Structural Momentum Gauge [JOAT]

1 195
Structural Momentum Gauge [JOAT]

Introduction

Structural Momentum Gauge [JOAT] is an open-source overlay indicator that fuses an adaptive Kalman filter with a Supertrend ratchet trail and a WMA-based volatility envelope to produce three clearly defined regime states: Bull Trend, Bear Trend, and Range-Bound. Rather than relying on a fixed moving average, the Kalman filter continuously self-calibrates its noise estimate each bar, delivering a smoothed price proxy that adapts to changing market conditions without introducing unnecessary lag. The Supertrend ratchet applied directly to the Kalman value — rather than to a raw price midpoint — generates directional bias changes that are markedly more stable than those produced by conventional price-based systems.

The core problem this indicator addresses is that most trend-following tools either repaint (flipping signals on the same bar as price reverses) or commit to a direction far too slowly. The Kalman filter's gain calculation absorbs noise on low-momentum bars while remaining sensitive during genuine impulses. Layering an envelope breach condition on top means both the Kalman direction and price location relative to the volatility band must agree before a trend regime is confirmed — a dual-gate that substantially reduces false readings on choppy, sideways charts.

snapshot

Core Concepts

1. Adaptive Kalman Filter

The Kalman filter maintains two persistent state variables: the current estimate (k_est) and the error variance (k_err). Each bar the Kalman gain is computed as k_err / (k_err + noise), where noise equals kAlpha * kPeriod. The gain controls how much the estimate shifts toward the current close. After updating the estimate, the error variance is revised: (1 - gain) * k_err + kBeta / kPeriod. This means a large prediction error pushes the variance higher, increasing the gain on the next bar and making the filter more responsive. When price action settles, the gain contracts and the filter smooths out. The result is a price proxy that is neither the fixed-lag of a simple moving average nor the noise sensitivity of a raw close.

2. Supertrend Ratchet on Kalman

ATR-scaled upper and lower bands are applied around the Kalman value rather than the raw hl2. The ratchet rule then applies: the upper band can only move down (or reset when the Kalman value crosses above it), and the lower band can only move up (or reset when the Kalman value crosses below it). Direction flips when the Kalman value closes through the active band. Applying the ratchet to a pre-filtered price removes the micro-fluctuations that cause excessive direction changes when using hl2 directly.

3. WMA Volatility Envelope

A WMA of the high-low range, multiplied by the deviation parameter, defines half the envelope width. The envelope upper and lower levels are placed symmetrically around the Kalman value. An extended outer cloud — 1.35x the inner envelope — is plotted for spatial context. A price close above the upper envelope sets the range state to 1; a close below the lower sets it to -1. Regime confirmation requires both the Kalman Supertrend direction and the envelope range state to agree in sign:

4. Regime Classification

combined = kBias * rState, where kBias is +1 when the Kalman Supertrend is bullish and rState is +1 when close is above the upper envelope. combined == 1 with kBias == 1 is a confirmed bull trend. combined == 1 with kBias == -1 is a confirmed bear trend. All other states are range or opposing. A rolling 50-bar history computes what percentage of recent bars were in a trending state, producing a Trend Strength percentage.

5. K-Velocity

The rate of change of the Kalman value over three bars, normalized by the current ATR, yields a K-Velocity score from 0 to 1. Velocity dots appear on the Kalman line when the score exceeds 0.5, with their transparency inversely proportional to the velocity — faster moves produce more saturated dots. This creates a visual intensity signal on the trail itself, communicating acceleration and deceleration without a separate panel.


Features

  • Adaptive Kalman Filter: Self-calibrating price proxy with alpha and beta gain controls — responds faster during impulses, smooths more during consolidation
  • Supertrend Ratchet on Kalman: Direction-persistent trail applied to the Kalman value, eliminating noise-driven flips on raw price crossovers
  • Outer Envelope Cloud: Wide ATR envelope filled directionally, providing spatial context at a glance
  • Inner Envelope Fill: Standard WMA envelope bands with conditional fills that activate in range regime
  • Triple-Layer Kalman Glow: Three stacked plots at widths 9, 5, and 2 with decreasing transparency create a neon glow shadow effect on the Kalman line
  • Gradient Core Fills: 6-argument fill() between Kalman and candle mid-body, transparent at the Kalman line and saturated at the body — colored by confirmed regime
  • K-Velocity Dots: Pulsing circles on the trail during high-velocity trend bars, intensity scales with normalized velocity score
  • Regime Transition Circles: Circle marker fires at every confirmed regime change — immediate visual alert to state transitions
  • Bull/Bear Trend Start Arrows: Triangle up/down plotshape fires at the exact bar where both Kalman direction and envelope breach first agree
  • Trend End Marker: X marker fires when the trending regime ends, helping traders tighten stops or close positions
  • Kalman Flip Labels: K▲ / K▼ labels placed below/above the Supertrend level when the Kalman bias flips direction
  • Envelope Squeeze Marker: Golden diamond when envelope width drops below 80% of its recent SMA — flags compression before potential breakout
  • Gradient Bar Coloring: Bars saturate based on distance from Kalman within envelope range, fading to neutral in range-bound conditions
  • 10-Row Dashboard: Regime state, K-Trend direction, Kalman price, upper/lower band levels, trend bar count, T-Strength %, K-Velocity %, volatility state


Input Parameters

Kalman Filter:
  • Alpha (Smoothing): Controls base noise level — lower values produce a smoother, higher-lag filter (default 0.01)
  • Beta (Adapt Rate): Controls how quickly error variance recovers after a large miss — higher values make the filter adapt faster (default 0.10)
  • Period: Normalises the gain magnitude — acts as a scaling factor on both noise and beta (default 77)


Supertrend:
  • ST Factor: ATR multiplier for the ratchet bands around the Kalman value (default 0.7)
  • ST ATR Length: ATR lookback for the Supertrend band calculation (default 7)


Volatility Envelope:
  • Envelope WMA Length: Lookback for the WMA of high-low range (default 200)
  • Envelope Deviation: Multiplier on the WMA to set envelope half-width (default 1.2)


Visuals:
  • Toggles for Supertrend line, envelope bands, gradient fills, Kalman glow, envelope cloud, and dashboard
  • Bull Color (default cyan #22d3ee), Bear Color (default rose #f43f5e), Range Color (default slate #94a3b8)


How to Use This Indicator

Primary Setup — Trend Confirmation Entry:
Wait for a trend start arrow (triangle up or down) to fire. This marks the bar where the Kalman Supertrend direction and the envelope breach state first agree. Enter in the arrow direction. Trail your stop below the Kalman line for longs or above it for shorts. Exit on a Trend End X marker or when the K▲/K▼ flip label fires against your position.

Using K-Velocity for Sizing:
When velocity dots are dense and bright, momentum is expanding — the trending move is accelerating. When dots thin out or disappear, momentum is fading even if the regime has not changed yet. Reduce size on fade or tighten stops before the trend end marker appears.

Squeeze Setup:
When the golden diamond squeeze marker fires, the envelope is compressing. Wait for price to break the envelope band in either direction. If a trend start arrow follows within the next few bars, this is a high-probability breakout entry aligned with both volatility expansion and regime confirmation.

Reading the Dashboard:
T-Strength above 60% indicates a mature, sustained trend. Values below 30% indicate the regime state is new or unstable — the trend is young and position sizing should reflect that uncertainty.

snapshot

Indicator Limitations

  • The Kalman filter's gain is bounded by the alpha and beta parameters. Very low alpha values may make the filter too sluggish to capture short, sharp reversal moves before the ratchet trail catches them
  • The envelope breach condition for regime confirmation means the indicator will not register a trend until price has already moved far enough from the Kalman center to exit the band — entries will not be at the very start of a move
  • On instruments with consistently narrow true range (low-liquidity futures, off-hours sessions), the WMA envelope may be so tight that price is rarely inside the band, causing permanent range state classification
  • The Kalman filter uses close-to-close data and has no concept of intrabar price action; on daily charts, a spike high that closes near the open may produce a different Kalman trajectory than on a lower timeframe
  • Trend Strength is a rolling 50-bar measure. On very fast timeframes, 50 bars may represent only minutes, making the percentage less meaningful as a maturity gauge


Originality Statement

This indicator is original in its application of a Kalman filter as the supertrend base, the dual-gate regime confirmation system, and the K-velocity visual intensity layer. The publication is justified because:
  • Applying the Supertrend ratchet to a Kalman-filtered price rather than raw hl2 produces direction changes that are measurably more stable — the Kalman pre-filters noise that would otherwise cause excessive band crossings
  • The dual-gate regime system (Kalman direction AND envelope breach must agree) produces a stricter trending classification than any single-condition approach, reducing false trend readings in sideways conditions
  • The K-velocity normalization layer embeds a momentum acceleration measure directly into the trail visualization without requiring a separate panel, communicating both direction and rate-of-change simultaneously
  • The envelope squeeze detection integrated with trend start arrows identifies the specific condition where compressed volatility resolves into a confirmed regime shift — a novel combination for a Kalman-based system
  • The Trend Strength rolling percentage provides a trend maturity measure that distinguishes freshly flipped regimes from mature, sustained trends, enabling differentiated position sizing without a separate indicator


Disclaimer

This indicator is provided for educational and informational purposes only and does not constitute financial advice or a recommendation to buy or sell any financial instrument. Past performance of any pattern or signal does not guarantee future results. All trading involves substantial risk. Always use proper risk management and conduct your own independent analysis.

— Made with passion by officialjackofalltrades

Wyłączenie odpowiedzialności

Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.