How to cancel and delete pending orders in MQL5?

Can anyone help me with the code to cancel pending orders once there are no trades in the opposite direction open?

read here, deleting pending orders

thanks for your comment.
the EA I am working on is quite complex could I modify these functions to close opposite pending orders?

//+------------------------------------------------------------------+

//|      exit sells   breakout trades                                                         |

//+------------------------------------------------------------------+

void exitsells()

  {

   int total=OrdersTotal()-1;

   for(int i=total; i>=0; i--)

     {

      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

        {

         if(OrderMagicNumber()==magic)

            if(OrderType()==OP_SELLSTOP)

              {

               int attempts=1;

               while(attempts<=5)

                 {

                  int err=0;

                  bool result=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);

                  if(result)break;

                  else

                    {

                     err=GetLastError();

                     Print("LastError = ",ErrorDescription(err));

                     if(err==4108) break;// ticket not valid. break out of while loop

                     switch(err)

                       {

                        case 135: //price change.

                        case 136: //off Quotes.

                        case 137: //Broker Busy

                        case 138: // Requote

                        case 146: // Trade Context Busy

                           Sleep(1000);

                           RefreshRates();//will do these things if any of these things are the case

                        default:break;//break out of switch

                       }//end of switch

                    }//else                 

                  attempts++;

                  if(attempts==6)

                     Print("Could not close trades after 5 attempts.",ErrorDescription(err));

                 }//end of while loop

              }//op sell

        }//orderselect

      else Print("When selecting a trade, error ",GetLastError()," occurred");//order select return get last error

     }//for



  }

  //+------------------------------------------------------------------+

//|      exit buys  breakout trade                                                          |

//+------------------------------------------------------------------+

void exitbuys()

  {

   int total= OrdersTotal()-1;

   for(int i=total; i>=0; i--)

     {

      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

        {

         if(OrderMagicNumber()==magic)

            if(OrderType()==OP_BUYSTOP)

              {

               int attempts=1;

               while(attempts<=5)

                 {

                  int err=0;

                  bool result=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Red);

                  if(result)break;

                  else

                    {

                     err=GetLastError();

                     Print("LastError = ",ErrorDescription(err));

                     if(err==4108) break;// ticket not valid. break out of while loop

                     switch(err)

                       {

                        case 135: //price change.

                        case 136: //off Quotes.

                        case 137: //Broker Busy

                        case 138: // Requote

                        case 146: // Trade Context Busy

                           Sleep(1000);

                           RefreshRates();//will do these things if any of these things are the case

                        default:break;//break out of switch

                       }//end of switch

                    }//else

                  attempts++;

                  if(attempts==6)

                     Print("Could not close trades after 5 attempts.",ErrorDescription(err));

                 }//end of while loop

              }//op buy

        }//orderselect

      else Print("When selecting a trade, error ",GetLastError()," occurred");//order select return get last error

     }//for



  }

What about something like this?

bool exit(int direction)
{
   RefreshRates();
   for(int i=0; OrderSelect(i, SELECT_BY_POS); i++)
      if(OrderType() == direction)
         if(OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 100, clrRed))
            return exit(direction);
         else
            return false;
   for(int i=0; OrderSelect(i, SELECT_BY_POS); i++){
      int type = OrderType();
      if((direction == OP_BUY && (type == OP_SELLLIMIT || type == OP_SELLSTOP))
         || (direction == OP_SELL && (type == OP_BUYLIMIT || type == OP_BUYSTOP))
      ){
         if(OrderDelete(OrderTicket(), clrRed))
            return exit(direction);
         else 
            return false;
      }
   }
   return true;
}

Thanks ill give it a try.

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   for(int i=100;i>0;i--)
     {
      Comment(i);
     }
 CheckForSignal();
 if(UseTrailingStop)AdjustTrail();
   if(UseMoveToBE)MovetoBreakeven();
   
 
           
   
            
         
       
   
  
}
  
//+------------------------------------------------------------------+
//|       TRIGGER FUNCTION pull back STRATEGY                       |
//+------------------------------------------------------------------+
void CheckForSignal()
  {
   static datetime candletime=0;
   if(candletime!=Time[0])
     {
      double currenttrendMa30=iMA(NULL,0,50,0,1,0,1);
      double trendMa200=iMA(NULL,0,200,0,1,0,1);
      double currentMACD=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
      double previouspreviousMACD=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,3);
      double previousMACD=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,2);
      double currentupper = iBands(NULL,0,20,2,0,0,1,0);
      double currentlower = iBands(NULL,0,20,2,0,0,2,0);
      

      //SELL signal
      

      if(currentMACD < previousMACD && previousMACD > previouspreviousMACD && currentMACD > Threshold*pips)
       

        if(TotalOpenSellOrders())
         {
        
            
              
              
          if(Bid - HighestSellPosition() >= TradeSpacing*pips)
            
         EnterTrade(OP_SELL);
      }
      else EnterTrade(OP_SELL);
     if(TotalPendingBuyOrders()<1) 
      {
         EnterTrade2(OP_BUYSTOP);  exit(OP_SELLSTOP) ;
         }
         

       
        
      //BUY signal 
     
      
      if(currentMACD > previousMACD && previousMACD < previouspreviousMACD && currentMACD < -Threshold*pips)
       
      
      if(TotalOpenBuyOrders())
      {
       
        
        if(LowestBuyPosition()-Ask >= TradeSpacing*pips)
               
                  EnterTrade(OP_BUY);
         }
         else EnterTrade(OP_BUY);
        if(TotalPendingSellOrders()<1)
         {
            EnterTrade2(OP_SELLSTOP);exit(OP_BUYSTOP);
         }
         
      candletime=Time[0];
     }
  }

//+------------------------------------------------------------------+
//|     TRADE PLACING FUNCTION                                                             |
//+------------------------------------------------------------------+
void EnterTrade(int type){

   int err=0;
   double price=Bid,
          sl=0, 
          tp=0,
          lotsize = 0;
          
           
          {
          
          if(TotalOpenBuyOrders()==3) lotsize = (TotalOpenBuyOrders()+SmartinggaleAmount)*Lotsize;
           else lotsize = (TotalOpenSellOrders()+SmartinggaleAmount)* Lotsize;
            
           }
   if(type == OP_BUY)
   {
   if (TotalOpenSellOrders()==3)  lotsize = (TotalOpenSellOrders()+SmartinggaleAmount)*Lotsize;
           
             else lotsize = (TotalOpenBuyOrders()+SmartinggaleAmount)*Lotsize;
             }
             {
      price =Ask;
   }
   
   //----
   int ticket =  OrderSend(Symbol(),type,lotsize,price,30,0,0,"EaTemplate",magic,0,Magenta); 
   if(ticket>0)
   {
      if(OrderSelect(ticket,SELECT_BY_TICKET))
      {
         if(OrderType() == OP_SELL)
         {
         
           sl = OrderOpenPrice()+(StopLoss*pips);
            if(StopLoss==0)sl=0;
           tp = BreakevenOfSells()-(TakeProfit*pips);
         }
         else if(OrderType()==OP_BUY)
         {
         
          sl = OrderOpenPrice()-(StopLoss*pips);
            if(StopLoss==0)sl=0;
            tp = BreakevenOfBuys()+(TakeProfit*pips);
         }
         //---Modify This Order
         if(!OrderModify(ticket,price,sl,tp,0,Magenta)) 
         {
            err = GetLastError();
            Print("Encountered an error during modification!"+(string)err+" "+ErrorDescription(err)  );
         }
         //---Modify The Other Orders that are Open.
         if(TotalOpenOrders() > 1)         
         {
            for(int i=0;i<OrdersTotal()-1;i++)
            {
               if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
                  if(OrderMagicNumber()==magic)
                     if(OrderType()==type)
                        if(!OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),tp,0,clrMagenta))                              
                        {
                           err = GetLastError();
                           Print("Encountered an error during modification!"+(string)err+" "+ErrorDescription(err)  );
                        }
            }
         }
         
         
      }
      else
      {//in case it fails to select the order for some reason 
         Print(__FUNCTION__,"Failed to Select Order ",ticket);
         err = GetLastError();
         Print("Encountered an error while seleting order "+(string)ticket+" error number "+(string)err+" "+ErrorDescription(err)  );
      }
   }
   else
   {//in case it fails to place the order and send us back a ticket number.
      err = GetLastError();
      Print("Encountered an error during order placement!"+(string)err+" "+ErrorDescription(err)  );
      if(err==ERR_TRADE_NOT_ALLOWED)MessageBox("You can not place a trade because \"Allow Live Trading\" is not checked in your options. Please check the \"Allow Live Trading\" Box!","Check Your Settings!");
   }
}
  //+------------------------------------------------------------------+
//|     TRADE2 PLACING FUNCTION                                                             |
//+------------------------------------------------------------------+
void EnterTrade2(int type){

   int err=0;
   double price=Bid-25*pips,
          sl=0, 
          tp=0,
          lotsize = (TotalOpenBuyOrders()+1) * Lotsize;
   if(type == OP_BUYSTOP)
   {
      lotsize = (TotalOpenSellOrders()+1) * Lotsize;
      price =Ask+25*pips;
   }
      
   //----
   int ticket =  OrderSend(Symbol(),type,lotsize,price,30,0,0,"trapper Trade",magic,0,Magenta); 
   if(ticket>0){
      if(OrderSelect(ticket,SELECT_BY_TICKET)){
         sl = OrderOpenPrice()+(StopLoss2*pips);
         if(StopLoss2==0)sl=0;
         tp = OrderOpenPrice()-(TakeProfit2*pips);
         if(OrderType()==OP_BUYSTOP){
            sl = OrderOpenPrice()-(StopLoss2*pips);
            if(StopLoss2==0)sl=0;
            tp = OrderOpenPrice()+(TakeProfit2*pips);
         }
         if(!OrderModify(ticket,price,sl,tp,0,Magenta)) {
            err = GetLastError();
            Print("Encountered an error during modification!"+(string)err+" "+ErrorDescription(err)  );
         }
      }
      else{//in case it fails to select the order for some reason 
         Print("Failed to Select Order ",ticket);
         err = GetLastError();
         Print("Encountered an error while seleting order "+(string)ticket+" error number "+(string)err+" "+ErrorDescription(err)  );
      }
   }
   else{//in case it fails to place the order and send us back a ticket number.
      err = GetLastError();
      Print("Encountered an error during order placement!"+(string)err+" "+ErrorDescription(err)  );
      if(err==ERR_TRADE_NOT_ALLOWED)MessageBox("You can not place a trade because \"Allow Live Trading\" is not checked in your options. Please check the \"Allow Live Trading\" Box!","Check Your Settings!");
   }
}

//+------------------------------------------------------------------+
//| delete pending order function                                    |
//+------------------------------------------------------------------+
bool exit(int direction)
{
   RefreshRates();
   for(int i=0; OrderSelect(i, SELECT_BY_POS); i++)
      if(OrderType() == direction)
         if(OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 100, clrRed))
            return exit(direction);
         else
            return false;
   for(int i=0; OrderSelect(i, SELECT_BY_POS); i++){
      int type = OrderType();
      if((direction == OP_BUY && (type == OP_SELLLIMIT || type == OP_SELLSTOP))
         || (direction == OP_SELL && (type == OP_BUYLIMIT || type == OP_BUYSTOP))
      ){
         if(OrderDelete(OrderTicket(), clrRed))
            return exit(direction);
         else 
            return false;
      }
   }
   return true;
}

Thanks for you suggestions. here is the EA I am still having trouble closing the Pending orders once one in the opposite direction is opened. the signal code seems to be ok the problem I think is with the exit(); function at the end of the EA. IT GIVES ERROR CODE 4108 in the journal ERR_INVALID_TICKET