Code fetches wrong Order ID

 
Hi , my code bellow fetches information of a wrong Order ID. What happens is when I have a pending order open for order ID 1 for OP_BUYSTOP for example and then afterwards another pending order for order ID 1 for OP_SELLSTOP opens and i want information for the sell stop , i get information for the but stop. The buy stop is the blue line and the sell stop is the red line on the picture bellow
bool KTDeleteAfterTwentyBarsSellKT()
{ 
    bool exists = false;
    for (int i=OrdersTotal()-1; i >= 0; i--)
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
        if (OrderType() == OP_SELLSTOP && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)
        {
            exists = true;
        }
    }
    else
    {
        Print("OrderSelect() error - ", ErrorDescription(GetLastError()));
    }
    
    if (exists)
    {    int      iBar     = iBarShift(Symbol(),0,OrderOpenTime())+1;
        Print("Index of the bar for the time ",TimeToStr(OrderOpenTime(),TIME_DATE|TIME_SECONDS)," is ",iBar);
        
       {  
      if ( iBar>=20 )
     {return(true);}
     }
     
    }
}
Image
 

You set exists=true when you find it, but then you keep selecting other orders. Once you exit the loop, you don't know which order is selected.

Drop the exists variable and put the code in the loop.

 
what do you mean I keep selecting other orders that i dont know after i have exited the loop but yet I have specified the exact type of order that I want to select
 

What WHRoeder is saying is that you continue looping through orders after finding the order that you are looking for. So you are printing details of the last order selected, not necessarily the one that you want.

        if (OrderType() == OP_SELLSTOP && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)
        {
            exists = true;
            break;
        }

 You could exit the loop after finding the trade.

 
GumRai:

What WHRoeder is saying is that you continue looping through orders after finding the order that you are looking for. So you are printing details of the last order selected, not necessarily the one that you want.

 You could exit the loop after finding the trade.

Thanks. Its working now
Reason: