1
votes

I am really new to MQL4, and still trying to grasp the concept. I would want to have an event handler to detect every candle bar opening (or every previous candle bar closing). Trying to wrap that around my head but it is not working:

So I have a function to check for the tick:

bool checkingFirstTick(){
   datetime currentTime = iTime(Symbol(), Period(), 0);

   if(currentTime - lastCandle > 0){
      lastCandle = currentTime;
      return true;
   }
   return false;
}

where lastCandle is a global variable.

Now when I put it into the OnTick() event:

void OnTick(){

  Print("Ticking");
   if(checkingFirstTick()){
      Print("It's an opening!");
   }
}

The It's an opening! statement never get printed.

enter image description here

Am I doing something fundamentally wrong? Or is there any more efficient way to listen to an opening of the candle bar, no matter what is the period I set?

1
All is fine, but keep in mind that you run it on H4, so no events until 0:00:00 or 4:00:00 etc - Daniel Kniaz
@DanielKniaz yes, but then you look at the log, it is ticking at almost every second! which shouldn't be the case right? shouldn't it log every 4 hours? - CozyAzure
'Ticking' at every tick, 'It's opening' one a new bar'. Hide the 'Ticking' line to see if you get new bars, I think you have millions of 'Ticking' and do not see 'new bar' line in logs - Daniel Kniaz

1 Answers

4
votes

Try this:

// --- Global Variable ----
datetime ArrayTime[], LastTime;

void OnTick() {
   if(NewBar(PERIOD_H1)) {
       // insert your program here
   }
}

bool NewBar(int period) {
    bool firstRun = false, newBar = false;

    ArraySetAsSeries(ArrayTime,true);
    CopyTime(Symbol(),period,0,2,ArrayTime);

    if(LastTime == 0) firstRun = true;
    if(ArrayTime[0] > LastTime) {
        if(firstRun == false) newBar = true;
        LastTime = ArrayTime[0];
    }
    return newBar;   
}