Forex4you on social networks

MQL4 Course

Working with built-in language MQL4, developing indicators. Discussing experiences.

MQL4 Course

Postby Kirill » Sat Jul 04, 2009 1:58 am

Here I will post an MQL4 course.
We will study programming step by step. It isn't an easy task, but it can be accomplished if you take on a fundamental approach.

You should definitely train everything we study here. That is the only way to improve your skills. And as you do so many questions will arise.
You are free to ask them in the General Questions topic here: http://www.forex4you.com/forum/viewtopic.php?f=9&t=20
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Lesson 1

Postby Kirill » Tue Jul 07, 2009 1:07 am

Image

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.

Image
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.

Image
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.
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Lesson 2 - SYNTAX

Postby Kirill » Thu Jul 09, 2009 11:07 pm

Good day everybody!

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 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:

Code: Select all
double  MacdCurrent, MacdPrevious, SignalCurrent;


Code: Select all
double

MacdCurrent,

MacdPrevious,

SignalCurrent;


Code: Select all
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:

Code: Select all
#property

copyright "Copyright © 2004, MetaQuotes Software Corp."


This is the valid “Controlling compilation”:

Code: Select all
#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:

Code: Select all
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:

Code: Select all
extern int MA_Period=1

3;


Code: Select all
extern int MA_Period=1           3;


Notice the tab between 1 and 3.

Code: Select all
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:

Single line comments

The Single line comment starts with “//” and ends with the new line.

For example:

Code: Select all
//This is a comment

extern int MA_Period=13;


Code: Select all
extern int MA_Period=13; //This is another comment


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:

Code: Select all
/* this

is

multi

line

comment*/


You can also nest single line comment inside multi lines comment like that:
Code: Select all
/* this

is

multi        //another comment nested here.

line

comment*/


This is a valid comment too:

Code: Select all
extern int /*HELLO! I’m a comment*/ MA_Period=13;


But this is an invalid comment:

Code: Select all
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:

Code: Select all
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 _.
    3. You can’t use any reserved words as an Identifier.
    4. The identifiers’ names are case sensitive.

Let’s take some examples:

Code: Select all
Name1                       Valid

_Name1                      Valid

1Name                       Invalid (don’t start with a 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):

Image

For example the next lines of code are invalid:

Code: Select all
extern int datetime =13;

int extern =20;

double continue = 0;
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Lesson 3 - MQL4 Data Types

Postby Kirill » Sun Jul 12, 2009 2:00 pm

What are the Data types?

Any programming language has a set of names for the memory representation of 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 in 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.

    * In order to use a box to store data, the box must be given a name; this process is known as declaration.
    * In the declaration process you use a word tell the computer what’s the kind and size of the box you want to use, this word known as keyword.
    * It helps if you give a box a meaningful name that relates to the type of information which make it easier to find the data, this name is the variable constant.
    * Data is placed into a box by assigning the data to the box.
    * You can set the value of the box you have created in the same line you declared the variable; this process is known as initialization.

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 what the Data type is for.

For example if we say this line of code to the computer:
Code: Select all
int  MyVaraible=0;


It means 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 the coming lessons.

In MQL4, the following Data types exist:

    * Integer (int)
    * Boolean (bool)
    * Character (char)
    * String (string)
    * Floating-point number (double)
    * Color (color)
    * Datetime (datetime)


1 - Integer

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:
Code: Select all
12, 3, 2134, 0, -230

0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7


We use the keyword int to create an integer variable.

For example:
Code: Select all
int intInteger = 0;

int intAnotherIntger = -100;

int intHexIntger=0x12;


Decimal and Hexadecimal:

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.
2 - Boolean

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:
Code: Select all
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:
Code: Select all
'a' , '$' , 'Z'


We use the keyword int to create a character variable.

For example:
Code: Select all
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:
Code: Select all
int chrA = '\\';      //slash character

int chrB = '\n';      //new line


This is the list of Escape Sequence characters used in MQL4.
Code: Select all
carriage return                          \r

new line                                    \n

horizontal tab                           \t

reverse slash                             \\

single quote                               \'

double quote                              \"

hexadecimal ASCII-code          \xhh


4 - String

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.

Image
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:
Code: Select all
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:
Code: Select all
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:
Code: Select all
// 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:
Code: Select all
color clr1= Red;

color clr1= C'128,128,128' ;

color clr1=32768;


Image

7 - Datetime

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:
Code: Select all
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:
Code: Select all
datetime dtMyBirthDay= D'1972.10.19 12:00:00';

datetime dt1= D'2005.10.22 04:30:00';


See you soon!
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Lesson 4 - MQL4 Operators & Expressions

Postby Kirill » Thu Jul 16, 2009 1:20 am

What are Operations & Expressions?

You know the operations very well. If I tell you that (+,-,*, /) are the basic arithmetical operators, you will remember very fast what 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:

Code: Select all
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:

Image

Note: You can’t combine the increment and decrement operator with other expressions.

For example you can’t say:

Code: Select all
A=(B++)*5;


But you can write it like this:

Code: Select all
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:

Code: Select all
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:

Image


3 - Relational operators:

The relational operators compare two values (operands) and result false or true only.

It’s is like the question “Is John taller than Alfred? Yes / no?”

The result will be false only if the expression produce zero and true if it produces any number differing from zero;

For example:

Code: Select all
4 == 4;            //true

4 < 4;              //false

4 <= 4            //true;


In MQL4 there are 6 Relational operations

This is the list of them with the usage of each:

Image

4- Logical operators:

Logical operators are generally derived from Boolean algebra, which is a mathematical way of manipulating the truth values of concepts in an abstract way without bothering about what the concepts actually mean. The truth value of a concept in Boolean value can have just one of two possible values: true or false.

MQL4 names the Logical operators as Boolean operators

MQL4 uses the most important 3 logical operators.

This is the list of them with the usage of each:

Image

5 - Bitwise operators:

The bitwise operators are similar to the logical operators, except that they work on a smaller scale -- binary representations of data.

The following operators are available in MQL4:

Image

Note Both operands associated with the bitwise operator must be integers.

6 - Other operators:

There are some operators which used in MQL4 and don’t belong to one of the previous categories:

1 - The array indexing operator ([]).

2 - The function call operator (());

3 - The function arguments separator operator -comma (,)

We will know more about the Arrays and Functions in the next lessons, so just remember these 3 operators as “Other operators”.


Operators Precedence:

If you don't explicitly indicate the order in which you want the operations in a compound expression to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators with a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Thus, the two following statements are equivalent:

Code: Select all
x + y / 100


x + (y / 100) //unambiguous, recommended


When writing compound expressions, you should be explicit and indicate with parentheses () which operators should be evaluated first. This practice will make your code easier to read and to maintain.

The following table shows the precedence assigned to the operators in the MQL4. The operators in this table are listed in precedence order: The higher in the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with a relatively lower precedence. Operators on the same group have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right. Assignment operators are evaluated right to left.

() Function call From left to right

[] Array element selection

! Negation From left to right

~ Bitwise negation

- Sign changing operation

* Multiplication From left to right

/ Division

% Module division

+ Addition From left to right

- Subtraction

<< Left shift From left to right

>> Right shift

< Less than From left to right

<= Less than or equals

> Greater than

>= Greater than or equals

== Equals From left to right

!= Not equal

& Bitwise AND operation From left to right

^ Bitwise exclusive OR From left to right

&& Logical AND From left to right

|| Logical OR From left to right

= Assignment From right to left

+= Assignment addition

-= Assignment subtraction

*= Assignment multiplication

/= Assignment division

%= Assignment module

>>= Assignment right shift

<<= Assignment left shift

&= Assignment bitwise AND

|= Assignment bitwise OR

^= Assignment exclusive OR

, Comma From left to right



* And now a little fun.
I love operator precedence rules because mearly anybody learns them off by heart. So if you know at least a few - you're cool :D
For example, you can ask the result of this operator: ++ i ++; (but this is more into C/C++, where you have both left and right increment operations). Or this: i +++ i;
Also, precedence is one of the good aces in IOCCC - International Obfuscated C Code Contest.
http://en.wikipedia.org/wiki/International_Obfuscated_C_Code_Contest - this is hilarious, you just HAVE to see it!

See you in the coming lessons,
Kirill.
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Lesson 5 - Loops & Decisions (Part1)

Postby Kirill » Thu Jul 16, 2009 3:37 pm

Welcome to the fifth lesson in my course about MQL4.

The normal flow control of the program you write in MQL4 (And in others languages as well) executes from top to bottom, A statement by a statement.

A statement is a line of code telling the computer to do something.

For example:

Code: Select all
Print("Hello World");
return 0;


A semicolon at end of the statement is a crucial part of the syntax but usually easy to forget, and that's make it the source of 90% of errors.

But the top bottom execution is not the only case and it has two exceptions,

They are the loops and the decisions.

The programs you write like -the human- decides what to do in response of circumstances changing. In these cases the flow of control jumps from one part of the program to another.

Statements cause such jumps is called Control Statements.

Such controls consist of Loops and Decisions.

LOOPS

Loops causing a section of your program to be repeated a certain number of times.

And this repetition continues while some condition is true and ends when it becomes false.

When the loop end it passes the control to next statement follow the loop section.

In MQL4 there are two kinds of loops:

1. The for Loop

The for loop considered the easiest loop because all of its control elements are gathered in one place.

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

For example:

Code: Select all
int j;

for(j=0; j<15; j++)

            Print(j);


How does this work?

The for statement consists of for keyword, followed by parentheses that contain three expressions separated by semicolons:

for(j=0; j<15; j++)

These three expressions are the initialization expression, the test expression and the increment expression:

j=0 - initialization expression

j<15 - test expression

J++ - increment expression

The body of the loop is the code to be executed the fixed number of the loop:

Print(j);

This executes the body of the loop in our example for 15 times.

Note: the for statement in not followed by a semicolon. That's because the for statement and the loop body are together considered to be a program statement.

The initialization expression:

The initialization expression is executed only once, when the loop first starts. And its purpose to give the loop variable an initial value (0 in our example).

You can declare the loop variable outside (before) the loop like our example:

Code: Select all
int j;


Or you can make the declaration inside the loop parentheses like this:

Code: Select all
for(int j=0; j<15; j++)


The previous two lines of code are equal, except the Scope of each variable (you will know more about the variable declaration and scopes in the Variables lesson).

The outside declaration method makes every line in the code block to know about the variable, while the inside declaration makes only the for loop to know about the variable.

You can use more that one initialization expression in for loop by separating them with comma (,) like this:

Code: Select all
int i;

int j;

for(i=0 ,j=0;i<15;i++)

   Print(i);


The Test expression:

The test expression always a relational expression that uses relational operators (please refer to relational operators in the previous lesson).

It is evaluated by the loop every time the loop executed to determine if the loop will continue or will stop. It will continue if the result of the expression is true and will stop if it false.

In our example the body loop will continue printing i (Print(i)) while the case j<15 is true. For example the j = 0,1,2,3,4,5,6,7,8,9,10,11,12,13 and 14.

And when j reaches 15 the loop will stops and the control passes to the statement following the loop.

The Increment expression:

The increment expression changes the value of the loop variable (j in our example) by increase it value by 1.

It executed as the last step in the loop steps, after initializing the loop variable, testing the test expression and executing the body of the loop.

Figure 1 shows a flow chart of the for loop.

Image
Figure 1 - Flow chart of the for loop

Like the initialization expression, in the increment expression you can use more than one increment expression in the for loop by separating them with comma (,) like this:



Code: Select all
int i;

int j;

for(i=0 ,j=0;i<15;i++,j++)

   Print(i);


But you can only use one test expression.

Another notice about the increment expression, it’s not only can increase the variable of the loop, but it can perform and operation it like for example decrements the loop variable like this:

Code: Select all
int i;

for(i=15;i>0,i<;i--)

   Print(i);


The above example will initialize the i to 15 and start the loop, every time it decreases i by 1 and check the test expression (i>0).

The program will produce these results: 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1.

Multi statement in the loop body:

In our previous examples, we used only one statement in the body of the loop, this is not always the case.

You can use multi statements in the loop body delimited by braces like this:

Code: Select all
for(int i=1;i<=15;i++)
{

   Print(i);

   PlaySound("alert.wav");

}


In the above code the body of the loop contains two statements, the program will execute the first statement then the second one every time the loop executed.

Don’t forget to put a semicolon at the end of every statement.

The Break Statement:

When the keyword presents in the for loop (and in while loop and switch statement as well) the execution of the loop will terminate and the control passes to the statement followed the loop section.

For example:

Code: Select all
for(int i=0;i<15;i++)
{

  if((i==10)

    break;

  Print(i);

}


The above example will execute the loop until i reaches 10, in that case the break keyword will terminate the loop. The code will produce these values: 0,1,2,3,4,5,6,7,8,9.

The Continue Statement:

The break statement takes you out the loop, while the continue statement will get you back to the top of the loop (parentheses).

For example:

Code: Select all
for(int i=0;i<15; i++)
{

   if(i==10) continue;

   Print(i)

}


The above example will execute the loop until i reaches 10, in that case the continue keyword will get the loop back to the top of the loop without printing i the tenth time. The code will produce these values: 0,1,2,3,4,5,6,7,8,9,11,12,13,14.

Latest note:

You can leave out some or all of the expressions in for loop if you want, for example:

for(;;)

This loop is like while loop with a test expression always set to true.

We will introduce the while loop to you right now.

2. The while Loop

The for loop usually used in the case you know how many times the loop will be executed. What happen if you don’t know how many times you want to execute the loop?

This the while loop is for.

The while loop like the for loop has a Test expression. But it hasn’t Initialization or Increment expressions.

This is an example:

Code: Select all
int i=0;

while(i<15)
{

   Print(i);

   i++;

}


In the example you will notice the followings:

* The loop variable had declared and initialized before the loop, you can not declare or initialize it inside the parentheses of the while loop like the for loop.
* The i++ statement here is not the increment expression as you may think, but the body of the loop must contain some statement that changes the loop variable, otherwise the loop would never end.

How does the above example work?

The while statement contains only the Test expression, and it will examine it every loop, if it’s true the loop will continue, if it’s false the loop will end and the control passes to the statement followed the loop section.

In the example the loop will execute till i reaches 16 in this case i<15=false and the loop ends.

Figure 2 shows a flow chart of the while loop.

Image
Figure 2 - Flow chart of the while loop

I told you before that the while loop is like the for loop, these are the similar aspects:

1. You can use break statement and continue in both of them.
2. You can single or multi statements in the body of the loop in both of them, in the case of using multi statements you have to delimit them by braces.
3. The similar copy of for(;;) is while(true)

See you in the coming lessons,
Kirill.
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Lesson 6 - Loops & Decisions (Part2)

Postby Kirill » Mon Jul 20, 2009 11:13 am

Welcome to the sixth lesson in the MQL4 course!
I hope you enjoyed the previous lessons.

In the previous lesson, we talked about Loops.

And we have seen that the Loops are one of two ways we use to change the normal flow of the program execution - from top to bottom. The second way is the Decisions.
Decisions in a program cause a one-time jump to a different part of the program, depending on the value of an expression.

These are the kinds of decisions statements available in MQL4:

1 - The if Statement

The if statement is the simplest decision statement, here’s an example:

Code: Select all
if( x < 100 )

Print("hi");


Here the if keyword has followed by parentheses, inside the parentheses the Test expression ( x < 100), when the result of test expression is true the body of the if will execute (Print("hi");) ,and if it is false, the control passes to the statement follows the if block.

Image
Figure 1 - Flow chart of the if statement

Multi Statements in the if Body:

Like the loops, the body of if can consist of more than statement delimited by braces.

For example:

Code: Select all
if(current_price==stop_lose)
{
            Print("you have to close the order");

            PlaySound("warning.wav");
}


Notice the symbol == in the Test expression; it's one of the Relational Operators you have studied in the lesson 4 - operations & expressions.
This is a source of a lot of errors, when you forget and use the assignment operator =.

Nesting:

The loops and decision structures can be basted inside one another; you can nest ifs inside loops, loops inside ifs, ifs inside ifs, and so on.

Here's an example:

Code: Select all
for(int i=2 ; i<10 ; i++)
            if(i%2==0)
            {
                        Print("It's not a prime nomber");

                        PlaySound("warning.wav");
            }


In the previous example the if structure nested inside the for loop.

Notice: you will notice that there are no braces around the loop body, this is because the if statement and the statements inside its body, are considered to be a single statement.


2 - The if...else Statement

The if statement let's you to do something if a condition is true, suppose we want to do another thing if it's false. That's the if...else statement comes in.

It consist of if statement followed by statement or a block of statements, then the else keyword followed by another statement or a block of statements.

Like this example:

Code: Select all
if(current_price>stop_lose)
            Print("It’s too late to stop, please stop!");

else
            Print("you doing well today!");


If the test expression in the if statement is true, the program one message, if it isn’t true, it prints the other.

Image
Figure 2 - Flow chart of the if..else statement

Nested if…else Statements

You can nest if…else statement in ifs statements, you can nest if…else statement in if…else statement, and so on.

Like this:
Code: Select all
if(current_price>stop_lose)
            Print("It’s too late to stop, please stop!");

if(current_price==stop_lose)
            Print("It’s time to stop!");

else
            Print("you playing well today!");


NB: There’s a potential problem in nested if…else statements, you can inadvertently match an else with the wrong if.

To solve this case you can do one of two things:


1 - you can delimited the if…else pairs with braces like this:

Code: Select all
if(current_price>stop_lose)
{
            Print("It’s too late to stop, please stop!");

            if(current_price==stop_lose)
                    Print("It’s time to stop!");
            else
                    Print("you playing well today!");
}


2- If you can’t do the first solution (in the case of a lot of if…else statements or you are lazy to do it) take it as rule: match else with the nearest if. (Here it’s the line if(current_price==stop_lose)).


3 - The switch Statement

If you have a large decision tree, and all the decisions depend on the value of the same variable, you can use a switch statement here.

Here’s an example:

Code: Select all
switch(x)
{
   case 'A':
      Print("CASE A");
      break;

   case 'B':

   case 'C':
      Print("CASE B or C");
      break;

   default:
      Print("NOT A, B or C");
      break;
}


In the above example the switch keyword is followed by parentheses, inside the parentheses you’ll find the switch constant, this constant can be an integer, a character constant or a constant expression. The constant expression mustn’t include variable for example: case X+Y: is an invalid switch constant.

How the above example works?

The switch statement matches the constant x with one of the cases constants.

In the case x=='A' the program will print "CASE A" and the break statement will take you the control out of the switch block.

In the cases x=='B' or x=='C', the program will print "CASE B or C". That’s because there’s no break statement after case 'B':.

In the case that x != any of the cases constants the switch statement will execute the default case and print "NOT A, B or C".

Image
Figure 3 - Flow chart of the switch statement
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Lesson 7 - Functions

Postby Kirill » Tue Jul 21, 2009 1:51 pm

Welcome to the world of MQL4 Functions.

The functions in any language take two phases:
- Learning them which is sometimes a boring thing ;)
- Using them which is always a lifeboat.

Let’s start the seventh lesson.


What’s the meaning of functions?

The function is very like the sausage machine, you input the meat and the spices and it outs the sausage.

The meat and the spices are the function parameters; the sausage is the function return value. The machine itself is the function body.

There’s only one difference between the functions and your sausage machine, some of the functions will return nothing (nothing in MQL4 called void).

Let’s take some examples:

Code: Select all
double                                 // type of the sausage – return value
my_func (double a, double b, double c) // function name and parameters list (meat & spices)
{                               
   return (a*b + c);                   // sausage outs - returned value
}


As you see above, the function starts with the type of the returned value “double” followed by the function name which followed by parentheses.
Inside the parentheses you put the meat and spices, sorry, you put the parameters of the function.
Here we have put three parameters double a, double b, double c.
Then the function body starts and ends with braces. In our example the function body will produce the operation (a*b + c).
The return keyword is responsible about returning the final result.

Return keyword:

The return keyword terminates the function (like the break keyword does in the loop), and it gives the control to the function caller (we will know it soon).
The return keyword can include an expression inside its parentheses like the above example return (a*b + c); and this means to terminate the function and return the result of the expression.
And it can be without any expression and its only job in this case is to terminate the function.

Notice: Not all the functions use the return keyword, especially if there’s no return value. Like the next example:

Code: Select all
void                                 // void mean there’s no sausage – returned value.
my_func (string s) // function name and parameters list (meat & spices)
{                               
       Print(s);
}


The function above will not return value, but it will print the parameter s you provided. When the function has no return value you use “void” as the funciotn returns type.
These kinds of functions in some programming language are called “Methods”, but MQL4 calls them functions.

Function call:

We know very well now what the function is (I hope)? How to use functions in your MQL4?
There’s an extra step after writing your function to use the function in you program.
This step is calling it (using it).

Assume you have a function which collects the summation of two integers.
This is the function:

Code: Select all
int collect (int first_number, int second_number)
{                               
       return(first_number+ second_number);
}


You know how the previous function works, and you want to use it.
You use it like this:

Code: Select all
int a = 10;
int b = 15;

int sum = collect(a,b);

Print (sum);


The example above will print 25 (is it magic). But how did it know?

The magic line is int sum = collect(a,b); here you declared a variable (sum) to hold the function return value and gave the function its two parameters (a,b).

You basically called the function.

When MQL4 sees your function name, it will take your parameters and go to the function and it will return –soon- with the result and place it in the same line.
It’s very like copying all the lines of the function instead of the place you called the function in, easy right?


Nesting functions inside function:

You can nest function (or more) inside the body of another function. That’s because the caller line is treated like any normal statement (it’s actually a statement).

For example:
We will use the collect function described above inside another new function which its job is printing the result of the collection:

Code: Select all
void print_collection (int first_number, int second_number)
{                               
       int sum = collect(first_number, second_number);
       Print(sum);
}


Here we called the collect function inside the print_collection function body and printed the result. void means there’s no return vale (do you still remember?).


MQL4 Special functions init(), deinit() and start():

In MQL4, every program begins with the function “init()” (initialize) and it occurs when you attach your program(Expert advisor or Custom indicator) to the MetaTrader charts or in the case you change the financial symbol or the chart periodicity. And its job is to initialize the main variables of your program (you will know about the variables initialization in the next lesson).

When your program finishes its job or you close the chart window or change the financial symbol or the chart periodicity or shutdown MetaTrader terminal, the function "deinit()" (de-initialize) will occur.

The third function (which is the most important one) “start()” will occur every time new quotations are received , you spend 90% of your programming life inside this function.

We will know a lot about these functions in our real world lessons when we write our own Expert Advisor and Custom Indicator.
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Lesson 8 - Variables in MQL4

Postby Kirill » Thu Jul 23, 2009 1:57 pm

Why do we need variables?

As I told you the secret before, the variables are the names that refer to sections of memory in 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.

* In order to use a box to store data, the box must be given a name; this process is known as declaration.
* In the declaration process you use a word to tell the computer what’s the kind and size of the box you want to use, this word id known as keyword.
* It helps if you give a box a meaningful name that relates to the type of information which make it easier to find the data, this name is the variable constant.
* Data is placed into a box by assigning the data to the box.
* When we set the value of the box you have created in the same line you declared the variable; this process is known as initialization.

When we create a variable we are telling the computer that we want it 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:

Code: Select all
int  MyVaraible=0;


That means 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:

* Integer (int)
* Boolean (bool)
* Character (char)
* String (string)
* Floating-point number (double)
* Color (color)
* Datetime (datetime)

I’ve copied the previous few lines from the DATA TYPES lesson for you. To know what’s the variable, now how do to declare the variables:

Declaration:

Declaring a variable means to introduce it to the world and specify its type. By using the keywords you have learned in the DATA TYPES lesson (int, double, char, bool, string, color and datetime) with the name you chose to the variable.

For example:

Code: Select all
int  MyVaraible;


Here you declared a variable named MyVaraible which is an integer type. And before the declaration you can’t use the MyVariable in your code. If you used it without declaration the MQL4 compiler will complain and will tell you something like this: 'MyVaraible' - variable not defined. 1 error(s), 0 warning(s).

Initialization:

Caution: For convenience purposes we will use the word "initialization" in the meaning of assigning a value to a variable whether we do it in the declaration line or not.

So, initializing the variable means assigning a value to it, for example MyVaraible=0;
You can initialize the variable at the same line of the declaration like the example: int MyVaraible=0;

And you can declare the variable in one place and initialize it in another place like this:

Code: Select all
int  MyVaraible;





MyVaraible=5;


But keep in your mind this fact: the declaration must be before the initialization.

Scopes of variables:

There are two scopes of the variables, Local and Global.

Scope means, which part of code will know about the variable and can use it.

1. Local variables
Local variables are not seen to outside world where they had declared. For example the variables declared inside function are local to the function block of code, and the variables declared inside the loop or decisions block of code are local to those blocks and can be seen or used outside them.

For example:

Code: Select all
double my_func (double a, double b, double c)
{
   int d ;                             
   return (a*b + c);
}


In the above example the variables a,b,c and d are local variables, which can be used only inside the function block of code (anything beside the braces) and can’t be used by outside code. So we can’t write a line after the function above saying for example: d=10; because d is not seen to the next line of the function because it’s outside it.

2. Global variables
Global variables are the variables which had declared outside any block of code and can be seen from any part of your code.

For example

Code: Select all
int Global_Variable;

double my_func (double a, double b, double c)
{
      return (a*b + c + Global_Variable);
}


Here the variable Global_Variable declared outside the function (function level declaration) so, it can be seen by all the functions in you program.

The Global variables will automatically set to zero if you didn’t initialize them.

Extern variables:

The keyword “extern” used to declare a special kind of variables; those kinds of variables are used to define input date of the program, which you can set them form the property of your Expert advisor or Custom indicator.

For example:

Code: Select all
extern color Indicator_color = C'0x00,0x00,0xFF'; // blue

int init()
{

   ...

}



Here the variable Indicator_color had defined as an extern variable which you will see it the first time you attach your indicator (or EA) to the MetaTrader chart and which you can change it from the properties sheet windows. Look at Figure 1.

Image
Figure 1: Property sheet of MA indicator

Here the variables Period, Shift, MA_method, Apply_to and Style are variables defined using the “extern” keyword so they appear in the property sheet.

Any variable you want the user of your program be able to change and set, make it extern variable.

See you in the next lessons!
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Lesson 9 - Preprocessors

Postby Kirill » Sun Jul 26, 2009 4:11 am

What are the Preprocessors?

Preprocessors are the instructions you give to the compiler to carry them out before starting (processing) your code.

For example if you used the preprocessor directive #include <win32.h> that’s mean you telling the compiler to include the content of the file “win32.h” in the place you wrote the include keyword before processing your code.

In MQL4 there are four of preprocessors directives:



1 - define directive:

The define directive used to generate a constant.
The constant is very like the variable with only one different, you set its value only once and you can not change its value in your code like the variable.
For example:

Code: Select all
#define my_constant          100


As you can notice in the above example there’s no assignment symbol (=) but only space between the constant name (my_constant ) and its value (100).
And you can notice too that the line didn’t end with semi-colon but it ended with a carriage-return character (new line).

The name of constant obeys the same rules you had learnt about choosing the identifier names (lesson 2 SYNTAX), for example you can’t start the constant name with a number or exceeds 31 characters.

The value of the content can be any type you want.
The compiler will replace each occurrence of constant name in your source code with the corresponding value.
So you can use the above constant in your code like that:

Code: Select all
sum = constant1 * 10;




2 - property directive:

There are predefined constants called “Controlling Compilation” included in the MQL4 language, which you can set them in your program.
They are the properties of your program which you can set them using the compiler directive “property” and the compiler will write them in the settings of your executable program (ex4 file).
For example:

Code: Select all
#property link        "http://www.forex-tsd.com"
#property copyright   "Anyone who wants to use"


This is the list of the MQL4 predefined constants:

Image



3 - include directive:

When you ask the compiler to include a file name with the “include” directive, it’s very like when you copy the entire file content and paste it in the place of the line you write include.
For example:

Code: Select all
#include <win32.h>


In the above example you telling the compiler to open the file “win32.h” and reads all of its content and copy them in the same place of the include statement.

Note: in the above example you enclosed the file name with Angle brackets <> and that’s mean you telling the compiler to use the default directory (usually, terminal_directory\experts\include) to search for the file win32.h and don’t search the current directory.

If the file you want to include located at the same path of your code, you have to use quotes instead of angle brackets like this:

Code: Select all
#include “mylib.h”


In the both cases if the file can’t be found you will get an error message.

You can use include anywhere you want but it usually used at the beginning of the source code.

Tip: It’s a good programming practice to write the frequently used code in a separate file and use include directive to put it in your code when you need (just an advice).



4 - import directive:

It’s like include directive in the aspect of using outside file in your program.
But there are differences between them.
You use import only with MQL4 executables files (.ex4) or library files (.dll) to import their functions to your program.
For example:

Code: Select all
#import "user32.dll"

   int MessageBoxA(int hWnd,string lpText,string lpCaption,

                           int uType);

   int MessageBoxExA(int hWnd,string lpText,string lpCaption,

                             int uType,int wLanguageId);

#import "melib.ex4"

#import "gdi32.dll"

   int      GetDC(int hWnd);

   int      ReleaseDC(int hWnd,int hDC);

#import


When you import functions from “ex4” file you don't have to declare the functions to be ready for use.

While importing the functions from a “.dll” file requires you to declare the functions you want to use like this:

Code: Select all
int MessageBoxA(int hWnd,string lpText,string lpCaption,

                           int uType);


And only the functions you have declared you can use in your code.

You must end the import directives with a blank import line #import (without parameters).


Like one of my programming-buddies says: "preprocessors help evade the monkey-work". That phrase has it all!

Good luck and see you in the coming lesson!
Kirill.
Kirill
 
Posts: 467
Joined: Sat Jun 27, 2009 12:02 am

Next

Return to MQL4 Programming Language. Scripts, Indicators.



Who is online

Users browsing this forum: No registered users and 1 guest