Welcome Forex EA downloads & MT4/MT5 auto-trading resources — EAs, Gold EAs, quant tools and real-world automation.
Sign In Sign Up

Detecting the start of a new bar or candle - MetaTrader 5 Expert - MQL5 #39103

author EAcpu | 2 reads | 0 comments |

For an Expert Advisor (EA) , when a new quote arrives, the MetaTrader Terminal calls the default OnTick() event handler. However, there is no default event handler when a new bar (candle) starts or opens.

To detect this, it is necessary to monitor the opening time of the current latest bar. Once it changes, it means the start of a new bar to which people can react and handle events. The following example code, compatible with MQL4 and MQL5, shows one way how to achieve this goal:

 //Default tick event handler blank check ()
  {
// Check new bars (compatible with MQL4 and MQL5). static datetime dtBar current = error_value ;
DateTimedtBarPrevious = dtBarCurrent;
                        dtBarcurrent= lovetime ( _symbol , _period , 0 );
Boolean value bNewBarEvent = ( dtBarCurrent != dtBarPrevious );

//React to the new bar event and handle it. if (bNewBarEvent)
        {
// Check if this is the first quote received and handle it. /* For example, when it is first attached to the chart and the bar is in the middle of its progress and this is not actually the start of a new bar. */ if (dtBarprevious== error_value )
              {
// Do something in the middle of the first tick or bar... }
other {
// Do something when the normal bar starts... };

// Regardless of the above conditions, do something... }
other {
// Do something else... };

// Do other things... };

In the code above, a static variable keeps track of the bar's opening hours, even when returning from the bar's OnTick() function. Unlike a normal local variable, it remembers its data content and does not release it when leaving the function. This is key to detecting changes in the opening time of the current bar.

It is also important to note that when the EA is first placed on the chart, the above code reacts as if the bar has just been opened. If the situation needs to be handled differently, then the situation needs to be handled specially.


Attachment download

📎 newbar.mq5 (2.8 KB)

Source: MQL5 #39103

Verification code Refresh