[MQL5 Paradise Episode 6] The Birth of a 24-Hour Working Robot! Feel the heartbeat of the EA with "OnTick"
Everyone, hello! I’m Pineapple.
In the previous Session 5,SymbolInfoDouble()we learned how to obtain the current “live price (Bid and Ask)” from MT5. When our program connected to real market data, didn’t you feel a touch of excitement?
However, up to now, what we created in this series has been a kind of “script.” A script performs its task“only once”when you drag it onto the chart, and that’s the end. Even if you can fetch real-time prices, if it only checks the price once and stops, it won’t become an automated trading robot that trades while you’re asleep, right?
So this time, we graduate from scripts and“Expert Advisor (EA)”and step fully into development. A system that monitors the market around the clock. The heart of an EA is“OnTick”as a framework we will learn!
Ready with a warm cup of coffee? Then please open MetaEditor right away.
From a one-time job (script) to a dedicated monitor (EA)
Let’s illustrate the difference between “script” and “EA” with a daily-life analogy.
A script is like a“one-off errand”. If you ask it to go to a convenience store and check the current milk price, it will dash there, check the price, and report back. But even if the milk goes on a half-price sale afterward, it won’t tell you again unless you ask it.
On the other hand, an EA is“a dedicated monitor”. It’s like asking someone to stand in front of the milk aisle all the time and report to you whenever the price changes. If it drops to half price, you want it to buy immediately—without complaints, 24/7, every day of the year.
What we want to create, of course, is the latter—“a dedicated monitor.” The mechanism that teaches the program this timing “every time the price changes” is what this time’s hero,
OnTickOpen the new template: “Expert Advisor”
A little saying goes a long way: Let's actually create an EA file in MetaEditor.
- Click the “New” button at the top-left of MetaEditor.
- Until now we selected the bottom option “Script,” but this time choose the very top“Expert Advisor (Template)”and proceed to “Next.”
- Enter a name like “My_First_EA” and proceed to “Finish.”
Then a new code screen will open. Unlike scripts, you’ll see a lot of English text. It may be a bit intimidating, but don’t worry. Just like with scripts, lines starting with gray// are comments.
If you scroll down a bit, you should find the following description.
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
}
Found it? This is the most important heart of the EA—the“OnTick” framework.
The magical framework that is called every time the price moves: OnTick
When you look at FX charts, you’ll see the price twitching a bit, right? Each update as the price moves is called a“Tick” in technical terms.
MT5, as the price moves by 1 Tick, runs the contents of thisOnTick()framework from top to bottom once. In other words, if the price moves three times in one second, the contents of this frame will also execute at three times in that second.
The script framework we learned so far wasOnStart(). That meant “only once when started.” In contrast,OnTick()means “every time there is a Tick (price update).”
What we should do is write inside theOnTick()braces{ }the things we want to check every time the price moves.
Let’s actually obtain price inside OnTick
Now, let’s put the real-time price retrieval we learned last time insideOnTick(). It will fetch the latest Bid price whenever the price moves and output it to the log (Expert tab) continuously.
Write the following code inside theOnTick()frame. (You can remove the existing notes if you like.)
void OnTick()
{
// 1. Put the chart currency pair name into a variable
string my_symbol = _Symbol;
// 2. Get the latest Bid (sell price) and put it into a variable
double current_bid = SymbolInfoDouble(my_symbol, SYMBOL_BID);
// 3. Output the retrieved price to the log
Print("The current Bid price is ", current_bid, "!");
}
Explanation of the sample code
The content of the code is exactly the same as what we learned before. The difference is only where you write it.OnStart() versusOnTick(); placing it inside OnTick() dramatically changes MT5’s behavior.
Now click the “Compile” button to confirm there are no errors, and return to MT5’s chart screen. This time, expand the EA folder in the Navigator window, not the Script folder. There you should find your newly created “My_First_EA.”
Drag this onto a chart and press OK in the settings dialog that appears. (If you see the EA’s name with a blue hat icon in the top-right of the chart, you’re all set.)
Now look at the “Experts” tab in the bottom of MT5’s toolbox. Each time the chart’s price moves, you should see rapid new messages like: “Current Bid price is 150.51!” “Current Bid price is 150.50!” appearing one after another in quick succession.
Seeing your own program relentlessly chasing the market and calculating in real time is a little moving, isn’t it?
(Note: If you’re testing on weekends when the market is closed and prices don’t move, you won’t see messages. Look forward to Monday morning!)
Because Tick moves, simplicity shines
As you saw just now,OnTick()contains code that runs at a furious pace each time the price moves. In a volatile market, it can be invoked dozens of times per second.
Do you understand what this implies? If you write inside OnTick() a very time-consuming and complex calculation, your computer’s CPU may get overwhelmed.
If you stuff in many complex if statements to match past charts or heavy indicator calculations, the EA may fail to keep up with market speed (risk of overfitting). If processing is slow, order timing may be late, resulting in slippage and a loss of funds.
That is why I value“simple and robust trading”.
Truly excellent programs are remarkably clean and free of unnecessary calculations. “Only fetch what is truly needed now, and make quick decisions.” This lightness is the greatest weapon to survive harsh real-time market conditions.
As you incorporate your own logic into EAs, cultivate the habit of always asking, “Does this processing really need to run every time Tick moves?” Slimming down code not only looks better but directly improves performance.
In closing
This time, we stepped up from a script to an Expert Advisor (EA) and learned about the heart of its operation—theOnTick()function. By understanding how the program runs whenever the price moves, you’re now ready to begin automated trading.
However, as it stands, you’re simply chasing the current price. In real trading, indicators like the Moving Average (MA) or RSI are used to analyze trends and overheating in the market.
Next time, we will cover“How to read indicator values inside a program”. We’ll retrieve both the current price and the moving average value simultaneously and use the if statements you learned a couple of lessons ago to program Golden Crosses and Dead Crosses.
Knowledge that was points will finally start to connect into lines. It’s going to get really interesting from here, so please look forward to it!
Well then, see you in the next edition of “MQL5 Paradise.” May your EA begin beating with a strong, steady heartbeat. Pineapple here!