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

Asked by Radhesh Joshi · SOLVED
1 reply 254 views Jump to solution Reply
Radhesh Joshi Original Post
Strategy Builder

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?

Posted Jul 27
Reply

    1 Reply

    Tech Support AlgoDelta
    Tech Support AlgoDelta Automation Expert ·

    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.

    Verified Solution
    • 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! – Radhesh Joshi Jul 28
    Markdown supported · ```json for code blocks · paste or drop screenshots

    Be specific and kind. Never share API keys, passwords or personal account details.

    Welcome to the community

    Log in or create your account in under a minute.

    1. 1Mobile
    2. 2E-mail
    3. 3Password
    +91

    Have a password?

    By continuing you agree to the community guidelines. We’ll send a one-time code by SMS.