Sunday, July 16, 2017

MT4 - Detecting a New Bar

Often when I am coding a new EA (Expert Advisor) I only want to execute the code to look for a new trade setup on the start of a new bar.  The code below provides this function.

Function



bool IsNewBar()
{
   bool result = false;
   static datetime lastBarTime = NULL;
  
   if (lastBarTime == NULL)
   {
      lastBarTime = iTime(NULL, 0, 0);

     
      // always return false when the EA first starts
      // so as not to falsely trigger buys etc. 
      result = false;
   }
   else if (iTime(NULL, 0, 0) != lastBarTime)
   {
      lastBarTime = iTime(NULL, 0, 0);
      result = true;
   }
   return result;
}


Usage


if ( IsNewBar() ) {
   // Insert code to only run when a new bar has formed.
}





MT4 - Detecting a New Bar

Often when I am coding a new EA (Expert Advisor) I only want to execute the code to look for a new trade setup on the start of a new bar.  T...