Search code examples
pine-scriptpine-script-v5

Error: Index is out of bound in array.get function


I am trying to find the regression line with the largest value using a loop. The regression line is calculated over several periods and then the period i with the highest value is to be output so that it can be used in the further calculation. For example, if the regression line of the last 15 days is the highest, then 15 should be output.

To find the corresponding regression line, I work with the array functions

I always get Runtime error:Error on bar 0: In 'array.get()' function. Index -1 is out of bounds, array size is 11.

The error always refers to the last line in the code shown below

src = input.source(title="Source", defval=close)
min_length = input.int(10, "Min. length", minval=1)
max_length = input.int(20, "Max. length", minval=1)
step = input.int(1, "Step", minval=1)

regression = array.new_float()
indices = array.new_int()


for i = min_length to max_length by step
    length = i
    x = bar_index
    y = close
    x_ = ta.sma(x,length)
    y_ = ta.sma(y,length)
    mx = ta.stdev(x,length)
    my = ta.stdev(y,length)
    c = ta.correlation(x,y,length)
    slope = c * (my/mx)
    //
    inter = y_ - slope*x_
    //
    reg = x*slope + inter

    regline = reg
    
    array.push(indices, i)
    array.push(regression, regline) 





// find maximum value
max_val = array.max(regression)
max_idx = array.indexof(regression, max_val)
max_len = array.get(indices, max_idx)

How can I solve the problem so that I get the corresponding period output? If I start the loop at 0 and go to max_length-1, I may have a result outside the desired range min-length to max_length.


Solution

  • Well, you are using array.indexof() to get the index of a value. If this value does not exist in the array, then array.indexof() will return -1 - which is what causing your issue.

    To avoid this, you can use an if check.

    max_idx = array.indexof(regression, max_val)
    int max_len = na
    
    if (max_idx != -1)
        max_len  := array.get(indices, max_idx)