Build notes
MQL5 New Bar Detection in OnTimer: Judging a Closed Candle Without Firing on Attach
Batdorj Byambadorj · · 4 min read
The standard way to detect a new bar in MQL5 fits in three lines. Remember iTime(symbol, timeframe, 0). Look again. If it changed, a bar has closed.
That check is correct. Used as it stands in an alert tool, it is also wrong in two opposite directions: it speaks when it should be silent, and it reports old news as if it were new.
My EA sends an alert when a candle closes beyond a line. It runs on a 250 ms timer and watches any symbol and timeframe, with or without a chart (how that works). A bar closes once a minute at most, so on nearly every pass there is nothing to do. All the difficulty is in the one pass where iTime has moved.
Danger one: firing on attach
The bars already on the chart closed long ago. If the first look counts as "it changed", or if the code helpfully walks back over recent history, attaching the EA sets off every candle alert at once, each one announcing a close the trader watched happen.
The fix is a flag per symbol-and-timeframe pair. I call it primed. The first sighting of a pair only records the current bar's open time. Nothing is judged. From then on, only bars that close while the engine is watching can fire anything. A pair added later, because a new alert needs it, starts unprimed like the rest.
Danger two: catching up
The opposite failure needs a stall. The terminal freezes, the connection drops, the laptop sleeps. When the engine looks again, four M15 bars have closed.
The tempting move is to work through all four in order. But telling the trader about the first of them is telling them about something that stopped being true an hour ago, with the urgency of something happening now.
So only the newest closed bar is judged. The others are counted as missed and written to the log. They are never judged, and never dropped without a trace.
That rule loses alerts, and I chose it knowing that. It is a limit of one terminal watching one feed. A quiet miss that shows up in a counter is better than a late alert that sends someone to the chart for a move that is already over.
The whole detector
datetime t0 = iTime(sym, tf, 0);
if(t0 == 0)
return; // history still loading
if(!primed) // never judge what was already there
{
lastOpen = t0;
primed = true;
return;
}
if(t0 == lastOpen)
return; // same bar, nothing closed
if(t0 < lastOpen) // history was rebuilt under us
{
lastOpen = t0;
return;
}
datetime watched = lastOpen; // the bar we expected to close
datetime closed = iTime(sym, tf, 1);
lastOpen = t0;
if(closed <= 0)
return;
if(closed != watched)
missed++; // bars went by unseen: say so in the log
Judge(sym, tf, closed); // only the newest closed bar
Four details in there are easy to get wrong.
Zero is not a time. While history is loading, iTime returns 0. Priming on that would make the first real bar look like a change.
Time can go backwards. If the newest bar's open time is earlier than the one remembered, the history was rebuilt. Resynchronise and judge nothing.
The event names a bar, not a moment. What is passed on is the open time of the bar that closed. The evaluator finds it with iBarShift(sym, tf, closed, true), exact match on. With an inexact match, a missing bar would quietly hand it the neighbour.
The fired time is the bar's close. That is the bar's open plus PeriodSeconds(tf), not the moment the engine noticed. The history row then says when the condition was true, which is the question the trader will ask.
A cousin: the alert that was born true
Priming protects against old bars. It does not protect against a new alert whose condition already holds. Create "close above the line" while price is closing above the line, and the next close fires, telling the trader what they were looking at when they set it.
So each alert carries an armed flag. An alert created while its condition is already true starts unarmed and cannot fire. It arms itself the first time the condition is observed false.
I ran the two side by side on Bitcoin M1: same line, same condition, one armed and one not. The armed one fired on the first close. The other stayed silent for about eight closes, armed when price fell back and the condition went false, and fired when price returned. Eleven minutes separated the two.
One rule matters more here than the flag itself. "Could not evaluate" is not "false". If history is missing or the line has no value at that bar, the alert stays unarmed. Arming on a failed check would release an alert that never actually went false.
What I would keep
- Prime each symbol-and-timeframe pair on first sight. Judge only bars that close while you are watching.
- After a stall, judge the newest closed bar only. Count the rest, and log them.
- Do not prime on
iTime == 0, and resynchronise if time goes backwards. - Stamp the alert with the bar's close time, not the time you noticed.
- Keep "could not check" separate from "checked, and it was false".
The EA these notes come from is free to download, and the alert types it offers are described in How to Use.
Batdorj Byambadorj
Batdorj Byambadorj has been trading forex for his own account since 2007, mostly gold. He is the sole developer of fx-alert and writes every article on this site himself.