Not got to a definitive answer but, I think the reason for the error, and what caused it are now clear.
However, the exact path taken to the error is still undefined.
#numbers/var refer to line numbers in your original code posted.
#Vopt When variable A3 = 15
#5 CountBars = A3, and then
#27 shift = CountBars-11-1 which equates to 3, giving a shift range of 0,1,2,3.
#29 main IF block is true when barindex is greater than Countbars
#30 main While loop, loops, shift value and, exit condition true when shift smaller than zero
#123 decrementing of shift by -1, end up at shift = -1, which breaks the loop.
Additionally…
#Vopt A2 = 1.5
#4 Risk = A2
#Vopt A23 = 77
#Vopt A24 = 15
#23 X1 = A23 + Risk which equates to 78.5, upper level threshold
#24 X2 = A24 – Risk which equates to 13.5, lower level threshold
#79 calculates the value of Value2 and then
#80 store Value2 in array, both related to shift value
#85 tests if current value of Value2 is smaller than the lower level threshold of X2, if it is….
#86 the value of i1 is set to one.
#87 The while loop, looks back and test if, pointed to, array value, of Value2, condition falls in between the upper and lower threshold levels.
So, current bar is below X2, #85, lookback searching for last time above X2 #87.
Now here is where I think the error comes in…
i1 is set to 1 #86 , so the look back starts at previous bar to shift , shift+1.
On the first run of main while, shift = 3, and that is the index value used to store arrays, then
adding 1 to shift points to an undefined element ‘4’ and hence error as loop commences.
Now pre-defining arrays to avoid this error means that the default value of these extra elements hold the value of zero.
When checking for the last inside of range, a value of zero, means that may not happen, because all higher elements are 0 and depending on situation at the time.
It’s possible that, if shift = 0, when all this happens, then condition for inside threshold area may be met before i1 increments to a value which results in accessing the undefined element. So not a total failure.
The original code had CountBars = 500, this would have resulted in a shift range of 0 – 488.
In the while loop, looking back would have a lot of elements defined. This avoiding error or at least pushes to an edge case where if, value2 stayed below or above the threshold levels that long and other factors allowed access beyond defined array element could happen.
I suppose the number of consecutive bars, above or below the threshold levels, in that process, is the cut off point.
And depending on timeframe used, the amount of these bars are going to be more or less.
Therefore A3 needs increasing to a value that avoids this array look back error situation.