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 #41601

author EAcpu | 3 reads | 0 comments |

For an Expert Advisor (EA) , when a new quote ( "tick") is received by the MetaTrader , the standard OnTick() event handler is called by the terminal. However, there is no standard event handler for when a new bar (candle) starts.

To detect this, you need to monitor the opening time of the most recent bar. When it changes, it means the start of a new bar and you can react to situations and handle events. The following code example, compatible with MQL4 and MQL5, demonstrates one of the ways how to achieve this goal:

 //Standard scale event handler blank check ()
  {
// Check new bars (compatible with MQL4 and MQL5). static datetime dtBarraCorrente = error_value ;
datetimedtBarraPrecedente = dtBarraCorrente;
                        dtBarraCorrente = lovetime ( _symbol , _period , 0 );
Boolean bEventoBarraNova = ( dtBarraCorrente != dtBarraPrecedente );

// React to the events of the new bar and handle this situation. if (bEventoBarraNova)
        {
// Detect if this is the first quote received and handle this case. /* For example, when it is first applied to the graph and the bar is in the middle of its progress and is not really the start of a new bar. */ if (dtBarraPrecedente == error_value )
              {
// Perform some operation at the first tick or in the middle of the bar... }
other {
// Do something when the normal bar appears... };

// Do something independent of the previous condition... }
other {
// Do something else... };

// Do other things... };

In the previous code, 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 previous code will react as if the bar has just been opened. If this situation needs to be handled differently, special handling is required.

Please note that all my source code repository publications are now also available through the meta-editor 's "Public Projects" under the name "FMIC".


Attachment download

📎novabarra.mq5 (1.53 KB)

Source: MQL5 #41601

Verification code Refresh