I'm writing a script that compares the evolution of % difference between two symbols but I can't figure out why it gets the calculation wrong.
Here is the script :
//@version=4
study(title="Compare", shorttitle="Compare")
rocPeriod = input(1, minval = 1)
Max = input(defval = 5, type = input.float)
Min = input(defval = -5, type = input.float)
showLines = input(true)
showDelta = input(true)
sym1 = input(defval = "BINANCE:BTCUSDT", type = input.symbol)
sym2 = input(defval = "BINANCE:ETHUSDT", type = input.symbol)
perc_change = roc(close, rocPeriod)
res = ""
s1 = security(sym1, res, perc_change)
s2 = security(sym2, res, perc_change)
delta = s1 - s2
var float cumulativeDelta = 0.0
if barstate.isfirst
cumulativeDelta == delta
else
cumulativeDelta := cumulativeDelta + delta
plot(showLines ? s1 : na, "s1", color.orange)
plot(showLines ? s2 : na, "s2", color.blue)
hline(0)
plot(showDelta ? delta : na, "delta", delta > 0 ? color.lime : color.red, 1, plot.style_columns)
plot(cumulativeDelta, title = "CD", color= color.fuchsia)
bgcolor(cumulativeDelta >= Max ? color.red : na, transp=50)
bgcolor(cumulativeDelta <= Min ? color.green : na, transp=50)
At first, things work very well and the script identifies the first bar and sets the value "cumulativeDelta" = "delta" then performs its first calculations correctly. However, after a few bars, the result of "cumulativeDelta" starts to be slightly wrong (example: 0.31 + 0.20 = 0.52) and then, as the bars follow one another, the discrepancy only becomes more pronounced until it causes major differences between the final result and reality.
Where's the error? Thanks in advance for your help