Welcome to the MQL4 course.
In this series, I will try to strip the mystique and confusion from MQL4 by giving you comprehensive tutorials with a straight forward example.
In this series of lessons, I will show you how to use the MQL4 for building your own Expert Advisors, Custom Indicators and Scripts.

If you are programming in C (or its superset C++) then you know a lot of MQL4 before even I start my lessons, if you didn’t write in any programming language before, no problem, I’ll guide you to understand the concept of programming in general as well.
So, let’s start from the beginning.
MQL4? What, Why and Where?
MQL4 stands for MetaQuotes Language 4.
MetaQuotes is the company who built the MetaTrader Trading Platform.
And to make it stronger than the other trading platforms the company extended it by a built-in programming language that enables the user (you) to write his own trading strategies.
The language enables you to create one of the following:
1- Expert Advisors.
2- Custom Indicators.
3- Scripts.
• Expert Advisor is a program which can automate trading deals for you. For example it can automate your market orders, stops orders automatically, cancels/replaces orders and takes your profit.
• Custom Indicator is a program which enables you to use the functions of the technical indicators and it cannot automate your deals.
• Script is a program designed for single function execution. Unlike the Advisor, scripts are being held only once (on demand), and not by ticks. And of course has no access to indicator functions.
These were “What” MQL4 is? “Why” to use MQL4?
Now, “Where” do I write MQL4?
To write your MQL4 code and as anything else in world, you can choose one of two ways, the hard way and the easy way.
1- The hard way:
The hard way is using your favorite text editor and the command prompt to compile your program.
Notepad is not bad choice, but do not forget two things:
1- To save the file you have created in plain text format.
2- To save the file as .mp4 (that’s to be easy to reopen it with MetaEditor), but you can save it as any extension you prefer.
After saving your program there is an extra step to make your code comes out to the light.
It’s the Compiling step.
Compiling means to convert the human readable script that you have just wrote to the machine language that your computer understands.
MetaTrader has been shipped with its own compiler (the program which will convert your script to the machine language) called MetaLang.exe.
Metalang.exe is a console program which takes two parameters and output an .ex4 file (the file which Metatrader understands).
The first parameter is “options” parameter and the only option available is –q quit
The second parameter is the full path to your .mql file.
The syntax will be in this format.
metalang [options…] filename
Example:
1- Find your metalang.exe path, it will be the same path of MetaTrader (here my path is D:\Program Files\MetaTrader 4).
2- Create a batch file and name it compile.bat (or any name you prefer).
3- Write these lines into the bat file then save it:
cd D:\Program Files\MetaTrader 4
metalang -q "D:\Program Files\MetaTrader 4\my_first_mql4_script.mq4"
(Don’t forget to change the path to you MetaTrader installed path).
4- Run the batch file and if you are lucky person like me you will get a screen like figure 1.
Figure 1 Metalang compiler
As you see you will get the output file “my_first_mql4_script.ex4”
2-The easy way:
Metatrader has been shipped with a good IDE (integrated development editor) called MetaEditor which has these features:
1- A text editor has the feature of highlighting different constructions of MQL4 language while you are writing/reading code.
2- Easy to compile your program, just click F5 and the MetaEditor will make all the hard work for you and produces the “ex4” file.
Besides it’s easy to see what the wrong in your program is (in the Error Tab – see figure 2).
3- Built-in a dictionary book which you can access by highlight the keyword you want to know further about it then press F1.

Figure 2 MetaEditor 4
In the coming lessons we will know more about MetaEditor.
Today I just came to say hello, tomorrow we will start the real works and will study the Syntax of MQL4.
I welcome very much the questions and the suggestions.
See you
Coders’ Guru
Hi folks,
We are talking today about the SYNTAX rules of MQL4.
And as I told you before, If you are programming in C (or its superset C++) then you know a lot of MQL4 before even I start my lessons.
That’s because the syntax of MQL4 is very like of the syntax of C.
The dictionary means of the word SYNTAX of a programming language is:
“The set of allowed reserved words and their parameters and the correct word order in the expression is called the syntax of language”. “Wikipedia”
So, when we are studying the syntax of the language we are studying its grammar and writing rules which consist of:
· Format
· Comments
· Identifiers
· Reserved words
Let’s slice the cake.
1- Format:
When you write your code, you can freely use any set of spaces, tabs and empty lines you want to separate your code and your line of code to make them readable and eyes pleasing.
For example all of these lines are valid in MQL4:
| double MacdCurrent, MacdPrevious, SignalCurrent; |
| double MacdCurrent, MacdPrevious, SignalCurrent; |
| double MacdCurrent, MacdPrevious, SignalCurrent; |
But, as you see, the first line is more readable and easy to understand.
And as everything in the world there are exceptions to the rule:
1- You can’t use new line in the “Controlling compilation”
You will know more about “Controlling compilation” in next lesson but just remember this is an exception.
For example the next line of code is invalid and the MQL4 compiler will complain:
| #property copyright "Copyright © 2004, MetaQuotes Software Corp." |
This is the valid “Controlling compilation”:
| #property copyright "Copyright © 2004, MetaQuotes Software Corp." |
2- You can’t use new line or space in the middle of Constant values, Identifiers or Keywords.
For example this line is valid:
| extern int MA_Period=13; |
“extren” and “int” here are Keywords , “MA_Period” is an Identifier and “13” is a Constant value..
You will know more in the next lessons.
For example the next lines are invalids:
| extern int MA_Period=1 3; |
| extern int MA_Period=1 3; |
Notice the tab between 1 and 3.
| ex tern int MA_Period=13; |
2- Comments:
To make the programming world easier, any programming language has its style of writing comments.
You use Comments to write lines in your code which the compiler will ignore then but it clears your code and makes it understandable.
Assume that you write a program in the summer and in the winter you want to read it. Without comments -even you are the code’s creator- you can’t understand all these puzzled lines.
MQL4 (& C/C++) uses two kinds of comments styles:
1- Single line comments
The Single line comment starts with “//” and ends with the new line.
For example:
| //This is a comment extern int MA_Period=13; |
| extern int MA_Period=13; //This is another comment |
2- Multi-line comments
The multi-line comment start with “/*” and ends with “*/”.
And you can comment more than line or more by putting “/*” at the start of the first line, and “*/” at the end of the last line.
For example:
| /* this is multi line comment*/ |
You can also nest single line comment inside multi lines comment like that:
| /* this is multi //another comment nested here. line comment*/ |
This is a valid comment too:
| extern int /*HELLO! I’m a comment*/ MA_Period=13; |
But this is invalid comment:
| extern int //test MA_Period=13; |
3- Identifiers:
An identifier is the name you choose to your variables, constants and functions.
For example MA_Period here is an identifier:
| extern int MA_Period=13; |
There are few rules and restrictions for choosing those names:
1- The length of the Identifier must not exceed 31 characters.
2- The Identifier must begin with a letter (capital or small) or the underlining symbol _.
So, it can’t be started with a number or another symbol except the underlining symbol.
3- You can’t use any reserved words as an Identifier.
You will see the list of the reserved words too soon.
4- The identifiers’ names are case sensitive.
So, MA_PERIOD not the same as ma_period or MA_Period
Let’s take some examples:
| Name1 Valid _Name1 Valid 1Name Invalid (don’t start with number) ~Name1 Invalid (you can only use underline symbol) N~ame1 Invalid (you can only use underline symbol) i_love_my_country_and_my_country_loves_all_the_world Invalid (you can’t exceed the 31 characters length) Color Valid color Invalid (you can’t use reversed word, and color is one of them) |
4- Reserved words:
There are “words” which the language uses them for specific actions.
So, they are reserved to the language usage and you can’t use them as an identifier name or for any other purpose.
This is the list of the reserved words (from the MQL4 guide):
| Data types | Memory classes | Operators | Other |
| bool | extern | Break | false |
| color | static | Case | true |
| datetime |
| continue |
|
| double |
| Default |
|
| int |
| Else |
|
| string |
| For |
|
| void |
| If |
|
|
|
| Return |
|
|
|
| Switch |
|
|
|
| While |
|
For example the next lines of code are invalid:
| extern int datetime =13; int extern =20; double continue = 0; |
What’s the Data type mean?
Any programming language has a set of names of the memory representation of the data.
For example if the memory holds numbers between -2147483648 to 2147483647, the most of the programming languages will name this data as “Integer” data type.
Variables?
Variables are the names that refer to sections of memory into which data can be stored.
To help you think of this as a picture, imagine that memory is a series of different size boxes. The box size is memory storage area required in bytes.
When we create a variable we are telling the computer that we want him to assign a specified memory length (in bytes) to our variable, since storing a simple number, a letter or a large number is not going to occupy the same space in memory, so the computer will ask us what’s the kind of data and how much the length of the data? That is the Data type for.
For example if we said this line of code to the computer:
| int MyVaraible=0; |
That’s mean we are asking the computer to set a block of 4 bytes length to our variable named “MyVaraiable”.
In the previous example we have used:
int ß Keyword
int ß Integer data type.
int ß Declaration
MyVaraible ß Variable’s constant.
=0 ß Initialization
We will know more about variables in a coming lesson.
In MQL4, these are the kinds of Data types:
An integer, is a number that can start with a + or a - sign and is made of digits. And its range value is between -2147483648 to 2147483647.
MQL4 presents the integer in decimal or hexadecimal format.
For example the next numbers are Integers:
| 12, 3, 2134, 0, -230 0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7 |
We use the keyword int to create an integer variable.
For example:
| int intInteger = 0; int intAnotherIntger = -100; int intHexIntger=0x12; |
Decimal notation is the writing of numbers in the base of 10, and uses digits (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9) to represent numbers. These digits are frequently used with a decimal point which indicates the start of a fractional part, and with one of the sign symbols + (plus) or − (minus) to indicate sign.
Hexadecimal is a numeral system with a base of 16 usually written using the symbols 0–9 and A–F or a–f.
For example, the decimal numeral 79 can be written as 4F in hexadecimal.
Boolean variable is a data type which can hold only two values, true and false (or their numeric representation, 0 and 1). And it occupies 1 bit of the memory.
In MQL4, false,FALSE,False,true,TRUE and True are equals.
Boolean named like this in the honor of the great mathematician Boole George.
We use the keyword bool to create a boolean variable.
For example:
| bool I = true; bool bFlag = 1; bool bBool=FALSE; |
3- Character
MQL4 names this Data type “Literal”.
A character is one of 256 defined alphabetic, numeric, and special key elements
defined in the ASCII (American Standard Code for Information Interchange) set.
Characters have integer values corresponding to location in the ASCII set.
You write the character constant by using single quotes (') surrounding the character.
For example:
| 'a' , '$' , 'Z' |
We use the keyword int to create a character variable.
For example:
| int chrA = 'A'; int chrB = '$'; |
Some characters called Special Characters can’t present directly inside the single quotes because they have a reserved meanings in MQL4 language.
Here we use something called Escape Sequence to present those special characters,
And that by prefixing the character with the backslash character (\).
For example:
| int chrA = '\\'; //slash character int chrB = '\n'; //new line |
This is the list of Escape Sequence characters used in MQL4.
| carriage return \r new line \n horizontal tab \t reverse slash \\ single quote \' double quote \" hexadecimal ASCII-code \xhh |
The string data type is an array of characters enclosed in double quote (").
The array of characters is an array which holds one character after another, starting at index 0. After the last character of data, a NULL character is placed in the next array location. It does not matter if there are unused array locations after that.
A NULL character is a special character (represented by the ASCII code 0) used to mark the end of this type of string.
See figure 1 for a simple representation of the string constant “hello” in the characters array.
Figure 1 – Characters array
MQL4 limits the size of the string variable to 255 characters and any character above 255 characters will generate this error: (too long string (255 characters maximum)).
You can use any special character -mentioned above- in your string constant by prefixing it with the backslash (\).
We use the keyword string to create a string variable.
For example:
| string str1 = "Hello world1, with you coders guru”; string str2 = "Copyright © 2005, \"Forex-tsd forum\"."; //Notice the use of (") character. string str3 = "1234567890"; |
5- Floating-point number (double)
Floating point number is the Real Number (that is, a number that can contain a fractional part beside the integer part separated with (.) dot).Ex: 3.0,-115.5, 15 and 0.0001.
And its range value is between 2.2e-308 to 1.8e308.
We use the keyword double to create a floating-point variable.
For example:
| double dblNumber1 = 1000000000000000; double dblNumber3 = 1/4; double dblNumber3 = 5.75; |
6- Color
Color data type is a special MQL4 data type, which holds a color appears on the MetaTrader chart when you create your own Expert Advisor or Custom Indictor and the user can change it from the property tab of your Expert Advisor or Custom Indictor.
You can set the Color variable constant in three ways:
1- By the color name: For the well know colors (called Web Colors Set) you can assign the name of the color to the color variable, see the list of the Web Colors Set.
2- By Character representation (MQL4 named it this name): In this method you use the keyword (C) followed by two signal quotations ('). Between the two signal quotations you set the value of the red, green and blue (know as RGB value of the color). These values have to be between: 0 to 255. And you can write these values in decimal or hexadecimal format.
3- By the integer value: Every color in the Web Colors Set has its integer value which you can write it in decimal or hexadecimal format. And you can assign the Integer value of the color to the color variable. The hexadecimal color format looks like this: 0xBBGGRR where BB is the blue value, GG is green value and RR is the red value.
For example:
| // symbol constants C'128,128,128' // gray C'0x00,0x00,0xFF' // blue // named color Red Yellow Black // integer-valued representation 0xFFFFFF // white 16777215 // white 0x008000 // green 32768 // green |
We use the keyword color to create a color variable.
For example:
| color clr1= Red; color clr1= C'128,128,128' ; color clr1=32768; |
Web Colors Set
| Black | DarkGreen | DarkSlateGray | Olive | Green | Teal | Navy | Purple |
| Maroon | Indigo | MidnightBlue | DarkBlue | DarkOliveGreen | SaddleBrown | ForestGreen | OliveDrab |
| SeaGreen | DarkGoldenrod | DarkSlateBlue | Sienna | MediumBlue | Brown | DarkTurquoise | DimGray |
| LightSeaGreen | DarkViolet | FireBrick | MediumVioletRed | MediumSeaGreen | Chocolate | Crimson | SteelBlue |
| Goldenrod | MediumSpringGreen | LawnGreen | CadetBlue | DarkOrchid | YellowGreen | LimeGreen | OrangeRed |
| DarkOrange | Orange | Gold | Yellow | Chartreuse | Lime | SpringGreen | Aqua |
| DeepSkyBlue | Blue | Magenta | Red | Gray | SlateGray | Peru | BlueViolet |
| LightSlateGray | DeepPink | MediumTurquoise | DodgerBlue | Turquoise | RoyalBlue | SlateBlue | DarkKhaki |
| IndianRed | MediumOrchid | GreenYellow | MediumAquamarine | DarkSeaGreen | Tomato | RosyBrown | Orchid |
| MediumPurple | PaleVioletRed | Coral | CornflowerBlue | DarkGray | SandyBrown | MediumSlateBlue | Tan |
| DarkSalmon | BurlyWood | HotPink | Salmon | Violet | LightCoral | SkyBlue | LightSalmon |
| Plum | Khaki | LightGreen | Aquamarine | Silver | LightSkyBlue | LightSteelBlue | LightBlue |
| PaleGreen | Thistle | PowderBlue | PaleGoldenrod | PaleTurquoise | LightGrey | Wheat | NavajoWhite |
| Moccasin | LightPink | Gainsboro | PeachPuff | Pink | Bisque | LightGoldenRod | BlanchedAlmond |
| LemonChiffon | Beige | AntiqueWhite | PapayaWhip | Cornsilk | LightYellow | LightCyan | Linen |
| Lavender | MistyRose | OldLace | WhiteSmoke | Seashell | Ivory | Honeydew | AliceBlue |
| LavenderBlush | MintCream | Snow | White |
|
|
|
|
Datetime data type is a special MQL4 data type, which holds a date and time data. You set the Datetime variable by using the keyword (D) followed by two signal quotations ('). Between the two signal quotations you write a character line consisting of 6 parts for value of year, month, date, hour, minutes, and seconds. Datetime constant can vary from Jan 1, 1970 to Dec 31, 2037.
For example:
| D'2004.01.01 00:00' // New Year D'1980.07.19 12:30:27' D'19.07.1980 12:30:27' D'19.07.1980 12' //equal to D'1980.07.19 12:00:00' D'01.01.2004' //equal to D'01.01.2004 00:00:00' |
We use the keyword datetime to create a datetime variable.
For example:
| datetime dtMyBirthDay= D'1972.10.19 12:00:00'; datetime dt1= D'2005.10.22 04:30:00'; |
What’s the meaning of Operations & Expressions?
You know the operations very well. If I told you that (+,-,*, /) are the basic arithmetical operators, you will remember very fast what’s the operator means.
I hear you saying “OK, I know the operations; could you tell me what’s the meaning of the expression?”
Identifiers (do you remember them? If not, Review the SYNTAX lesson) together with the Operations produce the Expressions.
Puzzled? Let’s illustrate it in an example:
| x = (y*z)/w; |
x,y,z and w, here are identifiers.
=,* and / are the operators.
The whole line is an expression.
When the expressions combined together it makes a statement.
And when the statements combined together it makes a function and when the functions combined together it makes a program.
In the remaining of this lesson we are going to talk about the kinds operators used in MQL4.
So, let’s start with the basic arithmetical operators:
1- Arithmetical operators:
In MQL4 there are 9 Arithmetical operations
This is the list of them with the usage of each:
| Operator | Name | Example | Description |
| + | Addition operator | A = B + C; | Add A to B and assign the result to C. |
| - | Subtraction operator | A = B - C; | Subtract C from B and assign the result to C. |
| + - | Sign changer operators | A = -A; | Change the sign of A from positive to negative. |
| * | Multiplication operator | A = B * C; | Multiply B and C and assign the result to A. |
| / | Division operator | A = B / C; | Divide B on C and assign the result to A. |
| % | Modulus operator | A =A % C; | A is the reminder of division of B on C. (ex: 10%2 will produce 0, 10%3 will produce 1). |
| ++ | Increment operator | A++; | Increase A by 1 (ex: if A =1 make it 2). |
| -- | Decrement operator | A--; | Decrease 1 from A (ex: if A =2 make it 1). |
Note: You can’t combine the increment and decrement operator with other expressions.
For example you can’t say:
| A=(B++)*5; |
But you can write it like that:
| A++; B=A*5; |
2- Assignment operators:
The purpose of any expression is producing a result and the assignment operators setting the left operand with this result.
For example:
| A = B * C; |
Here we multiply B and C and assign the result to A.
(=) here is the assignment operator.
In MQL4 there are 11 assignments operations
This is the list of them with the usage of each:
| Operator | Name | Example | Description |
| = | Assignment operator | A = B; | Assign B to A. |
| += | Additive Assignment operator | A += B; | It’s equal to: A = A + B; Add B to A and assign the result to A. |
| -= | Subtractive Assignment operators | A -= B; | It’s equal to: A = A - B; Subtract B from A and assign the result to A. |
| *= | Multiplicative Assignment operator | A *= B; | It’s equal to: A = A * B; Multiply A and B and assign the result to A. |
| /= |