Read the article again and again bro. Especially this bit
[B]The Explanation[/B]
Let’s work through the code above . . . line by line, Order by Order . . .
Let’s assume we have the following Orders that we want to close, they all have the same magic number and Symbol as our EA so we want our code to close them all:
[TH=“bgcolor: #CACACA, align: center”]Position[/TH]
[TH=“bgcolor: #CACACA, align: center”]Ticket Number[/TH]
0
111
1
222
2
333
3
444
4
555
[U]1st run through the loop:[/U]
the initial value of PositionIndex is 0 so the order at position 0 is selected, ticket number 111, this order is successfully deleted and the remaining Orders change position as follows:
[TH=“bgcolor: #CACACA, align: center”]Position[/TH]
[TH=“bgcolor: #CACACA, align: center”]Ticket Number[/TH]
0
222
1
333
2
444
3
555
[U]2nd run through the loop:[/U]
now the value of PositionIndex is 1 so the order at position 1 is selected, ticket number 333, this order is successfully deleted and the remaining Orders change position as follows:
[TH=“bgcolor: #CACACA, align: center”]Position[/TH]
[TH=“bgcolor: #CACACA, align: center”]Ticket Number[/TH]
0
222
1
444
2
555
[U]3rd run through the loop:[/U]
now the value of PositionIndex is 2 so the order at position 2 is selected, ticket number 555, this order is successfully deleted and the remaining Orders change position as follows:
[TH=“bgcolor: #CACACA, align: center”]Position[/TH]
[TH=“bgcolor: #CACACA, align: center”]Ticket Number[/TH]
0
222
1
444
[U]4th run through the loop:[/U]
now the value of PositionIndex is 3 OrderSelect() tries to select the Order at position 3 and [B]fails[/B], the continue takes execution of the code to the next value in the loop . .
[U]
5th and last run through the loop:[/U]
now the value of PositionIndex is 4 OrderSelect() tries to select the Order at position 4 and [B]fails[/B], the continue takes execution of the code to the next value in the loop . . . the loop has finished.
We are now left with 2 Orders, tickets 222 and 444 which should have been closed but were not . . . next, how to resolve this issue.
It explains it far better than I will. When just working with orders the
PositionIndex++
is a valid format to loop through orders.
The problem arises when you start deleted/closing orders. Your code has a number of those functions, so the solution is to use
PositionIndex--