// This Pine Script® code is licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// © PineForge contributors 2026
//
// PF probe kkb-probe-01-kalman-filter — per-bar 1-D Kalman update
// Clean-room: written from validation goal, not from source.
//
// Purpose: isolates a 1-dimensional Kalman filter state recurrence written
// directly in PineScript. The engine surface under test is the cross-bar
// `var float` state pair (state estimate + error covariance) and the per-bar
// predict / update arithmetic:
//
// x_pred = x[1]
// p_pred = p[1] + q
// k_gain = p_pred / (p_pred + r)
// x = x_pred + k_gain * (close - x_pred)
// p = (1 - k_gain) * p_pred
//
// Verifies that engine vs TV agree on the gain numerics, especially after
// many recursive updates where small per-bar drift compounds.
//
// Validation goal: bit-exact entries on `ta.crossover(close, x)` and exits
// on `ta.crossunder(close, x)`. Pass = identical trade list vs TradingView.
//
// TV setup: 15m chart, ETH-USDT-USDT (Binance USDT-M Perpetual). Full window
// matching corpus/data/ohlcv_ETH-USDT-USDT_15m.csv. Strategy properties:
// leave defaults from script header. Export "List of trades" → tv_trades.csv.
//@version=6
strategy("PF probe kkb-probe-01-kalman-filter", shorttitle="PF_kkb01_KAL",
overlay=true, initial_capital=1000000,
commission_type=strategy.commission.percent, commission_value=0,
slippage=0, default_qty_type=strategy.fixed, default_qty_value=1,
pyramiding=1, process_orders_on_close=false)
// ---- inputs --------------------------------------------------------
float i_q = input.float(0.001, "Process variance Q", minval=0.0, step=0.0005)
float i_r = input.float(0.1, "Measurement variance R", minval=0.0001, step=0.01)
// ---- Kalman state (cross-bar) -------------------------------------
var float x = na
var float p = 1.0
float x_pred = nz(x[1], close)
float p_pred = nz(p[1], 1.0) + i_q
float k_gain = p_pred / (p_pred + i_r)
x := x_pred + k_gain * (close - x_pred)
p := (1 - k_gain) * p_pred
// ---- crosses -------------------------------------------------------
bool cross_up = ta.crossover(close, x)
bool cross_down = ta.crossunder(close, x)
// ---- order routing -------------------------------------------------
if cross_up and strategy.position_size <= 0
strategy.entry("L", strategy.long, qty=1, comment="kalman cross up")
if cross_down and strategy.position_size >= 0
strategy.entry("S", strategy.short, qty=1, comment="kalman cross down")