Kalman Gain Parameter Mechanics
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo

//@version=5
indicator('Kalman Gain Parameter Mechanics', '', true)

// Explanation of Gain parameter of Kalman function in HMA-Kalman & Trendlines script.
// To see better results set your Chart's timeframe to Daily.

//-- Inputs

ds    = input.source(close, 'Dataset')

g1    = input.bool(true,    'Kalman', inline='g1') 
g2    = input.bool(false,   'Kalman', inline='g2') 
g3    = input.bool(false,   'Kalman', inline='g3') 
g4    = input.bool(false,   'Kalman', inline='g4') 
g5    = input.bool(false,   'Kalman', inline='g5') 

gain1 = input.int(1,        'Gain1', 1, step=1, inline='g1') 
gain2 = input.int(10,       'Gain2', 1, step=1, inline='g2')
gain3 = input.int(100,      'Gain3', 1, step=1, inline='g3')
gain4 = input.int(1000,     'Gain4', 1, step=1, inline='g4')
gain5 = input.int(10000,    'Gain5', 1, step=1, inline='g5')

strat = input.bool(false, 'Show Strategy Code')

//-- Functions

kalman(x, g) =>
    gn = g/1000000  //-- smoothing magnitude adjustment
    kf = 0.0
    dk = x - nz(kf[1], x)
    smooth = nz(kf[1],x)+dk*math.sqrt(gn*2)  //-- serves as a smoothing factor
    velo = 0.0
    velo := nz(velo[1],0) + (gn*dk)
    kf := smooth+velo

//-- Logic

k1 = kalman(ds, gain1)
k2 = kalman(ds, gain2)
k3 = kalman(ds, gain3)
k4 = kalman(ds, gain4)
k5 = kalman(ds, gain5)

//-- Visuals

plot(g1 ? k1 : na, 'K1', color.orange)
plot(g2 ? k2 : na, 'K2', color.red)
plot(g3 ? k3 : na, 'K3', color.green)
plot(g4 ? k4 : na, 'K4', color.olive)
plot(g5 ? k5 : na, 'K5', color.gray)

//-- Strategy Logic

var int signal = 0
signal := ta.crossover(k4,k5) ? -1 : ta.crossunder(k4,k5) ? 1 : nz(signal[1])

changed = ta.change(signal)

long  = changed and signal== 1
short = changed and signal==-1

//-- Visuals

plot(strat? k4 : na, 'K4', color.olive, 2)
plot(strat? k5 : na, 'K5', color.gray,  2)

plotshape(strat and long ?low :na, '', shape.labelup,   location.belowbar, color.green, size=size.small)
plotshape(strat and short?high:na, '', shape.labeldown, location.abovebar, color.red,   size=size.small)
