two_leg_spread_returns_zscore
// 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_returns_zscore")

timeframe   = input.timeframe("5", "timeframe")
leg1_sym    = input.symbol("RB1!", "leg1_sym")
leg2_sym    = input.symbol("HO1!", "leg2_sym")
ma_length   = input.int(48, "ma_length")

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

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

var leg1_returns = array.new_float()
var leg2_returns = array.new_float()

array.push(leg1_returns, leg1_log_return)
array.push(leg2_returns, leg2_log_return)

leg1_zscore = (leg1_log_return - array.avg(leg1_returns)) / array.stdev(leg1_returns)
leg2_zscore = (leg2_log_return - array.avg(leg2_returns)) / array.stdev(leg2_returns)

diff = ta.ema(leg1_zscore - leg2_zscore, ma_length)

bgcolor(leg1_zscore > 0 and leg2_zscore < 0 ? color.new(color.blue, 95) : leg1_zscore < 0 and leg2_zscore > 0 ? color.new(color.orange, 95) : color.new(color.white, 100))

plot(leg1_zscore, style = plot.style_histogram, color = color.new(color.blue, 50))
plot(leg2_zscore, style = plot.style_histogram, color = color.new(color.orange, 50))
plot(0, color = color.new(color.gray, 50))
plot(diff, color = diff > 0 ? color.blue : diff < 0 ? color.orange : color.gray)