Ways to detect a birth of new bar in EA and Indicators

28 January 2024, 15:31
Rajesh Kumar Nait
2
126

For Indicators:


// Add this code inside OnCalculate
ArraySetAsSeries(time,true);
static datetime pastime = time[0];
if(pastime!=time[0]) {
   Print("new bar closed");
   // Do whatever you want
   pastime=time[0];
}


For EA :Example for birth of a new bar in 1minute

//define global variable
datetime lastBarTime=0;

void OnNewBar() {
//---

// Check if a new bar has opened
   if (lastBarTime != iTime(NULL, PERIOD_M1, 0)) {
      // Perform your desired actions when a new 1-minute bar opens

      //do something
  
      Print("New 1-minute bar opened at: ", TimeToString(iTime(NULL, PERIOD_M1, 0)));

      lastBarTime = iTime(NULL, PERIOD_M1, 0);

   }

}
add OnNewBar() function to OnTick() or OnTimer() to detect the birth of a new bar


Share it with friends: