Condition for open the order when the order close

 

Hello everyone, i need a help

Sometimes i close orders whole and sometimes i close orders partial. Can anyone to give the condition for the below code because it open a bulk orders against the close order.


void OpenClosedOrders()
 {
 
 for( int i=OrdersHistoryTotal()-1;i>=0;i--){
  ticket=OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
  double open=OrderOpenPrice();
  double open_b=Ask+(Distance)*Point;
  double open_s=Bid-(Distance)*Point;
  double lott=OrderLots();
  int type=OrderType();

  if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MAGICMA){
   {
   if(type==OP_BUY){
  
    if(Ask>open+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point){
     ticket=OrderSend(Symbol(),OP_BUY,lott,Ask,3,0,0,"",MAGICMA,0,Green);}
   
    if(Ask<open-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point){
     ticket=OrderSend(Symbol(),OP_BUYSTOP,lott,open_b,3,0,0,"",MAGICMA,0,Green);}
     
   }
   if(type==OP_SELL){
  
   if(Bid>open+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point){
     ticket=OrderSend(Symbol(),OP_SELLSTOP,lott,open_s,3,0,0,"",MAGICMA,0,Green);}
   
    if(Bid<open-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point){
     ticket=OrderSend(Symbol(),OP_SELL,lott,Bid,3,0,0,"",MAGICMA,0,Green);}
    
     }
    }
   }
  }
 }

Files:
 
Trade Functions

For a start, sort it out

Reason: