Get Free Consultation!
We are ready to answer right now! Sign up for a free consultation.
I consent to the processing of personal data and agree with the user agreement and privacy policy
In algorithmic trading, your Expert Advisor (EA) lives and breathes through events. Among those events, the arrival of a new market tick is one of the most important. This is why event driven programming on tick in expert advisor design is such a powerful concept. Instead of constantly looping and checking prices, your EA simply waits for the server to inform it that “something changed” — a new tick came in — and then reacts instantly.
In MetaTrader platforms (MT4 and MT5), this behavior is implemented with the OnTick() function. Every time the broker sends a price update for the symbol where the EA is attached, OnTick() is called. Inside this function, you decide what your EA will do: update indicators, check entry rules, modify stops, or close positions. Thinking of your EA as a system that reacts to ticks instead of one that constantly polls the market makes your design more efficient, cleaner, and easier to maintain.
When you understand this event-driven model, you also start thinking in terms of what should happen when a tick arrives instead of just “what is the current price.” That mental shift is what separates quick experimental scripts from robust professional-grade trading robots.
Event-driven programming is a style where your code reacts to events rather than running in a continuous, manual loop. In trading platforms, these events usually come from the market or from the platform itself. Typical events include:
In a simple procedural script, you might write a for loop that cycles through data, calculates something, and then exits. That’s fine for one-time tasks. But markets are continuous; they don’t stop. If you tried to loop forever inside an EA, you’d freeze the terminal.
Event-driven EAs remove this problem. The trading platform is responsible for waiting and listening to the server. When something interesting happens, it calls your event handler, such as OnInit(), OnTick(), or OnDeinit().
The core idea is: Don’t pull; let the platform push.
You don’t ask the market “Do we have a new price?” thousands of times per second. Instead, the platform says “Here’s a new price,” and your EA reacts.
This changes the way you design logic. You split your code into parts:
OnTick() is the heart of real-time trading decisions. It gets called automatically each time the price for the chart symbol updates.
In MT4 and MT5, the trading server streams quotes to your terminal. Each quote is a tick: a combination of bid, ask, and possibly volume information. When a tick for the symbol hits your terminal, MetaTrader:
OnTick() function for every EA attached to that symbol’s chartInside OnTick(), you can:
Bid, Ask, SymbolInfoDouble(), or iClose() for indicator valuesFor reference, the official MetaQuotes documentation explains the event-handling model and OnTick() function details.
(Note: For a deeper dive into the latest official docs, you can search “MetaTrader MQL4 OnTick reference” on the MetaQuotes site.)
You often combine OnTick with OnTimer to balance responsiveness and CPU usage.
Ticks don’t arrive at perfectly regular intervals. Their frequency depends on:
During high volatility, OnTick() can fire many times per second. During low liquidity, you might wait several seconds or more between ticks. Your EA logic must handle both extremes gracefully.
A typical EA structure in MQL4/MQL5 looks like this:
int OnInit()
{
// Load settings, indicators, and variables
return(INIT_SUCCEEDED);
}
void OnTick()
{
// Main trading logic triggered on every tick
}
void OnDeinit(const int reason)
{
// Cleanup resources
}
You might also add a OnTimer() function if you want periodic tasks.
Let’s imagine a basic strategy:
On every tick, you’ll:
Here’s a simplified pseudocode:
OnTick:
read fastMA and slowMA for current and previous bar
if no open trades:
if fastMA crosses above slowMA:
open Buy
else if fastMA crosses below slowMA:
open Sell
else:
manage existing trade:
move stop loss
close trade if target hit or condition met
This is a classic example of event-driven logic: You only act when a tick forces the code to run.
A clean EA design separates:
You can implement this using separate functions:
void OnTick()
{
UpdateMarketData();
TradeSignal signal = MakeDecision();
ExecuteSignal(signal);
}
This separation makes your EA easier to test and maintain.
A state machine tracks where your strategy is in its life cycle. Example states:
STATE_WAITING_FOR_ENTRYSTATE_POSITION_OPENSTATE_TRAIL_STOPSTATE_EXITINGOn every tick, the EA:
This prevents messy “spaghetti code” with lots of nested if statements.
Even though OnTick() is tied to one chart symbol, your logic can:
iClose() or SymbolInfoTick()However, you must be careful with performance. Reading heavy indicators for many symbols each tick can slow down your terminal.
Recalculating indicators on every tick from scratch is expensive. Techniques to improve efficiency:
A common trick is to detect when a new candle opens:
static datetime lastBarTime;
datetime currentBarTime = iTime(Symbol(), PERIOD_CURRENT, 0);
if (currentBarTime != lastBarTime)
{
lastBarTime = currentBarTime;
// New bar logic here
}
With this pattern, you can:
OnTick() for real-time trade execution and managementOnDeinit().OnTick().This keeps your EA responsive, even in fast markets.
Your lot size often depends on:
On each tick, when you detect an entry signal, you can compute the appropriate lot size just before sending the order.
Event-driven EAs can quickly react to changing market conditions:
slippage parameters or by validating fills.Your OnTick() logic should also guard against disaster:
Backtesting lets you see how your OnTick() logic behaves with historical data. You can:
Within OnTick(), log important information:
Print("New tick: Bid=", Bid, " Ask=", Ask, " Time=", TimeCurrent());
Use Comment() to display real-time info on the chart. During development, add temporary logs for:
Common mistakes include:
A disciplined event-driven design helps you sidestep these issues.
Inside one EA, you can emulate a mini-event system:
This pattern keeps your OnTick() body small and clear.
Using OnTimer() alongside OnTick() lets you:
OnTimer()OnTick() light, focusing on trade execution and quick checksThis hybrid model balances performance and responsiveness.
You can package:
This modularity makes large EAs more maintainable and reusable.
Scalpers often trade on M1 or even tick-based logic. For them, every incoming tick is a potential opportunity. Their OnTick() functions:
Swing traders are more interested in candle closes than individual ticks. Their event-driven design often uses:
OnTick() only to detect new barsPortfolio EAs read data from several symbols and timeframes. They use OnTick() on one chart as a central “dispatcher”:
Real-world trading isn’t perfect. Your terminal might restart, or your connection may drop. A robust EA:
OnInit() after a restartDefensive practices include:
“Runaway” logic happens when your EA opens many trades or loops endlessly because of a bug. Prevent this by:
If no ticks arrive for a symbol, OnTick() is simply not called. Your EA appears “idle.” This often happens when:
You can use OnTimer() to perform periodic checks during quiet times if needed.
Delays or missed trades can be due to:
OnTick()Optimizing the code and reducing unnecessary work per tick helps a lot.
There’s no fixed number, but as a rule of thumb:
Yes. In MetaTrader’s Strategy Tester, use “Every tick” modeling mode to simulate tick-by-tick logic. This mode allows your OnTick() function to behave similarly to live trading, though modeling quality depends on historical tick data.
OnTick() belongs to Expert Advisors and is used for trading decisions.OnCalculate() belongs to indicators and is used to calculate indicator values on chart data.They are both event-driven, but they apply to different types of programs.
Both approaches are valid:
Choose based on your strategy’s complexity and your coding comfort level.
We’ve walked through how OnTick() functions as the heartbeat of your trading robot, why event-driven design matters, and how to structure your EA for clarity, performance, and safety. When you embrace event driven programming on tick in expert advisor design, you’re no longer just reacting to price changes in an ad-hoc way. Instead, you’re building a structured, maintainable, and professional trading system.
By separating data input, decision logic, and trade execution, you keep your EA clean and testable. By using caching, new-bar detection, and hybrid OnTick/OnTimer models, you maintain speed even in heavy markets. And by adding strong risk management, defensive coding, and fail-safes, you protect both your account and your peace of mind.