Home System Trading Post

How to Detect the Start of a New Candle in MetaTrader 5

Attachments
39103.zip (884 bytes, Download 0 times)

If you're using an Expert Advisor (EA), you probably know that when a new tick quote comes in, the MetaTrader terminal triggers the default OnTick() event handler. But the catch is, there's no built-in event for when a new bar or candle kicks off.

To catch the opening of a new candle, you'll need to keep an eye on the opening time of the most recent bar. When that time changes, it signals the start of a new bar, and you can take action accordingly. Below is a sample code snippet that works with both MQL4 and MQL5, demonstrating how to implement this:

// Default tick event handler
   void OnTick()
   {
      // Check for new bar (compatible with both MQL4 and MQL5).
         static datetime dtBarCurrent  = WRONG_VALUE;
                datetime dtBarPrevious = dtBarCurrent;
                         dtBarCurrent  = iTime( _Symbol, _Period, 0 );
                bool     bNewBarEvent  = ( dtBarCurrent != dtBarPrevious );

      // React to a new bar event and handle it.
         if( bNewBarEvent )
         {
            // Detect if this is the first tick received and handle it.
               /* For example, when it is first attached to a chart and
                  the bar is somewhere in the middle of its progress and
                  it's not actually the start of a new bar. */
               if( dtBarPrevious == WRONG_VALUE )
               {
                  // Do something on first tick or middle of bar ...
               }
               else
               {
                  // Do something when a normal bar starts ...
               };

            // Do something irrespective of the above condition ...
         }
         else
         {
            // Do something else ...
         };

      // Do other things ...
   };

In the code above, the static variable helps keep track of the bar's opening time, even after the OnTick() function has run its course. Unlike regular local variables, this one remembers its value and doesn’t reset when the function ends, which is crucial for spotting any change in the current bar's opening time.

Also, keep in mind that when you first load the EA onto a chart, the code behaves as if a new bar has just opened. You might want to handle this situation differently, so be sure to consider that in your coding.

Lastly, remember that all my source code for CodeBase publications can now be found in the "Public Projects" tab of MetaEditor under the name "FMIC".

Related Posts

Comments (0)