PINE LIBRARY
Cập nhật KalmanEngineLib

KalmanEngineLib
A Pine Script v6 library that provides a reusable engine for multi-state Kalman filtering, symmetric covariance packing, sequential scalar measurement updates, Mahalanobis gating, adaptive noise estimation, online coupling estimation, multi-scale trajectory storage, covariance-derived confidence bands, and k-step covariance propagation.
What it does
Implements a generic N-state Kalman filter where the posterior covariance P is stored as a packed upper triangle (n*(n+1)/2 elements), saving ~47% memory vs a full matrix.new<float>(n,n) at n=14.
Supports block-diagonal transition matrices via separate sub-blocks (3×3 kinematics, 6×6 z-score dynamics, 5×5 Mahalanobis, 3×5 cross-coupling Γ_lag) instead of a single n×n F matrix.
Provides a sequential scalar measurement update in Joseph form for numerical stability; calling it once per observation is equivalent to a batch update but avoids allocating an m×n H matrix.
Core components
UDTs: KalmanState_N, TransitionConfig, TrajectoryStore, ConceptConfig — callers own all persistent state; library functions are stateless transforms.
Triangle primitives: f_tri_idx, f_tri_get, f_tri_set, f_tri_new, f_tri_diag, f_tri_add_outer_product for packed symmetric matrix arithmetic.
Prediction: f_predict_block, f_predict_identity, f_P_predict_diag, f_P_predict_cross.
Update: f_sequential_update returning [innovation, S] for external diagnostics.
Gating: f_mahalanobis_3d (analytic 3×3 inverse with Ledoit-Wolf shrinkage and diagonal fallback near singularity), f_nis_test, f_gating_gain_mod.
Adaptive noise: f_adaptive_Q_scalar (windowed MLE), f_adaptive_R_scalar (innovation z-score ratchet).
Coupling: f_gamma_lag_update (scalar 1-D Kalman β-tracker for Γ_lag elements).
Trajectory: f_traj_init, f_traj_update, f_traj_xcorr — circular buffers at Δ={3,5,7} bar skips with Pearson cross-correlation for lag calibration.
Bands and projection: f_covariance_band_width, f_confidence_envelope, f_k_step_cov_propagation, f_z_spread.
Derived outputs: KMEMA (adaptive EMA modulated by innovation shock, TE confidence, velocity), online OLS beta update, execution-score helpers.
Architecture notes
All functions are stateless transforms operating on UDTs passed by the caller; no var declarations inside library functions.
Element budget: ~3,600 for the core engine; ~1,800 for TrajectoryStore at depth=100, n_feat=6. Total ~22K elements under Pine's 100K limit.
Self-healing: f_state_sanitize resets na or overflow entries in x and P diagonals to caller-supplied defaults.
Usage pattern
Declare a var KalmanState_N state = f_init_regression(n, P0, Q0, R0) in the indicator.
Each bar: call f_predict_block → f_P_predict_diag/f_P_predict_cross → one or more f_sequential_update per scalar observation → optional f_mahalanobis_3d/f_adaptive_Q_scalar/f_adaptive_R_scalar → read outputs via f_z_spread, f_confidence_envelope, f_k_step_cov_propagation.
Scope
General-purpose Kalman infrastructure; no market-specific logic, no signals, no thresholds embedded. Intended as a dependency for indicators and strategies that need rigorous multi-state filtering with adaptive noise and regime-aware gating.
License
Mozilla Public License 2.0.
A Pine Script v6 library that provides a reusable engine for multi-state Kalman filtering, symmetric covariance packing, sequential scalar measurement updates, Mahalanobis gating, adaptive noise estimation, online coupling estimation, multi-scale trajectory storage, covariance-derived confidence bands, and k-step covariance propagation.
What it does
Implements a generic N-state Kalman filter where the posterior covariance P is stored as a packed upper triangle (n*(n+1)/2 elements), saving ~47% memory vs a full matrix.new<float>(n,n) at n=14.
Supports block-diagonal transition matrices via separate sub-blocks (3×3 kinematics, 6×6 z-score dynamics, 5×5 Mahalanobis, 3×5 cross-coupling Γ_lag) instead of a single n×n F matrix.
Provides a sequential scalar measurement update in Joseph form for numerical stability; calling it once per observation is equivalent to a batch update but avoids allocating an m×n H matrix.
Core components
UDTs: KalmanState_N, TransitionConfig, TrajectoryStore, ConceptConfig — callers own all persistent state; library functions are stateless transforms.
Triangle primitives: f_tri_idx, f_tri_get, f_tri_set, f_tri_new, f_tri_diag, f_tri_add_outer_product for packed symmetric matrix arithmetic.
Prediction: f_predict_block, f_predict_identity, f_P_predict_diag, f_P_predict_cross.
Update: f_sequential_update returning [innovation, S] for external diagnostics.
Gating: f_mahalanobis_3d (analytic 3×3 inverse with Ledoit-Wolf shrinkage and diagonal fallback near singularity), f_nis_test, f_gating_gain_mod.
Adaptive noise: f_adaptive_Q_scalar (windowed MLE), f_adaptive_R_scalar (innovation z-score ratchet).
Coupling: f_gamma_lag_update (scalar 1-D Kalman β-tracker for Γ_lag elements).
Trajectory: f_traj_init, f_traj_update, f_traj_xcorr — circular buffers at Δ={3,5,7} bar skips with Pearson cross-correlation for lag calibration.
Bands and projection: f_covariance_band_width, f_confidence_envelope, f_k_step_cov_propagation, f_z_spread.
Derived outputs: KMEMA (adaptive EMA modulated by innovation shock, TE confidence, velocity), online OLS beta update, execution-score helpers.
Architecture notes
All functions are stateless transforms operating on UDTs passed by the caller; no var declarations inside library functions.
Element budget: ~3,600 for the core engine; ~1,800 for TrajectoryStore at depth=100, n_feat=6. Total ~22K elements under Pine's 100K limit.
Self-healing: f_state_sanitize resets na or overflow entries in x and P diagonals to caller-supplied defaults.
Usage pattern
Declare a var KalmanState_N state = f_init_regression(n, P0, Q0, R0) in the indicator.
Each bar: call f_predict_block → f_P_predict_diag/f_P_predict_cross → one or more f_sequential_update per scalar observation → optional f_mahalanobis_3d/f_adaptive_Q_scalar/f_adaptive_R_scalar → read outputs via f_z_spread, f_confidence_envelope, f_k_step_cov_propagation.
Scope
General-purpose Kalman infrastructure; no market-specific logic, no signals, no thresholds embedded. Intended as a dependency for indicators and strategies that need rigorous multi-state filtering with adaptive noise and regime-aware gating.
License
Mozilla Public License 2.0.
Phát hành các Ghi chú
v2Phát hành các Ghi chú
v3Phát hành các Ghi chú
v4Added:
f_kalman1d_init(P0, Q, R)
Initialize 1D Kalman filter
Parameters:
P0 (float): Initial estimate variance
Q (float): Process noise variance
R (float): Measurement noise variance
Returns: Initialized KalmanState1D
method update(s, z)
Update 1D Kalman filter with new measurement
Namespace types: KalmanState1D
Parameters:
s (KalmanState1D): KalmanState1D to update (mutated in-place)
z (float): New measurement
Returns: Updated state (same reference as input)
KalmanState1D
Simple 1D Kalman filter for scalar smoothing (ergonomic wrapper over N-dim API)
Fields:
x (series float)
P (series float)
Q (series float)
R (series float)
Phát hành các Ghi chú
v5Added:
f_sep_pair5(mu_a, sigma_a, mu_b, sigma_b, use_f4, use_f5, var_floor)
Parameters:
mu_a (array<float>)
sigma_a (matrix<float>)
mu_b (array<float>)
sigma_b (matrix<float>)
use_f4 (bool)
use_f5 (bool)
var_floor (float)
Phát hành các Ghi chú
v6Added:
method update_value(s, z, Q, R)
Namespace types: KalmanState1D
Parameters:
s (KalmanState1D)
z (float)
Q (float)
R (float)
f_inverse_covariance3_diag(sigma, active_dims, variance_floor, determinant_floor)
Parameters:
sigma (matrix<float>)
active_dims (array<bool>)
variance_floor (float)
determinant_floor (float)
Phát hành các Ghi chú
v7Added:
f_sequential_update_metric(x, P_tri, z, H_row, R, n, use_lorentzian, bandwidth, max_r_multiplier)
Parameters:
x (array<float>)
P_tri (array<float>)
z (float)
H_row (array<float>)
R (float)
n (int)
use_lorentzian (bool)
bandwidth (float)
max_r_multiplier (float)
Thư viện Pine
Theo đúng tinh thần TradingView, tác giả đã công bố mã Pine này như một thư viện mã nguồn mở để các lập trình viên Pine khác trong cộng đồng có thể tái sử dụng. Chúc mừng tác giả! Bạn có thể sử dụng thư viện này cho mục đích cá nhân hoặc trong các ấn phẩm mã nguồn mở khác, nhưng việc tái sử dụng mã này trong các ấn phẩm phải tuân theo Nội Quy.
Thông báo miễn trừ trách nhiệm
Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.
Thư viện Pine
Theo đúng tinh thần TradingView, tác giả đã công bố mã Pine này như một thư viện mã nguồn mở để các lập trình viên Pine khác trong cộng đồng có thể tái sử dụng. Chúc mừng tác giả! Bạn có thể sử dụng thư viện này cho mục đích cá nhân hoặc trong các ấn phẩm mã nguồn mở khác, nhưng việc tái sử dụng mã này trong các ấn phẩm phải tuân theo Nội Quy.
Thông báo miễn trừ trách nhiệm
Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.