Home Forums MT4/MT5 Connection Is there any built-in function in MT5 to detect when a new candle starts?

Is there any built-in function in MT5 to detect when a new candle starts?

  • Author
    Posts
    • I’m creating an Expert Advisor in MT5 and I only want my strategy logic to run once whenever a new candle is formed.

      I know OnTick() executes on every incoming tick, but I don’t want my conditions to be checked on every price update.

      Is there any built-in function in MQL5 that can directly detect a new candle, or what is the recommended way to identify that a new bar has started?

    • Yes sir, this is a very common question for anyone developing strategies in MT5.

      There is no built-in function in MQL5 that directly tells you a new candle has started.

      The standard and recommended approach is to compare the opening time of the latest candle with the previously stored candle time.

      Whenever the latest candle time changes, it means a new candle has been formed.

      You can do it like this:

      datetime lastBarTime = 0;
      
      bool IsNewCandle()
      {
         datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
      
         if(currentBarTime != lastBarTime)
         {
            lastBarTime = currentBarTime;
            return true;
         }
      
         return false;
      }

      Now, wherever you want your strategy to execute only once per candle, simply use the function like this:

      void OnTick()
      {
         if(IsNewCandle())
         {
            // Your strategy logic here
      
            Print("New candle detected.");
         }
      }

      This is the most commonly used approach in MQL5 because:

      -It prevents your strategy from executing on every incoming tick.

      -It ensures your trading logic runs only once for each newly formed candle.

      -It works on any timeframe since it uses the current chart timeframe (PERIOD_CURRENT).

      So, instead of looking for a dedicated “new candle” function, the recommended practice in MT5 is to compare the latest candle’s opening time with the previously stored time. This is the approach used in most professional MQL5 Expert Advisors.

    • This is what I am looking for, thanks a lot for the detailed answer with the codes also, it’s really help me to detect new candle.

      Thanks again!

Viewing 2 reply threads
×

Start a Discussion

Get help from the AlgoDelta community.

×

Welcome Back!

Enter your email to sign in or create an account. No passwords needed.

⚠️

Delete This?

Are you sure you want to delete this? This action is permanent and cannot be undone.

Scroll to Top