Code for releasing orders

 

Hi, 

I am trying to code a way to release orders, but it is not working. Does anybody know the logic?

//+------------------------------------------------------------------+
//| Profit loop                                                      |
//+------------------------------------------------------------------+
void CloseLoopProfit(int ot=-1)
  {
      double opr=0;
      for(int i=2; i>0; i--)
        {
         for(int x=OrdersTotal()-1; x>=N_O; i--)
           {
            if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
              {
               if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
                 {
                  if(OrderType()==0 && (ot==0 || ot==-1))
                    {
                     opr+=OrderProfit()+OrderCommission()+OrderSwap();
                    }

                  if(OrderType()==1 && (ot==1 || ot==-1))
                    {
                     opr+=OrderProfit()+OrderCommission()+OrderSwap();
                    }
                 }
              }
           }
        }

      if(opr>0)
        {
         bool cl;
         for(int i=2; i>0; i--)
           {
            for(int x=OrdersTotal()-1; x>=N_O; x--)
              {
               if(OrderSelect(i,SELECT_BY_TICKET,MODE_TRADES))
                 {
                  if(OrderType()==0 && (ot==0 || ot==-1))
                    {
                     //RefreshRates();
                     cl=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,_Digits),Slip,White);
                    }
                  if(OrderType()==1 && (ot==1 || ot==-1))
                    {
                     //RefreshRates();
                     cl=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,_Digits),Slip,White);
                    }
                 }
              }
           }
        }
     }
 
OrdersTotal - 1 is not a ticket number.
 
I know the code is wrong. It is a bunch of copy paste. Sorry for that. I will keep trying to find the logic. 
Reason: