mql5

MQL5 IsNewBar function ignore 1970.01.01


i am working with mql5 and want to have a little function to detect a new bar. Seems not to be a hard point, smile ... But i am really confused about my function.

My goal is: I want to have a bool function that give back true if a new bar is opened. During initialisation / starting an EA first Tick will be nothing, so 1970.01.01 with value 0 should happen and be ignored. I really want to wait until the first complete new bar is opened.

//+------------------------------------------------------------------+
//| IsNewBar
//+------------------------------------------------------------------+
bool IsNewBar(ENUM_TIMEFRAMES m_timeframe){
   static datetime lastbar;
   datetime currentbar = (datetime)SeriesInfoInteger(_Symbol,m_timeframe,SERIES_LASTBAR_DATE);
   if(lastbar != currentbar){
      lastbar = currentbar;
      // if lastbar is 1970.01.01 (=value 0) ... This will happen during start an EA in the middle of a bar.
      if(lastbar != 0){
         Print("true");
         return true;
      }else{
         Print("false");
         return false;
      }
   }
   return false;
}

This is my testing code to activate the function:

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(){
   if(IsNewBar(PERIOD_M1)==true){
      Print("x");
   }
}

It seems like completely ignored the first Tick 1970.01.01 thing. I did not figure out where my problem is.

Please help! Thank you


Solution

  • I found the problem of my original code.

    If anyone is interesting in, here is the working function:

    bool IsNewBar(ENUM_TIMEFRAMES m_timeframe){
       static datetime lastbar;
       datetime currentbar = (datetime)SeriesInfoInteger(_Symbol,m_timeframe,SERIES_LASTBAR_DATE);
       
       if(lastbar != currentbar){
          if(lastbar == 0){
             lastbar = currentbar;
             return false;
          }else{
             lastbar = currentbar;
             return true;
          }
       }
       return false;
    }