EA opens two positions at the same milisecond

 

Hello,

I am using the following function within my EA to only open trades at the start of a new bar if the entry criteria are met.

//+------------------------------------------------------------------+
bool new_bar(ENUM_TIMEFRAMES timeframe)
  {
//--- memorize the time of opening of the last bar in the static variable
   static datetime last_time=0;
//--- current time
   datetime lastbar_time= (datetime)SeriesInfoInteger(Symbol(),timeframe,SERIES_LASTBAR_DATE);

//--- if it is the first call of the function
   if(last_time==0)
     {
      //--- set the time and exit
      last_time=lastbar_time;
      return(false);
     }

//--- if the time differs
   if(last_time!=lastbar_time)
     {
      //--- memorize the time and return true
      last_time=lastbar_time;
      return(true);
     }
//--- if we passed to this line, then the bar is not new; return false
   return(false);
  }
  

This is used with the following logic:

if(OrdersTotal() == 0 && new_bar(PERIOD_H1) && entry_criteria == true)
{
 OPEN TRADE
}

Because I am running the EA on a few different charts, there have been instances where on the start of a new bar, the EA has opened a position on two different Symbols, bypassing the orders total condition. 

What could I implement to avoid this happening?

 

Set a flag. PositionsTotal() can be out of sync.

[edit] You are using OrdersTotal(), it is for orders not positions.

 
Benjamin David Hardman:

Hello,

I am using the following function within my EA to only open trades at the start of a new bar if the entry criteria are met.

This is used with the following logic:

Because I am running the EA on a few different charts, there have been instances where on the start of a new bar, the EA has opened a position on two different Symbols, bypassing the orders total condition. 

What could I implement to avoid this happening?

Not sure if I understand your requirement, but could it be you need to check positions also?

if(OrdersTotal() == 0 && PositionsTotal() == 0  && new_bar(PERIOD_H1) && entry_criteria == true)
{
 OPEN TRADE
}


If you are doing this across different charts and you are trying to limit the transactions for the current symbol, you may need to scan the positions and orders and count how many exist for your current _Symbol - depends on what your are aiming to do

 
Why don't you create a loop to go each chart and check the logic on each chart, then open position on that Chart Symbol
Reason: