Why does this Variable Reassignment give n/a?

Solution 1:

Not all instruments have the same history length. When a value is not available, n/a is returned. Any calculation with an n/a value results in n/a. You can account for this by using the nz() function, which replaces NaN values with zeros (or given value) in a series.

This will work

//@version=5
indicator("Variable Reassignment Error")

var float diff_c_sum = 0.0
var float diff_t_sum = 0.0
BTC = request.security("COINBASE:BTCUSD", "", close)
ETH = request.security("COINBASE:ETHUSD", "", close)
US02Y = request.security("TVC:US02Y", "", close)
US10Y = request.security("TVC:US10Y", "", close)

diff_c = nz(BTC - ETH, 0) // this works
diff_t = nz(US10Y - US02Y, 0) // this works

diff_c_sum := diff_c_sum + diff_c // this does not work, outputs "n/a", WHY?
//diff_c_sum := diff_c_sum + -0.01 // but this works
diff_t_sum := diff_t_sum + diff_t // this works

plotchar(diff_c_sum, 'diff_c_sum', '', location.top)
plotchar(diff_t_sum, 'diff_t_sum', '', location.top)
plotchar(diff_c, 'diff_c', '', location.top)
plotchar(diff_t, 'diff_t', '', location.top)

The reason why diff_c_sum := diff_c_sum + -0.01 worked is because it doesn't include diff_c which contained an n/a value.

Tip: You don't need to plot a variable to 'debug' it's value. You can use plotchar() for that, to have it show up in the data window. That's described in Debugging > When the script’s scale must be preserved.