delete pending orders

 

can someone help me please? I can get this function to delete a pending order. What am i doing wrong? the way I would like it to work is when a open order is closed. this function will then delete the pending order. I keep getting the error 4108 for invalid ticket. I really have issue if another order is opened. then the function tries to delete the open order. Need help. Thank you

void CloseBuyStack1stLevelLimitOrder1M()
{
for(int b= OrdersTotal()-1; b >= 0; b--)
   {
   if(OrderSelect(b,SELECT_BY_TICKET,MODE_TRADES))
     if(OrderMagicNumber() == Stack1stLevelMagicNumber1M)
        if(OrderSymbol() == Symbol())
             if(OrderType()==OP_BUYLIMIT)
                if(CheckOrderOpenBuy1M () == false)
                     OrderDelete(OrderTicket(),clrNONE);
                    
   }


} 

 
   if(OrderSelect(b,SELECT_BY_TICKET,MODE_TRADES))
Select by position