MQL5 Algorithmic Trading Automation
Introduction to MQL5
The Language of Trading Bots
MetaQuotes Language 5, or MQL5, is the programming language you use to build automated trading strategies for the MetaTrader 5 platform. If you've ever seen C++, MQL5 will look familiar. Its main purpose is to create trading robots, known as Expert Advisors (EAs), custom technical indicators, and scripts to perform one-off actions.
Think of MQL5 as the set of instructions you give the trading platform to execute your strategy automatically, without you needing to be at the screen.
Every MQL5 program, whether it's an EA or a simple script, follows a specific structure. It generally consists of three parts: program properties, global variables, and special functions called event handlers.
// This section defines properties of the script.
#property copyright "Your Name"
#property version "1.00"
// This is the main function that runs when the script starts.
void OnStart()
{
// Print a message to the "Experts" log in MetaTrader 5.
Print("Hello, MQL5!");
}
The lines starting with #property set metadata for your program. The OnStart() function is a specific type of event handler that executes automatically when you run a script. Anything inside its curly braces {} is the code that will run. In this case, it just prints a message.
Storing Information
To do anything useful, your program needs to store information. This is done using variables. In MQL5, you must declare the type of data a variable will hold before you use it. This helps prevent errors by ensuring a variable meant for a number doesn't accidentally store text.
| Data Type | Description | Example Code |
|---|---|---|
int | Integer (a whole number) | int magicNumber = 12345; |
double | Floating-point number (for prices) | double takeProfit = 1.2550; |
string | A sequence of characters (text) | string currencyPair = "EURUSD"; |
bool | Boolean value (true or false) | bool canTrade = true; |
datetime | Date and time value | datetime serverTime = TimeCurrent(); |
The most common types you'll use are double for handling prices and int for counting things like trade volume. The string type is for holding text, like the name of a currency pair, and bool is perfect for tracking conditions, such as whether trading is currently allowed.
Making Decisions and Repeating Actions
Trading logic is all about making decisions. MQL5 uses conditional statements to check if certain conditions are met before executing a piece of code. The most common is the if-else statement.
double currentPrice = 1.0850;
// Check if the price is above a certain level
if(currentPrice > 1.0800)
{
Print("Price is above 1.0800. Time to consider selling.");
}
else
{
Print("Price is not above 1.0800.");
}
This code checks if currentPrice is greater than 1.0800. If the condition is true, the first Print function runs. If not, the code inside the else block runs instead.
Sometimes you need to repeat an action multiple times. That's where loops come in. The for loop is ideal when you know exactly how many times you want to repeat something.
// This loop will run 5 times
for(int i = 0; i < 5; i++)
{
// Print the current loop number (i)
Print("Loop iteration number: ", i);
}
This loop starts a counter i at 0 and runs as long as i is less than 5. After each pass, i++ increases the counter by one. This is useful for tasks like analyzing the last five price bars on a chart.
Responding to Events
Expert Advisors are event-driven. They don't just run from top to bottom and stop; they sit and wait for specific events to happen on the trading platform. MQL5 uses special functions called event handlers to react to these events.
Here are three essential event handlers for any EA:
| Handler | When It Runs |
|---|---|
OnInit() | Once, when the EA is first attached to a chart. |
OnDeinit() | Once, when the EA is removed from a chart. |
OnTick() | Every time a new price quote (a tick) arrives. |
The OnInit() function is perfect for setup tasks, like initializing variables. OnDeinit() is for cleanup. The most important one is OnTick(). This is where the core logic of your trading strategy lives, as it runs with every new price update, allowing your EA to constantly monitor the market.
// Global variable to count ticks
int tickCount = 0;
// This function runs every time a new price tick arrives
void OnTick()
{
// Increase the counter
tickCount++;
// Print the total number of ticks received so far
Print("New tick! Total ticks received: ", tickCount);
// Your trading logic would go here...
}
With these building blocks—variables, control structures, and event handlers—you have the foundation for creating your own automated trading programs in MQL5.