Skip to content
All library documents

Reliable New-Bar Detection and Event Handling in MQL5

Article MQL5 articles

Summary

The article reviews ways to detect when a new chart bar appears and develops a more reusable event-handling approach for MQL5. It identifies problems with a simple function that stores the last bar time in a static variable: repeated calls can interfere with detection, it is tied to the current symbol and period, and querying series data can fail while history is unavailable. Checks based on the first tick or equal bar prices may also miss events in live trading.

The proposed design uses a class to track bar state, with support for explicit time inputs, repeated use, initialization control, and detecting that multiple bars have passed since the previous check. For a single chart, the example calculates the bar opening time from the current time and period, then calls an OnNewBar handler when that time changes. The author argues this avoids series-query error handling and is faster. The method is presented as suitable for single-currency expert advisors; multi-currency handling is left for later work, and no benchmark evidence is provided.

Key ideas

  • Static state in a basic new-bar function can make its result depend on where and how often it is called.
  • Tick-based and bar-price checks may miss a new bar in live trading conditions.
  • A reusable bar-tracking class can support multiple calls, explicit initialization, and detection of skipped bars.
  • The example derives the current bar time from terminal time and chart-period seconds before invoking an event handler.
  • The described handler targets single-currency expert advisors; multi-currency use requires further work.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.