Looping for highest order misses sometimes order information

 

Hi, having problem with loop, when part of main order is closed, loop misses to find existing order information and by believing there is no order code shoots to open new order.

Code should find highest Buy order and remove part of the profit.

Overall is there a better/safer way to code loops. I am constantly finding my self in trouble where my loops are actiong like some ghost is pushing the switches when looping for order information.



//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
int SELLMAGIC=111,BUYMAGIC=222;
void OnTick()
  {
   int      HiOpnB_Tic=0,Tot=0;
   double   HiOpnB_Lot=0,HiOpnB_Prof=0,HiOpnB_Swap=0,HiOpnB_Commi=0,HiOpnB_Max=0,HiOpnB_Opn=0;
   for(int i4=OrdersTotal()-1;i4>=0;i4--)
   {
      if(OrderSelect(i4,SELECT_BY_POS,MODE_TRADES)==false) break;
         if(OrderSymbol()!=Symbol() 
         && OrderMagicNumber()!=SELLMAGIC) continue;
            if(OrderType()==OP_BUY && OrderComment()=="BUY")         
            {
               if(OrderOpenPrice()>HiOpnB_Max)
               {
                  HiOpnB_Max=OrderOpenPrice();
                  HiOpnB_Opn=OrderOpenPrice();
                  HiOpnB_Lot=OrderLots();
                  HiOpnB_Tic=OrderTicket();
                  HiOpnB_Prof=OrderProfit();
                  HiOpnB_Swap=OrderSwap();
                  HiOpnB_Commi=OrderCommission();
                  Tot++;
               }
            }
   }
   int ticket=0;
   if(Tot==0)
   {
      ticket=OrderSend(Symbol(),OP_BUY,1.00,Ask,10,0,0,"BUY",BUYMAGIC,0,clrNONE);
      
   }
   int Pips=10;
   if(Digits==3 || Digits==5)
   {
      Pips=10*10;
   }
   if(Bid>=HiOpnB_Opn+Pips*Point)
   {
      ticket=OrderClose(HiOpnB_Tic,0.10,Bid,10,clrNONE);
   }
   Comment("\nTotal: "+IntegerToString(Tot,0,' '));
  }
//+------------------------------------------------------------------+
Reason: