Introduction to New Bar Detection in MQL5
Detecting a new bar in MQL5 is a fundamental task for many trading strategies, especially those that rely on price action, candlestick patterns, or time-based analysis. Knowing when a new bar forms allows your Expert Advisor (EA) or script to execute specific actions at the beginning of each period, ensuring accuracy and efficiency.
Understanding the Importance of New Bar Detection
New bar detection is crucial for:
- Executing trades at the open of a new bar: Many strategies are based on the opening price of a new period.
- Calculating indicators based on historical data: Updating indicators at the start of each bar prevents unnecessary calculations on every tick.
- Implementing time-based logic: Triggering events at specific times related to the bar’s formation.
Common Approaches to Detecting New Bars
Several methods exist for detecting new bars in MQL5, each with its advantages and drawbacks. This article focuses on techniques utilizing the OnTick() event. While OnTimer() can also be used for time-based events, we will focus on tick-based approach for detecting a new bar.
The OnTick() Event in MQL5
Explanation of the OnTick() Function
The OnTick() function is an event handler in MQL5 that is automatically called whenever a new tick of price data arrives for the symbol the EA is attached to. This makes it a natural place to implement logic for detecting new bars, although careful implementation is required.
Limitations and Challenges of Using OnTick for New Bar Detection
While OnTick() provides real-time data updates, detecting new bars directly within it can be tricky. The primary challenge is that OnTick() is triggered multiple times within the same bar, so you need to ensure your code only executes the new-bar logic once per bar. Incorrectly implemented code can lead to repetitive execution and incorrect trading decisions.
Implementing New Bar Detection Using OnTick() – Method 1
Storing the Last Known Time
This method involves storing the time of the last processed bar and comparing it to the time of the current bar each time OnTick() is called. When the current bar’s time differs from the stored time, a new bar is detected.
Comparing Current Time with the Stored Time
The core logic is to compare the current bar’s open time with the previously stored bar’s open time. If the times are different, a new bar has formed.
Example Code Implementation
datetime lastBarTime;
void OnTick()
{
datetime currentBarTime = iTime(Symbol(), Period(), 0);
if (currentBarTime > lastBarTime)
{
// New bar detected!
Print("New bar detected at: ", TimeToString(currentBarTime));
// Perform your new-bar logic here
lastBarTime = currentBarTime; // Update lastBarTime
}
}
Advantages and Disadvantages of Method 1
- Advantages: Simple to implement, relatively efficient.
- Disadvantages: Relies on comparing
datetimevalues, which might be affected by slight time discrepancies. Requires a global variablelastBarTimeto persist the last processed bar time.
Implementing New Bar Detection Using OnTick() – Method 2 (Using iTime)
Using iTime function
The iTime() function retrieves the open time of a specific bar on a given chart. By comparing the current bar’s open time with the stored open time, we can detect new bars.
Comparing current bar time with previously stored bar time
This approach is similar to the previous method, but can provide a more robust comparison.
datetime lastBarTime = 0;
void OnTick()
{
datetime barTime = iTime(Symbol(), Period(), 0);
if(barTime > lastBarTime)
{
// New bar detected
Print("New bar detected at: ", TimeToString(barTime));
// Add your code here to execute on new bar
lastBarTime = barTime;
}
}
Advantages and Disadvantages of Method 2
- Advantages: Straightforward and easily understandable. It leverages the built-in
iTimefunction for accuracy. - Disadvantages: Still requires a global variable to store the last bar’s time and might be susceptible to missed ticks or time synchronization issues, although these are rare.
Advanced Techniques and Considerations
Handling Timeframe Changes
When the timeframe of the chart is changed, the lastBarTime variable will no longer be valid. You need to reset it, typically in the OnInit() function, but also consider handling timeframe changes dynamically. You can use the SymbolInfoInteger(Symbol(), SYMBOL_SELECT) function in MQL5 to check for symbol selection changes and reset lastBarTime accordingly.
Dealing with Market Gaps
Market gaps can sometimes cause issues with time-based new bar detection. Implementing additional checks to validate the time difference between bars can help mitigate these issues. For instance, if the time difference exceeds the expected timeframe duration, it might indicate a gap.
Optimizing Performance
New bar detection is a fundamental operation. Optimize your code to avoid unnecessary calculations within the OnTick() function. Minimize the number of function calls and keep the logic as lean as possible to ensure your EA responds quickly to market changes. Using efficient data structures and algorithms is also crucial for optimal performance.