Reputation: 27
The goal is to quickly identify the worst performing path and the worst performing loss. The challenge I am experiencing is that after I initialize the variable with a var
, the array.get()
function is no longer able to retrieve the value inside the array. All I received is the error message Index -1 is out of bounds, array size is 0
. In the example below, I am able to successfully create two arrays, one that includes all the loss path names, and the other that includes all the loss %. In the ideal scenario, I would like to plot the worst performing path name in the first table cell in the right hand corner, that is corresponding to the worst performing loss (working) in the second table cell. Any advices?
var lossPath = array.new_string(0)
var lossPercent = array.new_float(0)
if (change(entryPrice) and color_WINLOSS == color.new(color.red, 0))
array.push(lossPath, path[1])
percent = isLong ? (entryPrice[0] - entryPrice[1]) / entryPrice[1] * 100 : isShort ? -(entryPrice[0] - entryPrice[1]) / entryPrice[1] * 100 : na
array.push(lossPercent, percent)
if barstate.islast
label.new(bar_index, high, "Loss Path: " + tostring(lossPath) + "\nLoss Percent: " + tostring(lossPercent) + "\nArray Size: " + tostring(array.size(lossPath)), style=label.style_label_down)
worstPathIndex = array.indexof(lossPercent, array.min(lossPercent))
worstPathName = tostring(array.get(lossPath, min(worstPathIndex, array.size(lossPath) - 1)))
// plot(array.get(lossPercent, 0)) // Similarity this plot doesn't work either
worstLoss = tostring(array.min(lossPercent), format.percent)
Upvotes: 0
Views: 3507
Reputation: 1
Here's what you need to ensure to avoid this error:
When accessing the last element of an array, you must check if the array is empty. If it's not, then you can safely access the last element using array.size() - 1.
When removing the last element, you must perform the same check to ensure the array isn't empty before trying to remove an element.
Avoid using array indexing when you're not sure whether the array has elements in it. Always guard array access with size checks.
Upvotes: 0
Reputation: 3823
It is happening because on this line :
worstPathName := tostring(array.get(lossPath, min(worstPathIndex, array.size(lossPath) - 1)))
on the first bar the lossPath
array is empty, containing zero elements. So array.size
will return zero, resulting in array.get
trying to access the index "0 minus 1".
If you perform a check first to determine if the array is empty before this, you can prevent the error.
string worstPathName = na
if array.size(lossPath) > 0
worstPathName := tostring(array.get(lossPath, min(worstPathIndex, array.size(lossPath) - 1)))
Upvotes: 1