Practical Programming in Mql4
Practical Programming in Mql4
Kovalyov
Programming in Algorithmic
Language MQL4
Introductory Course
Source: http://book.mql4.com/
Nowadays, a personal computer became indispensable for everybody. The rapid development
of Internet and performance of modern computers opened up new vistas in many fields of
human activities. As early as ten years ago, the financial market trade was available only for
banks and for a limited community of specialists. Today, anybody can join the world of
professional traders and start independent trading at any time.
Hundreds of thousands of worldwide traders have already judged MetaTrader 4 Client
Terminal on its merits. The use of its embedded programming language, MQL4, lifts traders
to a new level of trading - to automated trading. Now, a trader can implement his or her ideas
as an application program - write a custom indicator, a script to perform single operations, or
create an Expert Advisor - an automated trading system (trading robot). An Expert Advisor
(EA) can work on a 24/7 basis without any intervention - track security prices, send
electronic messages, SMSes to your mobile phone, as well as do many other useful things.
The main advantage of applications is the possibility to make trades according to the
algorithm set by the trader. Any ideas that can be described in an algorithmic language
(intersection of two moving averages or digital processing of signals, three screens by Elder
or Peters' fractal analysis, a neural network or geometrical constructions) can be coded in an
application and then used in practical trading.
Development of applications for MetaTrader 4 Client Terminal requires the knowledge of
MQL4. This present textbook will help you create your own Expert Advisors, scripts and
indicators and incarnate in them your ideas – your algorithms of profitable trading. The
textbook is intended for a large number of readers without experience in programming that
want to learn how to develop automated trading applications for MetaTrader 4 Client
Terminal. The textbook is designed in such a method that to make learning MQL4 as
convenient and consequent as possible.
Preface
It is a sort of difficulty to start writing a textbook on programming for beginners, because the
area of knowledge under consideration involves some new concepts that are not based on
anything previously known or usual.
Generally speaking, a problem of this kind may occur in any other field of knowledge. For
example, point is known in mathematics as infinitesimal circle, whereas the circle itself is
defined as a set of points ordered in a certain manner. As is easy to see, these terms are
defined through each other. At the same time, this 'inadvertence' did not become a stumbling
block for mathematics. Both circles, points, as well as other terms adopted in mathematics go
well together. Moreover, everybody understands by insight what a point is and what a circle
is.
It is easy to find out that the vast majority of ordinary terms have indeterminate boundaries.
Some of those boundaries are so fuzzy that they cast some doubt on the existence of the very
object or phenomenon defined by the term. However, the nature of man is that this strange (in
terms of normal logic) situation does not come between a man and his existence and fruitful
activities. After a term has been used for a certain amount of time, it takes on its complete
sense for us. It's difficult to answer the question of how and why it happens this way. But it
does. We only know that multiple reference to a term plays an important role in the
remarkable process of terms learning.
The following tasks were set in this present work:
unfolding the sense of new terms using well-known analogies;
making the meaning of each term intuitively clear when it occurs for the first time;
providing the readers with the necessary amount of information to characterize
programs and programming.
For this purpose, the book contains many examples and figures. The text includes cross-
references that allow the reader to get information on allied topics.
A few words about the presentation of materials. Some textbooks on programming invite their
readers on the very first pages to print "Hello, world!" using a simple program. Their authors
think that, as soon as their readers start learning programming, they should refer to program
texts and gradually get used to how the programs may look, which will later facilitate their
learning. However, this approach results in that the reader has to deal with several unknown
terms at the same time and just to guess the content and properties of some lines in the
program. This may result in a misconception and, consecutively, in vacancy in the reader's
knowledge.
As I see it, it would be more effective to use a method where the reader goes to the next
section in the textbook only after he or she has had a thorough grasp of the previous materials.
In the framework of this method, the first program will be offered to the reader only after he
or she has mastered all necessary terms and gained some insight into the basic principles of
coding. This is the method this present textbook is based on.
To master knowledge given in the book, the reader has to be a PC user and to have some
experience in working with MetaTrader 4 produced by MetaQuotes Software Corp.
2
Table of Contents
Preface
Introduction to MQL4
Basics of MQL4
Some Basic Concepts
Constants and Variables
Data Types
Operations and Expressions
Operators
Functions
Program Types
MetaEditor
File System
Creating and Using Programs
Program in MQL4
Program Structure
Special Functions
Program Execution
Examples of Implementation
Operators
Assignment Operator
Conditional Operator 'if-else'
Cycle Operator 'while'
Cycle Operator 'for'
Operator 'break'
Operator 'continue'
Operator 'switch'
Function Call
Function Description and Operator 'return'
Variables
Predefined Variables and RefreshRates Function
Types of Variables
GlobalVariables
Arrays
3
Practical Programming in MQL4
Programming of Trade Operations
Common Way of Making Trades
Order Characteristics and Rules for Making Trades
Opening and Placing Orders
Closing and Deleting Orders. Function OrderSelect
Modification of Orders
Simple Programs in MQL4
Usage of Technical Indicators
Simple Expert Advisor
Creation of Custom Indicators
Custom Indicator ROC (Price Rate of Change)
Combined Use of Programs
Standard Functions
Common Functions
Graphical Objects
Operations with Charts
String Functions
Date and Time
File Operations
Arrays and Timeseries
Mathematical Functions
GlobalVariable Functions
Custom Indicators
Account Information
Trade Functions
Creation of a Normal Program
Structure of a Normal Program
Order Accounting
Data Function
Event Tracking Function
Volume Defining Function
Trading Criteria Defining Function
Trade Functions
Error Processing Function
4
Appendixes
Glossary
Types of Trades
Requirements and Limitations in Making Trades
Error Codes
Styles of Indicator Lines
Types and Properties of Graphical Objects
Sound Files
MessageBox() Return Codes
MarketInfo() Identifiers
List of Programs
5
Fig. 1. A program in MQL4 as a part of MetaTrader 4 Client Terminal.
If you are interested in MQL4 programming, you must have got acquainted with the client
terminal. Client terminal is a part of the online trading system. This system also includes a
server installed in a dealing center. The dealing center in its turn is connected with other
market participants - banks and financial institutions.
The client terminal includes informational environment - a set of parameters that inform
about the market state and relations between a trader and dealing center. It contains
information about current prices, limitations on the maximal and minimal order size, minimal
distance of stop orders, allowance/prohibition of the automated trading and many other useful
parameters characterizing the current state. The informational environment is updated when
new ticks are received by the terminal (green line in Fig. 1).
Built-In Tools
The client terminal contains built-in tools that allow conducting technical analysis of market
and execute manual trading management. For market analyzing one can use technical
indicators and different line studies - support/resistance lines, trend channels, Fibonacci
levels etc.
For manual trading management the order management toolbar is used. Using this toolbar a
trader can open, close and modify orders. Besides, the terminal has the option of automated
6
management of stop order position. A trader's actions with built-in trading management tools
result in the formation of trade orders, which are sent to a server.
For more information about the client terminal please refer to "Userguide"
(ClientTerminal_folder\Terminal.chm).
Programming Tools
custom indicator - a program for graphical displaying of market regularities written accord-
ing to an author's algorithm;
Expert Advisor - a program that allows to automate a large part of trading operations and
fully automate trading;
script - a program for executing one-time actions including execution of trade operations.
Fig. 1 shows that the application has the same means of access to the client terminal
informational environment as built-in tools for manual trading (blue arrows). It also can form
managing influences (red arrows), passed to the client terminal. Programs of different types
can be used simultaneously and exchange data. Using these applications a programmer can
automatize a large part of trading operations or create a robot that will trade without a trader's
interference.
Applications and manual management tools can be used in the client terminal simultaneously
complementing each other.
The fundamental technical characteristic of trading using the online trading system
MetaTrader is that all managing actions are produced in the client terminal and then
sent to a server. Application programs (Expert Advisor, script, indicator) can work
only as part of the client terminal provided it is connected to a server (dealing
center). None of application programs are installed on the server.
The server allows only to process signals coming from a client terminal. If a client terminal is
disconnected from the Internet or an application program (Expert Advisor or script) running
in it does not generate any managing actions, nothing will happen on the server.
The scope of our study includes programs (Expert Advisors, scripts and custom indicators)
that allow to conduct partially or fully automated trading and significantly widen the
informational maintenance of trading (see Fig. 1). In this book you will find the description
of program components and the main rules of creating and using programs. We will also
consider in details examples of programs and parameters of informational environment of the
client terminal, which are available to a program during its execution.
Programs for the automated trading possess much more potential possibilities than
manual tools of trade management.
In the majority of cases a program allows to make a trader's job easier eliminating the
necessity of a constant tracking of market situation sitting before a computer for a long period
7
of time. It may also help to relieve nervous tension and lower the number of errors appearing
in periods of extreme emotional tension. But the main thing is that using of the program
method of trade management allows to develop one's own ideas and test them on historical
data, select optimal parameters for applying these ideas and, finally, to implement a thought-
out trading strategy.
Basics of MQL4
This section represents basic terms underlying programming language MQL4:
Such terms as 'tick' (a price change), 'control' in algorithms, 'comment' in programs are de-
scribed. The main event when trading on financial markets is the change of price. This is why
tick is an important event that makes the basic mechanisms of MQL4 programs run. What to
do when a new tick incomes? What actions to take? This is control that moves to the fore-
front here. But don't forget to comment upon your code.
The terms of constants and variables are introduced, the difference between these terms is
explained. As the term suggests, a constant is something continuous, set once for all. Unlike
the constant, a variable is a programming code object that can modify its content. It is im-
possible to write a program without using unchangeable objects (constants) and/or objects
that can be modified during the program execution (variables).
Data Types
Certain types of data are used in any programming language. The type of a variable is chosen
according to its purpose. How can we declare a variable, how can we initialize it (preset its
initial value)? A wrong choice of the type for a variable may slow down the program or even
result in its wrong actions.
Operations operate upon operands. What types of operations are there? What is typecast-
ing used for? What are special features of operations on integers? Why is it important to
remember about precedences of data of different types? Without knowing about the fea-
tures of some operations, you can make subtle errors.
Operators
Simple and compound operators. A necessary action should not always be executed by a
simple operator. If it is required that a group of operators is executed as one big operator,
this group should be included into one compound operator. Requirements and specific ex-
amples of using operators are given.
8
Functions
The necessity of getting a simple code brings us to the term of Function. In order to use the
function from different locations in the program, it is necessary to provide it with Function
Parameters. We will consider the process of the custom function creation. The examples of
using standard functions are given.
Program Types
Scripts, indicators and Expert Advisors are the types of MQL4 programs that allow you to
cover practically the whole class of problems concerning trading in fincancial markets. It is
necessary to understand the purposes of each type of programs in order to use MetaTrader
4 Client Terminal in the best way.
Tick is an event that is characterized by a new price of the symbol at some instant.
Ticks are delivered to every client terminal by a server installed in a dealing center. As
appropriate to the current market situation, ticks may be received more or less frequently, but
each of them brings a new quote - the cost of one currency expressed in terms of another
currency.
An application operating with the client terminal may work within a long period of time, for
example, several days or weeks. Each application is executed according to the rules set for
programs of a certain type. For example, an Expert Advisor (EA) does not work continuously
all the time. An Expert Advisor is usually launched at the moment when a new tick comes.
For this reason, we don't characterize tick as just a new quote, but as an event to be processed
by the client terminal.
The duration of Expert Advisor's operation depends on what program code is included in it.
Normal EAs complete one information-processing cycle during some tenths or hundredths of
a second. Within this time, the EA can have processed some parameters, make a trading
decision, provide the trader with some useful information, etc. Having finished this part of its
work, the EA goes to waiting mode until a new tick comes. This new tick launches the Expert
9
Advisor again, the program makes its appropriate operations again and returns to the waiting
mode. The detailed description of how the appearance of a new tick influences program
operation follows below.
Speaking about the code execution flow in a program, as well as its interaction with the client
terminal, we will use the term of 'control'.
Control is a process of carrying out of actions preset by the program algorithm and the client
terminal features. Control can be transferred within the program from one code line to
another one, as well as from the program to the client terminal.
Control is transferred in a way similar to that of giving someone the floor to speak at a
meeting. Like speakers address a meeting and then give the floor to others, the client terminal
and the program transfer control to each other. At that, the client terminal dominates. Its
status is higher than that of the program, like the authority of the chairman of a meeting is
larger than those of an ordinary speaker.
Before the program is launched, the control is under the supervision of the client terminal.
When a new tick is received, the client terminal transfers the control to the program. The
program code starts to be executed at this moment.
The client terminal, after it has transferred the control to the program, does not stop its
operation. It continues working with maximum performance during the entire period of time
it is launched on PC. The program can only start operating at the moment when the client
terminal has transferred control to it (like the chairman of a meeting controls the meeting all
the time it is going on, whereas the current speaker takes the word for only a limited period of
time).
After it has completed its operation, the program returns control to the client terminal and
cannot be launched by its own. However, when the control has already been transferred to the
program, it returns control to the client terminal by itself. In other words, the client terminal
cannot return control from the program by itself. Dynamic actions of the user (for example,
forced termination of the program) are an exemption.
When discussing the matters of performance and internal structures of programs, we are
mostly interested in the part of control that is transferred within a program. Let's refer to Fig.
2 that shows the general nature of transferring control to, from and within a program. Circles
shown in the figure characterize some small, logically completed fragments of a program,
whereas the arrows between the circles show how control is transferred from one fragment to
another.
10
Fig. 2. Transferring control in a program
A program that has accepted control from the client terminal (the executing program) starts to
make some actions according to its inherent algorithm. The program contains program lines;
general order of program execution consists in sequential transfer of control from one line to
another in the top-down direction. What and according to what rules can be written in these
lines will be considered below in all details.
Here, it is only important to emphasize that every logically completed fragment is executed -
for example, some mathematical calculations are made, a message is displayed on the screen,
a trade order is formed, etc. Until the current fragment of the program is executed, it retains
the control. After it has been fully completed, the control is transferred to another fragment.
Thus, control within a program is transferred from one logically completed fragment to
another as they are executed. As soon as the last fragment is executed, the program will
transfer (return) control to the client terminal.
A program consists in two types of records: those making the program itself and those being
explanatory texts to the program code.
Comment is an optional and nonexecutable part of a program.
So, comment is an optional part of a program. It means that a ready program will work
according to its code irrespective of whether there are comments in it or not. However,
comments facilitate understanding of the program code very much. There are one-line and
11
multi-line comments. A one-line comment is any sequence of characters following double
slash (//). The sign of a one-line comment is ended by line feed. A multi-line comment starts
with the characters of /* and is ended by */ (see Fig. 3).
Comments are used to explain the program code. A good program always contains
comments.
Comments are widely used in coding. They are usually displayed in gray in codes. We will
use comments, too, in order to explain our codes and make them more intelligible.
12
m/s/s; in mathematics: Pi = 3.14. Constants of the kind cannot be considered similar to
constants in an algorithmic language.
The term of constant is also used in mathematical equations. For example, in the equation of
Y = 3 * X + 7, numbers 3 and 7 are constants. The values of such constants are fully
dependent on the will of the person that has made the equation. This is the closest analogy of
constants used in MQL4 programs.
A constant (as a value) is placed by a programmer in the code at the stage of its creation. The
constant is characterized only by its value, so the terms of 'constant' and 'the value of a
constant' are full synonyms.
Exemplary Constants:
The property of a constant is its power to retain during the time of the program operation the
value set by the programmer and set this value to the program when the program requests this
(Fig. 5). For each constant in the program, the computer allocates a part of its memory of the
necessary size. The value of a constant cannot be changed during execution of the program
neither by programmer nor by computer (Fig. 6).
Fig. 5. The state of the memory cell of a constant when setting the value to the program.
13
The value of a constant cannot be changed during the program operation.
Fig. 6. It is impossible to change the value of a constant during the program operation.
The property of a variable is its capability to get a certain value from the program, retain it
during the period of operation of the program and set this value to the program when
requested by the program. For each variable in the program, the computer allocates a part of
its memory of the necessary size. Let us refer to Fig. 7 and study the construction of a
variable.
14
Fig. 7. A Variable in the memory of a computer.
There is a value of a variable in the memory cell of the computer. This value can be requested
for processing and changed by the program. The name of a variable is never changed. When
writing a code, the programmer can set any name for the variable. However, as soon as the
ready program is launched, neither programmer nor the computer, nor the program has any
technical feasibility to change the name of the variable.
If a program while being executed meets the name of a variable, the program refers to this
variable in order to get its value for processing. If a program has referred to a variable, the
latter one sets its value to the program. At that, the value of the variable remains the same,
whereas the program gets the copy of the value contained in the memory cell allocated for
this variable (Fig. 8).
When the value of a variable is set to a program, this value remains unchanged. The
name of a variable will never be changed.
Fig. 8. The state of the memory cell of a variable when setting the value to the program.
A variable is not related to the executing program for a certain period of time. During this
period, the program may refer to other variables or make necessary calculations. Between
"sessions" of communication with the program, the variable retains its value, i.e., it keeps it
unchanged.
According to the algorithm of the program, it can become necessary to change the value of a
variable. In this case, the program sets to the variable its new value, whereas the variable gets
this value from the program. All necessary modifications are made in the memory cell. This
results in that the preceding value of the variable is deleted, whereas a new value of the
variable set by the program takes its place (Fig. 9).
The value of a variable can be changed by the program. The name of the variable is
15
always unchanged.
Fig. 9. The state of the memory cell of a variable when getting the value from the program.
In a program, constants and variables can be found in operators. In the code below, A and B
are variables, 7 and 3 are constants:
A = 7; // Line 1
B = A + 3; // Line 2
Let us study how a program works with constants and variables. Executing these lines, the
program will make the following steps:
Line 1:
Line 2:
1. The program has found an expression to the right from the equality sign and is trying to cal-
culate it.
2. Constant 3 sets its value to the program.
3. The program refers to variable A by the name.
4. Variable A sets its value (7) to the program.
5. The program makes calculations (7 + 3).
6. Variable В gets value 10 from the program.
The value of a variable can be changed during the program operation. For example, there can
be a line in the program that contains the following:
В = 33; // Line 3
In this case, the following will be done at execution of the program:
It is easy to notice that variable B gets value 10 at a certain stage of the program execution,
and then it gets the value of 33. The name of variable B remains unchanged during all these
events, whereas the value of the variable will change.
Fig. 10 shows constants and variables in the program code:
16
Fig. 10. A constant and a variable in a program.
Data Types
It is a common knowledge that only equitype values can be added or subtracted. For example,
apples can be added to apples, but apples cannot be added to square meters or to temperature.
Similar limitations can be found in most of modern algorithmic languages.
Like normal objects of life have certain types characterizing their color (red, blue, yellow,
green), their taste (bitter, sour, sweet), amount (one and a half, two, seven), MQL4 uses data
of different types. Speaking about data type, we will mean the type of the value of a constant,
of a variable and the value returned by a function (the notion of function is considered in the
section of Functions).
In MQL4, the following types are distinguished (for the values of constants, variables, and
the values returned by functions):
int - integers;
double - real numbers;
bool - Boolean (logical) values;
string - values of string type;
color - values of color type;
datetime - values of date and time.
Type int
The values of int type are integers. This type includes values that are integer by their nature.
The following values are integers, for example: amount of bars in the symbol window (16000
bars), amount of opened and pending orders (3 orders), distance in points between the current
symbol price and the order Open Price (15 points). Amounts representing such objects as
events can also be integers only. For example, the amount of attempts to open an order cannot
be equal to one and a half, but only to one, two, three, etc.
There are 2 types of integer values:
Decimal values can consist of digits from 0 to 9 and be either positive or negative: 10, 11, 12,
1, 5, -379, 25, -12345, -1, 2.
Hexadecimal values can consist of Latin letters from A to F or from a to f, digits from 0 to 9.
They must begin with 0x or 0X and take positive or negative values: 0x1a7b, 0xff340, 0xAC3
0X2DF23, 0X13AAB, 0X1.
17
Values of int type must be within the range from -2 147 483 648 to 2 147 483 647. If the
value of a constant or a variable is beyond the above range, the result of the program
operation will be void. The values of constants and variables of int type take 4 bytes of the
memory of a computer.
An example of using a variable of int type in a program:
int Art = 10; // Example integer variable
int B_27 = -1; // Example integer variable
int Num = 21; // Example integer variable
int Max = 2147483647; // Example integer variable
int Min = -2147483648; // Example integer variable
Type double
The value of double type are real numbers that contain a fractional part.
Example values of this type can be any values that have a fractional part: inclination of the
supporting line, symbol price, mean amount of orders opened within a day.
Sometimes you can face problems designating variables when writing your code, i.e., it is not
always clear to a programmer what type (int or double) the variable belongs to. Let us
consider a small example:
A program has opened 12 orders within a week. What is the type of variable A that considers
the mean amount of orders daily opened by this program? The answer is obvious: A = 12
orders / 5 days. It means that variable A = 2.4 should be considered in the program as double,
since this value has a fractional part. What type should be the same variable A if the total
amount of orders opened within a week is 10? You can think that if 2 (10 orders / 5 days = 2)
has no fractional part, variable A can be considered as int. However, this reasoning is wrong.
The current value of a variable can have a fraction part consisting of only zeros. It is
important that that value of this variable is real by its nature. In this case, variable A has also
to be of double type. The separating point must also be shown in the constant record in the
program: А = 2.0
The values of real constants and variables consist of an integer part, a decimal point, and a fractional
part. The values can be positive or negative. The integer part and the fractional part are made of
digits from 0 to 9. The amount of significant figures after decimal point can reach the value of 15.
Example:
18
Type bool
The values of bool type are values of Boolean (logical) type that contain falsehood or truth.
In order to learn the notion of Boolean type, let's consider a small example from our everyday
life. Say, a teacher needs to account the presence of textbooks of the pupils. In this case, the
teacher will list all pupils on a sheet of paper and then will tick in a right line whether a pupil
has a textbook or not. For example, the teacher may use tick marks and dashes in the table:
Textbook on Textbook on Textbook on
List of Pupils
Physics Biology Chemistry
1 Smith V - -
2 Jones V - V
3 Brown - V V
25 Thompson V V V
The values in right columns can be of only 2 types: true or false. These values cannot be
attributed to either of the types considered above since they are not numbers at all. They are
not the values of color, taste, amount, etc., either. However, they bear an important sense. In
MQL4, such values are named Boolean, or logical, values. Constants and variables of bool
type are characterized through that they can only take 2 possible values: true (True, TRUE, 1)
or false (False, FALSE, 0). The values of constants and variables of bool type take 4 bytes in
the computer memory.
An example of using a variable of bool type in a program:
bool aa = True; // Boolean variable аа has the value of
true
bool B17 = TRUE; // Boolean variable B17 has the value of
true
bool Hamma = 1; // Boolean variable Hamma has the value of
true
Type string
19
The value of string type is a value represented as a set of ASCII characters.
In our everyday life, a similar content belongs to, for example, store names, car makes, etc. A
string-type value is recorded as a set of characters placed in double quotes (not to be mixed
with doubled single quotes!). Quotes are used only to mark the beginning and the end of a
string constant. The value itself is the totality of characters framed by the quotes.
If there is a necessity to introduce a double quote ("), you should put a reverse slash (\) before
it. Any special character constants following the reverse slash (\) can be introduced in a
string. The length of a string constant ranges from 0 to 255 characters. If the length of a string
constant exceeds its maximum, the excessive characters on the right-hand side will be
truncated and compiler will give the corresponding warning. A combination of two
characters, the first of which is the reverse slash (\), is commonly accepted and perceived by
most programs as an instruction to execute a certain text formatting. This combination is not
displayed in the text. For example, the combination of \n indicates the necessity of a line
feed; \t demands tabulation, etc.
The value of string type is recorded as a set of characters framed by double quotes:
"MetaTrader 4", " Stop Loss", "Ssssstop_Loss", "stoploss", "10 pips". The string value as
such is the set of characters. The quotes are used only to mark the value borders. The internal
representation is a structure of 8 bytes.
An example of using a variable of string type in a program:
string Prefix = "MetaTrader 4"; // Example string
variable
string Postfix = "_of_my_progr. OK"; // Example string
variable
string Name_Mass = "History"; // Example string
variable
string text ="Upper Line\nLower Line"; // the text contains
line feed characters
Type color
Literals
The value of color type represented as a literal consists of three parts representing the
numeric values of intensity of three basic colors: red, green and blue (RGB). The
value of this kind starts with 'C' and is quoted by single quotes.
The numeric values of RGB intensity range from 0 to 255 and can be recorded both
decimally and hexadecimally.
Examples: C'128,128,128' (gray), C'0x00,0x00,0xFF' (blue), C'0xFF,0x33,0x00' (red).
20
Integer Representation
21
Fig. 11. Color parameters for literal and integer representation of the constant color
value can be taken in modern editors.
Color Names
The easiest way to set a color is to specify its name according to the table of web
colors. In this case, the value of a color is represented as a word corresponding with
the color, for example, Red - the red color.
Black DarkGreen DarkSlateGray Olive Green Teal Navy Purple
22
DarkSalmon BurlyWood HotPink Salmon Violet LightCoral SkyBlue LightSalmon
Constants and variables of color type take 4 bytes in the computer memory. An example of
using such a variable in a program:
color Paint_1 = C'128,128,128'; // The value of gray was assigned
to the variable
color Colo = C'0x00,0x00,0xFF'; // The value of blue was assigned
to the variable
color BMP_4 = C'0xFF,0x33,0x00' // The value of red was assigned
to the variable
Type datetime
23
The constant is framed in single quotes and starts with 'D'. It is allowed to use truncated
values: either without date or without time, or just an empty value. The range of values: from
January 1, 1970, to December 31, 2037. The values of constants and variables of datetime
type take 4 bytes in the computer memory. A value represents the amount of seconds elapsed
from 00:00 of the 1st of January 1970.
An example of using a variable of datetime type in a program:
datetime Alfa = D'2004.01.01 00:00'; // New Year
datetime Tim = D'01.01.2004'; // New Year
datetime Tims = D'2005.05.12 16:30:45'; // May 12, 2005 4:30:45 p.m.
datetime N_3 = D'12.05.2005 16:30:45'; // May 12, 2005 4:30:45 p.m.
datetime Compile = D''; // equivalent of
D'[compilation date]
//
00:00:00'
In order to avoid possible 'questions' by the program about what type of data this or that
variable belongs to, it is accepted in MQL4 to specify the types of variables at the very start
of a program explicitly. Before a variable starts to participate in any calculations, it should be
declared.
Variable Declaration is the first mentioning of a variable in a program. At declaration of a
variable, its type should be specified.
Variable Initialization means assignment to it a value corresponding with its type at its
declaration. Every variable can be initialized. If no initial value is set explicitly, a numeric
variable will be initialized by zero (0) and a string variable will be initialized by an empty
line.
In MQL4, it is accepted to specify the types of variables explicitly at their declaration.
The type of a variable is declared at the first mentioning of the name of this variable.
When it is mentioned for the second and all subsequent times, its type is not
specified anymore. In the course of execution of the program, the value of the
variable can change, but its type and name remain unchanged. The type of a variable
can be declared in single lines or operators.