What is MQL4 and How to use it in Forex Trading

The forex market is fast-paced and often requires making multiple decisions simultaneously. Fortunately, there’s MQL4 to make everything a whole lot easier. But what exactly is MQL4 and how do you use it in forex?

MetaQuotes Language 4 (MQL4) is a programming language that allows you to create technical indicators, scripts, function libraries, and trading robots (expert advisors) for use on the MetaTrader 4 (MT4) platform. The language essentially allows you to build your own algorithmic trading software.

Keeping up with all the action in the forex market is no easy task. However, an algorithmic trading system can simplify your decision-making process and give you an edge. This article will take you through what MQL4 is, how it works, and how you can use it in your forex trading.

Table of Contents

Why you should learn MQL4

Knowing how MQL4 works gives you a good understanding of how to automate or make more efficient certain aspects of your trading. This means that you can create a system that’s customized to your specific needs.

Importance and benefits of MQL4 and learning algorithmic trading

MQL4 is a powerful tool, which if used properly, can expand your trading capabilities. Let’s take a look at more advantages of MQL4 and algorithmic trading.

  • The psychological advantage. An algorithmic trading system encourages a systematic pattern of trading. This not only helps with keeping your emotions in check, but it also preserves your discipline and helps you achieve trading consistency.
  • The ability to backtest your strategy. An automated trading system is based on a precise set of rules. You can take these rules and test them on historical data. This way, you can evaluate and fine-tune your trading strategy before risking real capital.
  • Improved speed. Computer programs can respond immediately to changing market conditions. In forex trading, a few seconds can be the difference between a winning trade and a loss. An automated system can help you keep up in the dynamic forex market.
  • Optimization of opportunities. An automated system can run multiple strategies, putting you in a better position to identify excellent opportunities. It also allows you to take a break from your trading screen, giving you time to discover other markets or formulate new strategies.

An automated system has clear merit, but manual trading still exists for a reason.

Automated Trading vs. Manual Trading: getting the best of both worlds

Automated trading promises efficiency and opportunities, but a computer doesn’t have a brain.

A computer can only execute programmed scenarios. Conversely, a human can take into account everything that is happening. For instance, a human can get a feel for the market and they can also account for unexpected events or awkward movements in the market. 

There’s also the issue of automated systems being fallible. The systems still require some monitoring since they are susceptible to mechanical failures. 

Both manual and automated trading have their benefits and drawbacks. To get the best of both worlds, you can opt for a semi-automated forex system. This type of system analyses the market for trading opportunities but leaves you to decide whether to trade.

With semi-automated trading, you can combine your intelligence and experience with the analytical capabilities of an automated system. Nonetheless, a semi-automated system will require some coding, so you will need to know how MQL4 works.

How does MQL4 work?

MQL4 is based on the concepts of the C++ programming language. As such, it uses many C++ concepts such as object-oriented programming (OOP).

The programming language executes different applications according to the rules set for a certain type of program (e.g. trade management or market analysis). You can create and execute three types of applications in MQL4 – scripts, custom indicators, and expert advisors.

Scripts are for analyzing relatively simple yet frequently used actions such as closing orders or deleting objects from a chart. Custom indicators are market analysis tools. Lastly, we have expert advisors.

What are Expert Advisors in MQL4?

An expert advisor (EA) in MQL4 is a program that’s built using the language’s algorithms to monitor and trade the markets. An EA identifies opportunities in the market according to the specific parameters you set. When it finds an opportunity, it either notifies you or opens a position automatically.

The platform you use to create, edit, and compile your expert advisors, indicators, and scripts in the MQL4 language comes directly with MT4. It’s called MetaEditor.

MetaEditor Overview

To access MetaEditor, select the MetaEditor icon located on the top toolbar in MT4:

MetaEditor button

You can also select MetaQuotes Language Editor under the Tools menu:

MetaEditor can be broken down into five parts:

  1. The top toolbars house the traditional program menu.
  2. The Navigator window allows you to navigate through the file structure in the MQL4 directories.
  3. The program-writing editor is where you write and edit any active programs.
  4. The toolbox is a multifunctional window showing everything from errors, search results, and the program log to the latest MQL community articles and programs.
  5. The status bar contains program command prompts, information on the current cursor location, and the text input mode indicator (INS/OVR).

Once you’re familiar with this setup, you can start some programming.

MQL4 Core Programming

Your MQL4 core programming will involve two fundamental elements – variables and functions. Let’s start with the former.

You can think of variables as containers used for labeling and holding information in computer memory. A variable holds the value assigned to it for use in a computer program.

Types of Variables

An MQL4 program can contain many variables, but you can group them according to which part of code will know a certain variable and can use it in a program. This is known as scope. There are two scopes of variables in MQL4, local and global.

A local variable is one declared within a function. This type of variable is limited to the range of the function in which it’s declared and so it’s invisible to the other functions in your program.

On the other hand, a global variable is one declared outside all functions. The scope of a global variable is the entire program and so the variable is visible from any part of your code. 

Using Variables

When you create a variable, you’re essentially telling the computer to store data. To ensure that the program knows what kind of data to store and what data belongs to which variable, you must always declare a variable before using it.

Declaring a variable is known as declaration and you do it by specifying the variable’s data type and unique name. The data type is specified with a keyword and the unique name is called the variable constant.

When you set the value of a variable in the same line you specified the keyword and variable constant, the process is known as initialization.

Specifying the data type is important. MQL4 uses the following data types to denote the values of variables, constants, and the values returned by functions in a program. 

Integers (int)

Integers are positive and negative whole numbers. MQL4 presents integers in either decimal or hexadecimal format and they range from -2,147,483,648 to 2,147,483,647. If you input any variable value beyond this range, the result will be void.

The keyword for creating an integer variable or constant in a program is int.

MQL4 integers

Floating-point numbers (double)

Floating-point numbers are real numbers comprising an integer and a fractional part separated by a decimal point. The digits 0-9 represent both the integer and fractional parts and the fraction part can have up to 15 significant figures. Values of this type range from -1.7*e-308 to 1.7*e308 and the keyword for creating them is double.

MQL4 double variable

Boolean values (bool)

The Boolean data type can only hold two values, true and false or the numeric representation 1 and 0 respectively. The keyword for creating boolean variables is bool.

Note: In MQL4, the boolean values “true and false” can be written in sentence, upper, or lower case. This means false, False, FALSE are equal as are true, True, and TRUE.

Values of string type (string)

A set of ASCII characters enclosed in double quotes represents the string data type, for example, “Stop Loss”. The keyword for creating a string variable is string.

You can only write a string variable up to 255 characters. Anything above this will generate the error (too long string (255 characters maximum)).

Values of color type (color)

The value of a color data type is a color and it’s represented in any one of the following ways: color names, literal representations, or integer representations. The keyword for color is color.

Values of date and time (datetime)

The datetime data type is used to create date and time variables. The date and time can be denoted by a six-part line representing the numeric values of day, month, year (or year, month, day), hour, minute, and second. The data type starts with “D” and it is quoted by single quotes.

The keyword for creating a datetime variable is datetime.

In addition to variables, operations are also a big part of MQL4 core programming. It’s easy to think of the different parts operations this way; an operation is an action made on an operand using an operator. At this stage, it’s enough to think of an operand as either a constant or a variable. 

There are various types of operations in MQL4 but here we’ll take a look at logical operations. In forex trading, these operations will allow us to make decisions based on certain conditions. Logical operations are also known as boolean operations in MQL4. 

Boolean Operations and Variables

As mentioned earlier, boolean variables hold only two values, true and false. Similarly, boolean operations result in one of these two results based on the following three operators: NOT, OR, and AND. 

Before you can fully appreciate how boolean operations work, it’s important to first understand relational operations. This is because relational operators and logical operators are usually used together in logic expressions. There are six relational operators in MQL4.

MQL4 operators table

With this in mind, here’s how each boolean operation works.

NOT (!)

The NOT operation is TRUE (1), if the value of the operand is “NOT” true i.e. FALSE (0). Simply put, it’s TRUE if the argument is FALSE, otherwise, it’s FALSE. 

OR (ǁ)

The expression value of an OR operation is TRUE (1), if either the left-hand or right-hand operand value is true. Otherwise, it’s FALSE.

AND (&&)

The expression value of an AND operation is TRUE (1) if the values of both the left-hand and right-hand operands are TRUE, otherwise it’s false.

Putting together all these different elements of MQL4 programming creates the need for something to control the flow of your program. In MQL4, you use statements to make the flow of the program jump from one part to another. These statements consist of what are called loops and decisions. 

Loops cause a certain section of your program to repeat until some condition becomes false. There are two kinds of loops in MQL4, the “for” loop and the “while” loop.

The “For” Loop

The “for” loop executes a section of code a fixed number of times.

For example:

You can also declare the loop variable (int i) inside the parentheses of the “for” loop.

In a “for” loop, the “for” statement has the “for” keyword followed by parentheses containing three expressions separated by semicolons:

  • The initialization expression (i=0). This expression gives the loop variable an initial value (0 in our example) and it’s executed once when the loop first starts.
  • The test expression (i<10). This expression always uses relational operators and it evaluates the conditions of the loop termination to determine if the loop will continue or stop. When the loop becomes false it’s terminated.

In our example, the body loop, which is the code that’s executed a fixed number of times, will continue printing i (Print(i)) while i<10 is true. This means Print (i) executes the body of the loop 10 times (from 0 to 9) and when it reaches 10, the loop stops and passes control to the next operator.

  • The increment expression (i++). This expression allows for increments that are supposed to occur at the end of each loop iteration. It changes the value of the loop variable (i in our example) by increasing its value by 1.

Here’s a “for” loop flow chart.

The “While” Loop

You use the “while” loop when you don’t know how many times a loop will be executed. The “while” loop doesn’t have the initialization or increment expressions, it only has the test expression.

For example:

while loop in MQL4

The test expression is examined in every loop. If it’s true, the loop continues, otherwise it ends and control passes to the next operator. In the example, the loop will execute until it reaches 11. In this case, i<10 becomes false and the loop ends.

For the “while” loop, the i++ statement is not an increment expression. It’s there to change the loop variable otherwise the loop would never end.

Note: The loop variable is declared and initialized before the loop. You can’t declare or initialize the loop variable inside the parentheses of the “while” loop like you can do with the “for” loop. 

Here’s a “while” loop flow chart:

As we mentioned previously, besides loops, decisions also change the flow of a program. Decisions cause a one-time jump to another part of a program depending on the value of an expression. MQL4 has the following types of decision statements.

The “If” Statement

The “if” statement is the simplest decision statement. This is how it’s set up:

if statement in MQL4

The keyword is if and the test expression is inside the parentheses. If the test expression is true, the body of the statement executes the operator. If it’s false, control will pass on to the next operator.

In the example, if the result of the test expression is greater than 25, the body of the “if” will execute (Print(“Hello”);).

The “Else” Statement

While the “if” statement is executed if a specified condition is true, the “else” statement is executed if that specified condition is false.

The else statement has no test expression and it’s normally used in an “if else” construction.

The “Else If” Statement

The “else if” statement is executed if a condition is false but another condition is true. Else if basically allows you to say “ if the previous condition wasn’t true, then if this condition is true…”

Here’s a sample of how the three decision statements can connect:

MQL4 else if statement

The “Switch” Operator

A switch statement is useful when you have a large decision tree and all the decisions depend on the value of the same variable. The switch statement compares the expression value with constants in the different case variants and passes control to the one that corresponds with the expression value.

If none of the constants are equal to the expression value, the operators marked by the default label are executed. No actions are executed if none of the constants correspond to the expression value and there’s no default variant.

The constants are found inside the parentheses after the switch keyword. A constant can be an integer, a character constant, or a constant expression. However, a constant expression can’t include a variable. For example, x + y is an invalid switch constant.

In the example, the switch statement matches the constant x with one of the case constants.

Here’s a flow chart:

Now, let’s have a look at functions.

MQL4 Functions

A function is a section of a program that performs a specific action. It’s defined by function parameters, a function body, and a function return value.

The function starts with the type of the returned value. This is followed by the function name and parentheses. Inside the parentheses are the function parameters then the function body starts and ends with braces.

The return keyword is responsible for returning the final result and terminating the function.

Note: Not all functions use the return keyword, especially when there’s no return value. A function without a return value is of “void” type.

Functions play an important role in automated forex trading and MQL4 has a group of 25 trading functions for managing trading activities. The following are the functions for opening, closing, and modifying your orders.

OrderSend

OrderSend is the main function used to open a position or place a pending order. It returns the ticket number if the order is successful and -1 if it fails. OrderSend takes 11 parameters.

Here’s a description of the parameters:

For instance, here’s an example of a simple script for opening a Buy order:

OrderClose

The OrderClose function is used to close a specific opened order by its ticket. It examines a pool of open orders, looking for a matching symbol and other order types (OP_SELL or OP_BUY)

The function returns true if the order is successful and false it if fails. OrderClose takes five parameters.

Here’s a description of the parameters:

For example, if the ticket number of your order BUY (long) is 95790 and you want to close 0.6 lots, the call to the function closing this order may look like this:

OrderModify

The OrderModify function is used to modify the properties of a specific open or pending order. It returns true if the order is successful, otherwise, it returns false. The function takes six parameters.

This is the description of the parameters.

Here’s an example of how you would use the OrderModify function based on a price condition:

OrderSelect

Once you have placed an order, you will want to gather information about the order, especially if you want to modify it. This is where the OrderSelect function comes in.

 

The OrderSelect function lets you select an open or pending order using its ticket number or by index. It returns true if the order is successful or false if the order fails. The function takes three parameters.

 

Here’s the description of the parameters:

Here is an example using OrderSelect to get the status of an order:

Coding your first EA in MQL4

Here is a short tutorial so that you can start building your own Expert Advisor

Exclusive Bonus

Learning MQL4 can be rewarding, but it’s important to remember that success lies in understanding what’s going on. There can be no rewards without sufficient understanding so get started, make sure you understand the different concepts as you go, and keep learning.

Here is an exclusive discount if you wish to get started into MQL4, Algorithmic Trading and code your first Forex Robot:

Algorithmic Trading Course

Related Questions

The following are some additional questions related to MQL4.

Can I code indicators using MQL4?

Creating technical indicators is one of the things you can do with MQL4, so yes, you can code indicators using MQL4. Once you have coded a custom indicator, you can use it within the charting software or program it inside your EA.

What is the difference between MQL4 and MQL5?

MQL4 and MQL5 may both be c-based languages, but MQL5 is an OOP or object-oriented program.

MQL5 is more complex, giving traders more advanced features and more room for advanced commands and calculations. For example, MQL5 allows multi-currency pair backtesting, but MQL4 doesn’t. 

However, this means that MQL4 is more suited to beginners due to its simplicity. Learn more about the differences between MQL4 and MQL5 in this article

Is MQL4 hard to learn?

If you have any programming knowledge, especially in C or C++, you will probably find it relatively easy to learn MQL4. If you’re an absolute beginner, learning MQL4 is still possible, albeit with a more significant learning curve. Understanding the language should become easier with practice.

Can an MT4 EA run on MT5?

Technically, an MT4 EA can’t run on MT5 because the EAs because their programming languages are not directly compatible – an MT4 EA uses MQL4 while an MT5 EA uses MQL5. Nonetheless, with some modifications to an existing MQL4 source file, an MT4 EA can work on MT5. Do keep in mind that you will need to have good knowledge of the differences between MQL4 and MQL5 before you attempt any modifications.

What are you waiting for?

START LEARNING FOREX TODAY!

share This:
Muhammad Awais

Leave a Reply

Your email address will not be published. Required fields are marked *

What are you waiting for?

START LEARNING FOREX TODAY!

as seen on: