closing all orders on a Open Bar based ea

 

Hi,

I wrote an intraday ea for M1 timeframe based on Open so the start function begins like this:  

int start()                                  

{
     static int lastBars;
  bool status = false;

  if( lastBars != Bars )
    {
        status = true;
        lastBars = Bars;
    }
  

if (status == true )
  {  

 To remain intraday  I need to add a loop within the start function to close all orders at 21h59 just before market close

  for (m=0; m<OrdersTotal(); m++)
    {
    if (OrderSelect(m, SELECT_BY_POS, MODE_TRADES) )  
      {  
      if (OrderMagicNumber() == MagicNumber )
        {
         if (OrderType() == OP_BUY) price= MarketInfo(OrderSymbol(), MODE_BID); else price= MarketInfo(OrderSymbol(), MODE_ASK);
         if (TimeHour(TimeCurrent()) == 21 && TimeMinute(TimeCurrent())==59) OrderClose(OrderTicket(),OrderLots(),price,0,0); // fermeture des positions
        }
      }
    }

 

 The problem I face is that some open trades don't close at 21h59 when I run a backtesting; some do but for some reason other open orders remain alive overnight.

This only happens when I use  the specific beginning of the start function to trade on Open only.

 

Any idea what I'm doing wrong there ?

 

Thanks 

 
marsupilami:
...

Any idea what I'm doing wrong there ?

 

Thanks 

  • Place your time checking OUTSIDE the loop.
  • Always count down if you want to close (delete) orders.
  • Always check the return value of a trading function...
if(TimeHour(TimeCurrent())==21 && TimeMinute(TimeCurrent())==59)
  {
   for(m=OrdersTotal()-1; m>=0; m--)
     {
      if(OrderSelect(m,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderMagicNumber()==MagicNumber)
           {
            if(OrderType()==OP_BUY) price=MarketInfo(OrderSymbol(),MODE_BID); else price=MarketInfo(OrderSymbol(),MODE_ASK);
            if(!OrderClose(OrderTicket(),OrderLots(),price,0,0)) // fermeture des positions
            {
            // What do you want to do if the close fails ?
            }
           }
        }
     }
  }
 
Alain Verleyen:
  • Place your time checking OUTSIDE the loop.
  • Always count down if you want to close (delete) orders.
  • Always check the return value of a trading function...
if(TimeHour(TimeCurrent())==21 && TimeMinute(TimeCurrent())==59)
  {
   for(m=OrdersTotal()-1; m>=0; m--)
     {
      if(OrderSelect(m,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderMagicNumber()==MagicNumber)
           {
            if(OrderType()==OP_BUY) price=MarketInfo(OrderSymbol(),MODE_BID); else price=MarketInfo(OrderSymbol(),MODE_ASK);
            if(!OrderClose(OrderTicket(),OrderLots(),price,0,0)) // fermeture des positions
            {
            // What do you want to do if the close fails ?
            }
           }
        }
     }
  }
Thank you very much !
Reason: