two_leg_spread_diff
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © voided

//@version=5
indicator("two_leg_spread_diff")

timeframe   = input.timeframe("30", "timeframe")
leg1_sym    = input.symbol("RB1!", "leg1_sym")
leg2_sym    = input.symbol("HO1!", "leg2_sym")
lag         = input.int(46, "lag")
anchor      = input.bool(title = "anchor_to_session_start", defval = false)

if anchor and timeframe.isintraday
    
    for i = 0 to 5000
        
        if time[i + 1] - time[i + 2] != time[i + 2] - time[i + 3]
            
            lag := i + 2
                
            break

leg1 = request.security(leg1_sym, timeframe, close)
leg2 = request.security(leg2_sym, timeframe, close)

leg1_log_return = math.log(leg1 / leg1[lag])
leg2_log_return = math.log(leg2 / leg2[lag])

diff = leg1_log_return - leg2_log_return

var diffs   = array.new_float()
var acc1    = array.new_int()
var acc2    = array.new_int()

array.push(diffs, diff)

diff_std    = array.stdev(diffs)

if diff <= diff_std and diff >= -diff_std

    array.push(acc1, 1)

else

    array.push(acc1, 0)

if diff <= 2 * diff_std and diff >= 2 * -diff_std

    array.push(acc2, 1)

else

    array.push(acc2, 0)

plot(diff, color = leg1_log_return > 0 and leg2_log_return < 0 ? color.blue : leg1_log_return < 0 and leg2_log_return > 0 ? color.red : color.gray)
plot(0, color = color.new(color.gray, 50))
plot(diff_std, color = color.new(color.blue, 90))
plot(2 * diff_std, color = color.new(color.red, 90))
plot(-diff_std, color = color.new(color.blue, 90))
plot(2 * -diff_std, color = color.new(color.red, 90))

if barstate.islast

    t = table.new(position.top_right, 2, 2)

    fmt = "#.##"

    table.cell(t, 0, 0, "acc 1")
    table.cell(t, 0, 1, "acc 2")

    table.cell(t, 1, 0, str.tostring(array.avg(acc1), fmt))
    table.cell(t, 1, 1, str.tostring(array.avg(acc2), fmt))