🚀 AI One-Click Generation of mql4 Strategy Code

Using the OnTimer() Event in Mql4 for Time-Based EAs

mql4 | Published on: 2025/11/28
The following content is generated by EasyQuant .

Problem Description

How can I make my code run every 5 seconds, instead of on every price tick?

Solution

To run your code at a specific time interval (every 5 seconds) regardless of market activity, you should use the OnTimer() event handler instead of OnTick().

OnTick() only triggers when a new price quote is received. If the market is slow, your code might not run for minutes. OnTimer() uses the system clock to trigger events at exact intervals.

Here is the complete MQL4 structure to implement a 5-second loop:

MQL4 Code Implementation

#property strict

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Initialize the timer to trigger every 5 seconds
   if(!EventSetTimer(5)) 
   {
      Print("Error: Failed to set timer!");
      return(INIT_FAILED);
   }
   
   Print("Timer started: 5 seconds interval.");
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // Always kill the timer when the EA is removed to free resources
   EventKillTimer();
   Print("Timer stopped.");
}

//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
{
   // --- YOUR STRATEGY LOGIC GOES HERE ---
   
   // Example: Check prices or conditions
   Print("5 seconds passed. Current Bid: ", DoubleToString(Bid, Digits));
   
   // If you have a specific function you used to run in OnTick, call it here:
   // CheckTradingConditions();
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // Leave this empty if you only want to trade based on the timer.
   // Or, use this ONLY for operations that require immediate execution 
   // (like Trailing Stops) while keeping entry logic in OnTimer.
}

Key Components Explained

  1. EventSetTimer(5) in OnInit(): This tells MetaTrader 4 to generate a timer event every 5 seconds.
  2. OnTimer(): This is the function that catches that event. You should move your main trading logic (entry conditions, indicator calculations) from OnTick into this function.
  3. EventKillTimer() in OnDeinit(): This is crucial. If you do not stop the timer when removing the EA, it may continue to consume resources or cause errors in the terminal background.

Important Note on Backtesting

The OnTimer() function does work in the Strategy Tester. However, the Strategy Tester processes time based on the historical data timestamps, not your computer's real-time clock. It will simulate the 5-second intervals accurately relative to the historical simulation time.

Q&A

Q: Can I use Sleep(5000) inside OnTick instead?
A: It is not recommended. Sleep() freezes the entire Expert Advisor. During that freeze, the EA cannot perform other necessary tasks, such as modifying trailing stops, detecting manual closures, or responding to terminal events. Furthermore, Sleep() inside OnTick still requires an initial tick to start; if the market is quiet, the code will not run at all.

Q: What if I need more precision (e.g., 0.5 seconds)?
A: You can use EventSetMillisecondTimer(500). This sets the timer in milliseconds (1000 ms = 1 second).

Q: Will OnTimer run if the market is closed?
A: Yes. Unlike OnTick, which stops when the market closes (because no prices are coming in), OnTimer continues to run as long as the terminal is open and the EA is attached. You may need to add a check like if(!IsTradeAllowed()) return; inside OnTimer if your logic attempts to open orders.