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

Mike 2025.04.03 20:16 20 0 0
Attachments

If you're using an Expert Advisor (EA) in MetaTrader 5, you probably know that the platform calls the OnTick() function every time a new quote (or "tick") comes in. But here's the kicker: there’s no built-in function to signal when a new bar, or candle, starts.

To get around this, you’ll need to keep an eye on the opening time of the most recent candle. When that changes, it means a new candle has started, and that’s your cue to act. Below is a sample code that works for both MQL4 and MQL5, showing how to do this:

// Standard tick event handler
   void OnTick()
   {
      // Check for a new candle (works for both MQL4 and MQL5).
         static datetime dtCurrentCandle   = WRONG_VALUE;
                datetime dtPreviousCandle = dtCurrentCandle;
                         dtCurrentCandle   = iTime( _Symbol, _Period, 0 );
                bool     bNewCandleEvent  = ( dtCurrentCandle != dtPreviousCandle );

      // Respond to the new candle event.
         if( bNewCandleEvent )
         {
            // Check if this is the first tick received.
               /* This could happen when your EA is first applied to the chart and the bar is not at the start of a new candle. */
               if( dtPreviousCandle == WRONG_VALUE )
               {
                  // Handle the first tick or middle of a candle...
               }
               else
               {
                  // Handle a normal candle opening...
               };

      // Execute other actions regardless of previous conditions.
     }
      else
     {
            // Handle other scenarios...
     };

    // Additional operations...
   };

In this snippet, the static variable tracks the opening time of the candle, allowing it to retain its value even when the OnTick() function completes. This persistence is crucial for detecting when a new candle opens.

Keep in mind that when you first attach your EA to a chart, it may behave as though a new candle has just opened. You’ll want to account for this condition if it requires a different approach.

Also, for those of you interested, you can now access the source code of all my CodeBase publications directly through MetaEditor's "Public Projects" under the name "FMIC".

List
Comments 0