Closing market orders at 23:15

 

I want to close any outstanding market order at 23:15 every day. I am working with the following code, buy I am getting the error: 4108 (Invalid ticket.). I don't know what I am doing wrong.


  // Closing orders at end of day
 
   bool   result;
   double price;
   int    cmd,error;
 
if((TimeHour(TimeCurrent())==23) && (TimeMinute(TimeCurrent())==15))               //23:15
   {
   for (int i=1; i<=OrdersTotal(); i++)       .
     {                                        
      if(OrderSelect(i,SELECT_BY_TICKET)==true)
     {
      cmd=OrderType();
      //---- first order is buy or sell
      if(cmd==OP_BUYSTOP  || cmd==OP_SELLSTOP)
        {
         while(true)
           {
            if(cmd==OP_BUYSTOP) price=Bid;
            else            price=Ask;
            result=OrderClose(OrderTicket(),OrderLots(),price,3,Black);
            if(result!=TRUE) { error=GetLastError(); Print("LastError = ",error); }
            else error=0;
            if(error==135) RefreshRates();
            else break;
           }
        }
     }
     }        
   }


Also I don't understand why the OrderType() function gives the value of stop orders. I originally placed an OP_BUYSTOP or OP_SELLSTOP, that became an OP_BUY or OP_SELL if the stop price was reached, and I what I am trying to close is the market order. Is my logic ok? Or a Stop order still Stop even after it was triggered?


Thank you for your collaboration.



 
lococo:

I want to close any outstanding market order at 23:15 every day. I am working with the following code, buy I am getting the error: 4108 (Invalid ticket.). I don't know what I am doing wrong.



Also I don't understand why the OrderType() function gives the value of stop orders. I originally placed an OP_BUYSTOP or OP_SELLSTOP, that became an OP_BUY or OP_SELL if the stop price was reached, and I what I am trying to close is the market order. Is my logic ok? Or a Stop order still Stop even after it was triggered?


Thank you for your collaboration.






Try :


TotalOrders= OrdersTotal();
for (int i=1; i<=TotalOrders; i++)       .
     {                                        



 

1. Replace "SELECT_BY_TICKET" with "SELECT_BY_POS" as the routine does not know the ticket numbers of the orders.
2. Replace "for (int i=1; i<=OrdersTotal(); i++)" with "for(int i=OrdersTotal()-1; i>=0; i--)" when closing open orders or cancelling pending orders.
3. Use function OrderDelete() to cancel pending orders (OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP, OP_SELLSTOP) and OrderClose() to close open orders (OP_BUY, OP_SELL).

4. It is better to cater for "(TimeMinute(TimeCurrent())>=15))" as some Symbols/Instruments at that time are not very active.

Reason: