OPEN-SOURCE SCRIPT

Kalman Trend State [forexobroker]

930
Kalman Trend State applies a recursive Kalman filter to price, treating the unobserved trend as a hidden state with two components: instantaneous price level and per-bar velocity. Unlike a moving average, the filter's smoothing gain updates bar-by-bar from the residuals (innovation), so it adapts to volatility automatically without any length knob.

🔶 ALGORITHM

1. State [px, vx] tracks price and velocity. Transition F = [[1,1],[0,1]] (constant-velocity model).
2. Process noise Q is ATR-adaptive: Q = q_base + q_scale * (ATR / close). Higher volatility = larger Q = faster adaptation.
3. Measurement noise R is fixed (user input). Higher R = filter trusts the model more, smoother output.
4. At each bar: predict (px, P) -> measure close -> update gain K = P_pred * H' / S where S = P_pred[0,0] + R -> correct (px, vx, P).
5. The innovation z-score (close - prediction) / sigma quantifies how well the filter is tracking.

🔶 SIGNAL LOGIC

- Buy: velocity > k * ATR AND |innovation z| <= sigma gate AND close crosses Kalman line up AND not already long AND cooldown elapsed AND barstate.isconfirmed.
- Sell: mirror with velocity < -k * ATR.
- Position-lock state machine prevents same-side over-firing.

🔶 INPUTS

- Process Noise Base Q (default 0.001)
- Q ATR-Pct Scale (default 0.01)
- Measurement Noise R (default 1.0)
- Velocity Threshold x ATR (default 0.10)
- Innovation Sigma Gate (default 1.0)
- Cooldown Bars (default 4)
- Visual: 3-layer glow toggle, Kalman line toggle, dashboard toggle, buy / sell colors

🔶 ALERTS

KTS Buy, KTS Sell, KTS Any Signal, KTS Trend Up Start, KTS Trend Down Start, KTS Clean Fit, KTS Cross Up, KTS Cross Down, KTS Webhook JSON.

🔶 LIMITATIONS

- Kalman is optimal under linear-Gaussian assumptions; price is heavy-tailed, so the filter occasionally lags during regime breaks.
- Warm-up: about 14 bars (ATR seed). Earlier bars have NaN-guarded fallbacks but signals stay flat.
- Defaults tuned for liquid majors and indices on 5m-1H. Re-tune R for tick-driven micro-instruments.
- Velocity threshold scales with ATR but the filter itself does not change shape; for highly seasonal assets, a session-aware variant may help.

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.