EA Doctor rule · Environment and lifecycle
Timer started but never stopped
The EA starts a timer with EventSetTimer() but never calls EventKillTimer(), which the MQL5 reference pairs with it in OnDeinit().
Why it matters
EventSetTimer() and EventSetMillisecondTimer() start the program's timer; the MQL5 reference says to stop it with EventKillTimer(), usually in OnDeinit().
An EA is not unloaded when the chart's symbol or timeframe changes or its inputs are edited: MetaTrader calls OnDeinit() and then OnInit() again. Stopping the timer in OnDeinit() and starting it in OnInit() keeps exactly one timer, at the interval of the current inputs.
When the rule fires
EventSetTimer() or EventSetMillisecondTimer() is called and EventKillTimer() appears nowhere in the file.
When it stays quiet
EventKillTimer() is called anywhere in the file.
How to fix it
- Call
EventKillTimer()inOnDeinit(). - Start the timer in
OnInit()and check its return value.
Code that fires it
int OnInit()
{
EventSetTimer(60);
return(INIT_SUCCEEDED);
}
void OnTimer()
{
Comment("Server time: ", TimeToString(TimeCurrent(), TIME_SECONDS));
}Fixed code
int OnInit()
{
if(!EventSetTimer(60))
{
Print("EventSetTimer failed: ", GetLastError());
return(INIT_FAILED);
}
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
EventKillTimer();
Comment("");
}
void OnTimer()
{
Comment("Server time: ", TimeToString(TimeCurrent(), TIME_SECONDS));
}The fixed code shows this rule’s fix and compiles in MetaEditor for MetaTrader 5 (with CTrade trade, InpLots and InpMagic declared, as in a typical EA). Other rules may still apply to it as a fragment: check your whole EA.
Related MQL5 errors
More rules on environment and lifecycle
- LowAlgo trading permission not checkedThe EA sends orders without checking that algo trading is allowed in the terminal, for the EA and on the account, so every order fails when one is off.
- LowChart objects created but never removedThe EA draws chart objects but never deletes them, so lines and labels stay on the chart after it is removed.
Sources
Get your EA fixed
Check a whole EA for this and 29 other mistakes with EA Doctor, free and in your browser. Or send it to us: we confirm the price in writing, then fix it.