Kalman Filter [by Hajixde]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hajixde

//@version=5
indicator("Kalman by Hajixde", overlay = true, timeframe = "")

findSlope(src, N) =>
    float I =  na
    float s = na
    n = N > 5000 ? 4999 : N
    M1 = 0.0
    M2 = 0.0
    M3 = 0.0
    M4 = 0.0
    M5 = 0.0
    M6 = 0.0
    MN = 0.0
    if n > 2
        for i = 0 to n-1
            M1 := M1 + src[i]
            M2 := M2 + bar_index[i]*bar_index[i]
            M3 := M3 + bar_index[i]
            M4 := M4 + bar_index[i]*src[i]
            M5 := M5 + src[i]    
        s := (n*M4 - M3*M1) / (n*M2 - M3*M3)
        I := (M1 - s*M3) / (n)
    [s, I]


src = input.source(close, "Source")
n1=input.int(100, title = "Model length", minval = 2)
kf_gain1 = input.float(0.3, title = "Kalman gain", step = 0.05, minval = 0, maxval = 1) 
n2=input.int(250, title = "Model length", minval = 2)
kf_gain2 = input.float(0.1, title = "Kalman gain", step = 0.05, minval = 0, maxval = 1) 
lnCol1 = input.color(color.yellow, title = "Color")
lnCol2 = input.color(color.aqua, title = "Color")

float EST1 = 0.0
float EST2 = 0.0


[s1, I1] = findSlope(src, n1)
[s2, I2] = findSlope(src, n2)

E1 = na(EST1[1]) ? 0.0 : EST1[1]
E2 = na(EST2[1]) ? 0.0 : EST2[1]
error1 = src - E1
error2 = src - E2

EST1 := s1*(bar_index) + I1 + error1*kf_gain1
EST2 := s2*(bar_index) + I2 + error2*kf_gain2

plot(EST1 , offset = 1, color = lnCol1, title = "Kalman Fitting Curve 1")
plot(EST2 , offset = 1, color = lnCol2, title = "Kalman Fitting Curve 2")
