In this article, we will examine the basics of programming a forex trading robot. We’ll start by answering the question, “What types of codes can be programmed in the MQL4/MQL5 programming language?”
What Types of Code Can Be Programmed on the MQL4/MQL5 Programming Language?
The illustrations to be discussed here are based on the MQL4/MQL5 programming language. Three types of code can be written in the MQL4/MQL5. These are:
- Expert advisors (forex robots)
- Custom indicators
- Scripts
1. The expert advisor (EA)
This represents the automation of a manual trading system that is attached to the chart of a chosen financial asset. In other words, any code written for an EA has to be done with the chart of the asset in mind.
Some of these events run once, while others run multiple times until they are signaled to stop. So, an EA will start to operate if the events that make up the initialization (init) code sequence are activated.
These events include a new price level/tick, an event on the charts, or customized events. Once these events kick in, the EA will send an order to the broker’s server to either open a trade or close it. EA files are stored in the MQL4/Experts folder of the MT4 client.
2. The Script
This is a code used to perform a one-time execution of some functions, such as the Start event. Script files are stored in the MQL4/scripts folder of the MT4 client.
3. The Custom indicator
This is a bespoke technical indicator not listed among the native indicators on the MT4. They are not used for trading but to identify chart-linked events that can lead to the initiation of manual or EA trade activity. The custom indicator files are stored in the MQL4/indicators folder of the MT4 client.
What are the Components of an MQL4/MQL5 Code
The code written for a forex trading robot, indicator, or script in the MQL4/MQL5 environment will include syntax, variables, expressions, and conditional statements. Here is a look at what these are.
For the rest of this piece, we’ll only be making reference to the MQL4. But whatever we say also applies to the MQL5.
A. Syntax
Coding syntax is a bundle of guidelines or rules that govern the writing and structure of code within a specific programming language. In the world of MT4 and MT4 programming, the code for MQL4 will have a different syntax from C++, the language of the MT5 platform.
The syntax will determine the writing and construction of elements of the code, such as variable declarations, construction of loops and conditional statements, and presentation of instructions.
For instance, MQL4 does not have multiple inheritance or a goto operator in its syntax, but the C++ language has these, in addition to possessing address arithmetic. You will also find that elements such as how blocks of code are presented will differ.
For instance, the C++ language uses braces to indicate code blocks, while indentations are used for the same purpose in the Python programming language. Loops and conditional statements are also constructed using different keywords in different languages.
Proper compilation and execution of a Forex robot’s code depend on the programmer writing syntax that is error-free and appropriate for the coding language being used to develop the expert advisor, script, or indicator.
To assist programmers in this regard, some coding environments highlight the syntax code and also provide predictive completion to ensure an efficient and accurate representation of the coding syntax.
MQL4 (MetaQuotes Language 4) is a programming language used to develop trading robots and technical indicators on the MetaTrader 4 platform. The syntax of MQL4 is similar to that of the C programming language. Here are some key features of MQL4 syntax:
- Comments: support provided for both single-line comments (starting with //) and multi-line comments (enclosed in /* and */)
- Data types: Several data types, including integers, doubles, booleans, strings, and arrays, are supported
- Variables: MQL4 variables can be declared with a specific data type using the syntax type variableName;
- Operators: supports a range of operators, including arithmetic, logical, bitwise, and comparison operators
- Conditional statements: support provided on MQL4 for regular conditional statements like if, if-else, and switch-case
- Loops: supports the following loops – for, while, and do-while. Also supports break and continue statements
- Functions: It is possible to define functions using the syntax returnType functionName(arguments) { statements }
- Predefined functions: MQL4 provides a range of built-in functions for working with charts, indicators, and orders, among other things
- Object-oriented programming: MQL4 supports object-oriented programming concepts like classes, objects, and inheritance
You can see that the MQL4 coding environment is built to accommodate several syntax features, giving the programmer a good environment in which to build solid forex trading robots and indicators.
Comments
What are comments? In MQL4, programmers add notes to code lines to explain certain actions, functions or variables in the code. These are known as comments, and they do not impact on the program’s functionality.
Comments shine a light on the code, making it easy for the original programmer and future developers to understand certain elements of the code and explain why certain functions were written into the code.
Two kinds of comments are recognized in the MQL4 programming environment. These are:
- single-line comments
- multi-line comments.
Single-line comments start with two forward slashes (//) and continue until the end of the code line. For example:
Multi-line comments start with a forward slash and an asterisk (/*) and end with the asterisk and a forward slash in reverse order (*/). The comments are added between these two symbols. For example
Single line comments can be nested within the multi-line comments. However, multi-line comments cannot be nested.
Comments should be added intermittently within the entirety of the code to explain what each code section does or is meant to achieve. This will make the code easier to read and understand. Comments also break the code into sections, making isolating and working with each section easier.
Identifiers
In MQL4, an identifier is a name applied to a constant, variable, function, or any other programming element. As the name implies, an identifier refers to any of these programming elements in the entirety of the code. The use of identifiers has to follow some rules, and here are the MQL4 guidelines for naming identifiers.
- Identifiers must contain a maximum of only 31 characters.
- They can only contain digits from 0-9.
- They must start with a letter or an underscore symbol(_). Identifiers cannot start with a digit.
- Only letters, digits, and underscores are allowed in identifiers. By extension, special characters such as @, #, $, %, ^, &, *, are not allowed.
- Identifiers are case-sensitive, so you can only use lowercase where lowercase characters are required and uppercase for uppercase characters.
- Reserved words cannot be used in identifiers. So words that have other assigned purposes, such as OnStart, Print, if, else, while, for, int, double, string, bool, etc, cannot be used as identifiers.
- Names used as identifiers must be kept as short as possible, as long names make it harder to read or write the code.
- Identifiers should follow a consistent naming convention throughout the codebase. For example, all variables could be named using camelCase, where the first word is in lowercase, and subsequent words begin with a capital letter (e.g., myVariableName).
These identifier rules and guidelines are necessary to generate code that is readable and does not conflict with reserved keywords.
B. Variables
A variable is a named storage location that holds a value, such as a number or a string. Variables are information storage units that allow you to store and work with data within your MQL code. This helps to add flexibility to your code and allows you to customize it.
You will first look for the code under the Variables section. Here, you may decide to define new information sets for the various variable integers. Once you know what information a variable stores, you can combine these variables to get new pieces of information.
Variables are defined using various data types (such as int for integers or double for floating-point numbers), followed by a name for the variable. To create a variable, you have to define the integers of the code. Integers are whole numbers and, by definition, do not have decimal points.
For example, you may see variables x, y, and z with integers 10, 7, and 5. You can decide to define a new piece of information for a variable a. You can, therefore, say that a = y + z. Since the values of y and z are already known, it follows that a = 12.
If you define an integer by calling it “hi there“, You will need to add the “init” function
For example, to declare an integer variable called “myVar,” you would use the following syntax:
int myVar
You can also assign a value to a variable at the time of declaration. Let us assume we want the assigned value to be 12. We will use the following syntax to declare this assigned value for the myVar integer variable.
int myVar = 10;
After declaring a variable, it can be placed in the MQL code to perform a variety of functions or to perform its normal duty of being a store of information. So, if you are to add the code of the definition of the new variable a, as a summation of integer y + z, you can input it in this format:
int var1 = 10;
int var2 = 7;
Int var3 = 5
int result = var2 + var3; // result = 12
In this instance, you have declared three integer variables, known as var1, var2, and var3 (or x, y, and z). They have been assigned values of 10, 7, and 5, respectively. You are only interested in adding var2 and var3 to get a new integer for a new variable a. You use the + sign as the operator, and the int result is the new variable for a. The result value would be 12, which is the value obtained by adding var2 and var3.
For the purpose of core trading, a practical function for declaring/creating Variables is to store values that are amenable to change over time, such as the price of an asset. Currency prices change with time, so you can use a Variable to store and update this information whenever there is a tick change.
double price;
price = SymbolInfoDouble(_Symbol, SYMBOL_BID); // get the current bid price
ol, SYMBOL_BID); // get the current bid price
In a highly dynamic market like the FX market, you need to incorporate Variables in the code for your forex trading robot’s strategy to reflect this dynamism and adapt to changing market fundamentals.
Data types
Variables work in the MQL4 code in that they have to be declared according to a data format or data type. Each data type can only allow certain values for a declared variable. We have already made a mention of one data type that works with variables, which is the integer. Integers are whole numbers, so they cannot store code that defines decimals or alphabets.
What are the data types on which variables can be defined? Six data types are identified.
- Integer (int): the integer represents any number that ranges from -2 billion to + 2 billion. The int data types cannot store decimals.
- Double: represents numbers that range from -1.79 X 10308 to +1.79 X 10308. You can store data with decimal points using the double data type.
- Boolean (Bool): This represents data that defines true or false or logic.
- Color: This stores the color.
- String: a string is a line of text.
- DateTime: stores data and time.
Here is how the different data types that are used to define variables appear when written in MQL4.
You may have noticed the use of some words such as declaration, initialization, etc. These are words used to describe the start and end of all codes that make up variables.
Every variable has a beginning, an end, and what comes between. Therefore, four phases of the life cycle of variables are defined:
- Declaration/creation
- Value assignment (initialization)
- Value change (if needed)
- Destruction
So, what happens during each stage of the variable’s life cycle?
Declaration
To use a variable, you must create it first. This action of the creation of a variable is called a declaration. So you will see the terms “create” or “declare” used interchangeably. However, the more industry-friendly term is the declaration. Declaring the variable tells the code to create the variable by assigning a data type to it.
To declare a variable,
- write the data type, followed by a space
- write the variable’s name.
- close the line using a semicolon (;).
See how the variable with the integer (int) data type is declared:
- Here, the data type is int for integer.
- Variable name is hi
- The line is closed with a semi-colon.
Initialization
This is the next phase of the variable’s life cycle, and it is at this point that a value is assigned to the variable. This is the phase of initialization.
To initialize a variable,
- type the variable’s name and the equal sign (=).
- type the value you want to assign to the variable.
- close the line using a semicolon (;).
In the snapshot posted above, the integer variable hi was assigned a value of 10. The double variable hithere was assigned a value of 100.
Declaration with Initialization
Depending on the program and your style of coding, you can choose to initialize a variable when you declare it. It is totally acceptable in MQL4, so feel free to use this method. To declare and initialize a variable at the same time, just write the data type followed by a space, the variable name, an equal sign (=), the value, and a semicolon (;).
C. Expressions
Operations bear similarities to arithmetical operations such as plus, minus, multiplications and divisions. These are referred to as operation symbols or operators. When combined with variables in the same code line, they form expressions.
Here are the commonly used operation symbols in MQL4 code.
a) Arithmetic operators: plus, minus, percentage, division, multiplication (+ – % / *)
b) Logical operators: && ||
c) Assignment operators: Equal, plus equal, and multiplication equal (= += *=)
Expressions with a semi-colon (;) that ends the code line is an operator. So what expressions are of value to an MQL4 programmer?
Arithmetic operators are used to perform mathematical calculations on numerical values. Here is what the arithmetic operators look like.
The ++ operator tells the code to increase the value of b in line 27 by 1, so if b = 70, the code will assign a value of 70 + 1 or 71 whenever b++ appears. Similarly, the – – operator tells the code to reduce the value of b in line 28 by 1, so the code will assign a value of 69 when bb- – appears.
Here is another example of the expression of an arithmetic operator:
The ‘#include <math.mqh>’ directive instructs the code to enable the Math library functions to be used so there is no error when the code is compiled. The Math library functions seen here are MathPow() and MathSqrt().
So, what do each of the arithmetic operators mean?
- Addition (+): used to add the numerical values located to the left and right of the operator.
- Subtraction (-): used to subtract the numerical value on the right side of the operator from the numerical value on the left side of the operator
- Multiplication (*): used to multiply the values on the left and right sides of the operator.
- Division (/): used to divide the numeric value on the left of the operator by the numeric value on the right side of the operator.
- Modulus (%): returns the remainder of the division of the value on the left of the operator by the value on the right.
This is how they look in the MQL4 coding environment.
10 can be divided by 5 exactly two times with no remainder, so 10 % 5 will be 0 in line 23.
Assignment operators are used to give a value to a variable. Here is the meaning of the various assignment operators (= += -= *=)
- Assignment (=): assigns the value on the operator’s right side to the variable on the operator’s left.
- Addition assignment (+=): adds the value on the operator’s right to the variable’s value on the left, then assigns the result of this addition to the variable on the left to give it a new value.
- Subtraction assignment (-=): subtracts the value on the operator’s right from the variable’s value on the left, then assigns the result of this subtraction to the variable on the left to give it a new value.
- Multiplication assignment (*=): multiplies the value on the operator’s right by the variable’s value on the left side, then assigns the result of this multiplication to the variable on the left to give it a new value.
- Division assignment (/=): divides the value of the variable on the left by the value on the right side of the operator, then assigns the result to the variable on the left.
- Modulus assignment (%=): calculates the modulus of the value of the variable on the left and the value on the right of the operator, and assigns the result to the variable on the left.
Here are some examples of how the assignment operators can be used in MQL4:
D. Conditional operators (if/else, switch)
Conditional operators are used to perform functions that depend on whether another function’s parameters have been met. So, a conditional operator allows us to perform an action if another action is true.
In MT4, the conditional operators are the “if-else” and “switch” statements. They are both used to regulate how codes based on conditions are executed.
If-else statement
The “if-else” statement is typically used if multiple conditions in the code have to be checked,
If this script is compiled and run, it will print 10 because the condition is true. If you need to execute this condition multiple times in the code, you can change the brackets to curly brackets.
In the environment of the markets, the if-else statement is used in determining how the code works out the price variables.
Here is a sample of how the if-else condition works. Here, the variable “price” takes the value of the market ask price by default. The “if” component of the statement checks if the price is greater than 1.0. If yes, only the code within the first curly brackets will be executed. If not, (i.e. price < or = 1.), the only code which will run is the one within the second curly brackets.
//+--------------------------------------------------------+
//| Script program start function |
//+--------------------------------------------------------+
void OnStart(){
double price = Bid;
if (price > 1.0) {
// Execute this code if price is greater than 1.0
Alert("Price is above 1.0");
}else if (price < 0.5) {
// Execute this code if price is less than 0.5
Alert("Price is below 0.5");
}else {
// Execute this code if price is between 0.5 and 1.0
Alert("Price is between 0.5 and 1.0");
}
}
You can also create another “if-else” statement within an existing if-else statement, i.e. within the curly brackets of either the existing “if” or “else” blocks. This is called a nested if-else statement. A sample is shown below:
The nested if-else statement asks the code to check if the price is < 0.8 or lies between 0.8 and the target. If the price lies below 0.8, the code within the nested if statement runs. If no, the else statement of the nested code will run.
Conditional operators can be deployed in trade situations to handle pending entry orders and exit orders. These are the Buy Limit/ Sell Limit orders, Buy Stop/Sell Stop orders, and Take Profit/Stop Loss orders. If you notice, these are orders that can only be executed if certain price parameters are met (a condition). If the conditions are not met, they are not executed. Here is how the code for the trade entry conditionals would be written in the MQL4 environment.
Buy Stop
To place a buy-stop order at a specific price level, the following code can be used; The code asks the forex trading robot to do the following:
– execute a BUY STOP order at a stop distance of 10 pips from the current price, with a limit distance of 20 pips.
– use a Standard Lot (1.0 lots) as trade size.
– apply a green line to the order entry price on the chart for easy visualization.
– assign a unique identifier number to this trade.
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
double StopDistance = 10.0; // Stop distance in pips
double LimitDistance = 20.0; // Limit distance in pips
double Lots = 1.0; // Lot size
int Slippage = 3; // Maximum price deviation
int MagicNumber = 12345; // Unique identifier
color Green = Lime; // Order line color
// Get the current ask price
double price = Ask;
// Calculate the stop and limit prices
double stopPrice = NormalizeDouble(price + StopDistance * Point, Digits);
double limitPrice = NormalizeDouble(price + LimitDistance * Point, Digits);
// Place the buy stop order
int ticket = OrderSend(Symbol(), OP_BUYSTOP, Lots, stopPrice, Slippage, limitPrice, 0, "", MagicNumber, 0, Green);
if(ticket > 0)
{
Print("Buy stop order placed successfully with ticket #", ticket);
}
else
{
Print("Error placing buy stop order. Error code:", GetLastError());
}
}
The code defines the following variables:
- StopDistance
- LimitDistance
- Lots
- Slippage
- MagicNumber
- Green
Once the order is placed, the code will check for successful execution using the OrderSend() function’s return value (ticket). If the Buy Stop order is successfully filled, the code will print a message to the MT4 Journal tab. If not, the code will print an error message with the error code.
Sell Limit
To place a sell limit order at a specific price level, the following code can be used:
// Define order parametersdouble lotSize = 0.1; // Lot sizedouble limitPrice = 1.2000; // Limit pricedouble stopLoss = 1.2100; // Stop lossdouble takeProfit = 1.1900; // Take profitint slippage = 3; // Maximum deviation in pips from the requested price // Place sell limit orderbool sellLimitOrderPlaced = false;int ticket = 0;while (!sellLimitOrderPlaced) { ticket = OrderSend(Symbol(), OP_SELLLIMIT, lotSize, limitPrice, slippage, stopLoss, takeProfit, “Sell Limit”, MagicNumber, 0, Red); if (ticket > 0) { sellLimitOrderPlaced = true; } else { Print(“Sell limit order failed with error code “, GetLastError()); Sleep(5000); // Wait for 5 seconds before retrying }} // Check if the order is still openwhile (OrderSelect(ticket, SELECT_BY_TICKET)) { if (OrderCloseTime() > 0) { // Order has been closed break; } // Wait for 1 second before checking again Sleep(1000);} |
Stop Loss
This is how the forex trading robot would be asked to set a stop loss for a trade. Setting the stop loss can be tricky. Some programmers would want the code to set the stop loss only when the order is active. In this case, the code would be to modify the stop loss.
In this code, the EA has been asked to create a pending order and then modify the stop loss when the order has been executed.
// Define order parametersdouble lotSize = 0.1; // Lot sizedouble limitPrice = 1.2000; // Limit pricedouble stopLoss = 1.2100; // Stop lossdouble takeProfit = 1.1900; // Take profit // Place the pending orderint ticket = OrderSend(Symbol(), OP_SELLLIMIT, lotSize, limitPrice, 0, stopLoss, takeProfit, “Sell Limit”, MagicNumber, 0, Red);if (ticket <= 0) { Print(“Failed to place pending order with error code “, GetLastError());} else { Print(“Pending order placed with ticket number “, ticket);} // Modify the stop loss for the pending orderif (OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES)) { double newStopLoss = 1.2050; // New stop loss value if (!OrderModify(ticket, OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, Green)) { Print(“Failed to set stop loss for pending order with error code “, GetLastError()); } else { Print(“Stop loss set for pending order with ticket number “, ticket); }} else { Print(“Failed to select pending order with ticket number “, ticket, ” with error code “, GetLastError());} |
The variables in the code are seen clearly:
- the lot size is 1 mini lot (0.1 lots)
- The limit price is 1.2000
- Stop loss is 1.2100
- The take profit is 1.1900
The code has also asked to print any error codes to the journal if the stop loss cannot be modified. The pending order is placed using the OrderSend function, using the variables above as the desired parameters.
If the order goes through, the code asks the Forex trading robot to use the OrderSelect function (which contains the ticket number for identification). The MODE_TRADES function asks the robot to select open and pending orders for this action.
You can also use the OrderModify function to change order parameters, and the newStopLoss function to change the stop loss.
Please note you must know the rules regarding how many times you can change these parameters with your broker when you set the variables.
Take Profit
You may also decide to set a Take Profit order using a different code if you do not set it along with the stop loss as shown above. You can use the following code:
void OnTick() {// Set take profit leveldouble takeProfit = 1.5; // Take profit level as a multiple of the trade’s open pricedouble stopLoss = 1.0; // Stop loss level as a multiple of the trade’s open price // Place trade with take profit and stop loss levelsint ticket = OrderSend(Symbol(), OP_BUY, 1.0, Ask, 3, Bid – stopLoss * Point, Bid + takeProfit * Point, “My Order”, MagicNumber, 0, Blue); } |
This code has opted to use a risk-reward setting of 1:1.5 to set both the stop loss and take profit price targets. So the TP here is 1.5 times the entry price. Again, the OrderSend function places the trade, and the stopLoss and takeProfit variables are defined.
Switch
while the “switch” statement is used when there are multiple possible values for a variable to be compared against. Here is an example of how to use the “if-else” and “switch” statements in MT4:
double price = Bid;int tradeType = 2; // 0 = buy, 1 = sell, 2 = do nothing // if-else statementif (price > 1.0) { tradeType = 0;}else if (price < 0.5) { tradeType = 1;} // switch statementswitch (tradeType) { case 0: // Execute this code if tradeType is 0 (buy) OrderSend(Symbol(), OP_BUY, 0.1, price, 0, 0, 0, “Buy order”, 0, 0, Green); break; case 1: // Execute this code if tradeType is 1 (sell) OrderSend(Symbol(), OP_SELL, 0.1, price, 0, 0, 0, “Sell order”, 0, 0, Red); break; default: // Execute this code if tradeType is not 0 or 1 (do nothing) break;} |
The if/else statement requires the code to check and execute from the price standpoint.
- If the price > 1.0, the tradeType variable = 0 -> BUY.
- If the price variable < 0.5, the tradeType variable = 1 -> SELL.
- If the price is at current bid price (default setting), tradeType = 2 -> NO ACTION.
When using the switch statement, things are a bit different. The code will focus attention on the tradeType variable.
- If the tradeType = 0, -> BUY at price level set in the code.
- If the tradeType = 1, -> SELL at price
- If the tradeType = 2, -> NO ACTION
Follow these guides to learn how to install your forex robot on your trading terminals:
How to Install a Forex Trading Bot in MT4
How to Install a Forex Trading Bot in MT5
Conclusion
In conclusion, this module has looked at the different types of resources that make up the typical code of a Forex robot. You have been shown the types of code that can be done in MQL4 (forex trading robot, indicators, and scripts) and the various code formats that form components of the code of a forex robot. We have also looked at the various forms of code required for a Forex robot, indicator and script within the MQL4 environment. You now must have some idea about comments and identifiers, which are components of the coding syntax.
The core content of this module requires a lot of work and practice to perfect. We hope that the information here has helped you understand what goes into the coding of a Forex robot. Would you like to know more? Check out these comprehensive algorithmic trading courses