MQL4 Book

Preface Table of Contents Introduction to MQL4 Basics of MQL4 MetaEditor Program in MQL4 Operators Variables Programming in MQL4 Programming of Trade Operations Simple Programs in MQL4 Standard Functions Creation of a Normal Program About Complex Programs Appendixes

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.

Table of Contents

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

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 About Complex Programs 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 .

1. The dealing center in its turn is connected with other market participants . Fig. allowance/prohibition of the automated trading and many other useful parameters characterizing the current state. Fig. For a better understanding of the importance of these programs in trade management.Introduction to MQL4 Programming Before starting to study MQL4 programming. First of all it should be noted that programs discussed in this book can be used only as applications for working in MetaTrader 4 Client Terminal. 1 below shows the role of these programs in trade management. we will define the scope of our study. A program in MQL4 as a part of MetaTrader 4 Client Terminal. let's look at Fig. minimal distance of stop orders.banks and financial institutions. Client terminal is a part of the online trading system. 1.a set of parameters that inform about the market state and relations between a trader and dealing center. you must have got acquainted with the client terminal. 1). . This system also includes a server installed in a dealing center. The client terminal includes informational environment . It contains information about current prices. limitations on the maximal and minimal order size. If you are interested in MQL4 programming. The informational environment is updated when new ticks are received by the terminal (green line in Fig.

There are three types of applications created in MQL4 and intended for working in the client terminal: custom indicator .a program for graphical displaying of market regularities written according to an author's algorithm. Using this toolbar a trader can open. indicator) can work only as part of the client terminal provided it is connected to a server (dealing center). A trader's actions with built-in trading management tools result in the formation of trade orders. Fibonacci levels etc. scripts and custom indicators) that allow to conduct partially or fully automated trading and significantly widen the informational . 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). 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. Besides. The server allows only to process signals coming from a client terminal.Built-In Tools The client terminal contains built-in tools that allow conducting technical analysis of market and execute manual trading management.a program for executing one-time actions including execution of trade operations. 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.chm). Programming Tools Market analyzing and trade management in MetaTrader 4 Client Terminal is implemented with the help of programming tools. Application programs (Expert Advisor. script . which are sent to a server. nothing will happen on the server. 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. trend channels. passed to the client terminal. The scope of our study includes programs (Expert Advisors. For more information about the client terminal please refer to "Userguide" (ClientTerminal_folder\Terminal. Applications and manual management tools can be used in the client terminal simultaneously complementing each other. It also can form managing influences (red arrows). Expert Advisor . close and modify orders.a program that allows to automate a large part of trading operations and fully automate trading. For manual trading management the order management toolbar is used. MQL4 language allows creating such programs. For market analyzing one can use technical indicators and different line studies . script. the terminal has the option of automated management of stop order position. Programs of different types can be used simultaneously and exchange data.support/resistance lines. None of application programs are installed on the server. Fig.

This is why tick is an important event that makes the basic mechanisms of MQL4 programs run. How can we declare a variable.maintenance of trading (see Fig. finally. But don't forget to comment upon your code. Data Types Certain types of data are used in any programming language. What to do when a new tick incomes? What actions to take? This is control that moves to the forefront here. 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. Unlike the constant. Operations and Expressions Operations operate upon operands. The type of a variable is chosen according to its purpose. to implement a thought-out trading strategy. It may also help to relieve nervous tension and lower the number of errors appearing in periods of extreme emotional tension. which are available to a program during its execution. 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. select optimal parameters for applying these ideas and. the difference between these terms is explained. a variable is a programming code object that can modify its content. 'control' in algorithms. It is impossible to write a program without using unchangeable objects (constants) and/or objects that can be modified during the program execution (variables). In this book you will find the description of program components and the main rules of creating and using programs. 'comment' in programs are described. As the term suggests. you can make subtle errors. Programs for the automated trading possess much more potential possibilities than manual tools of trade management. set once for all. The main event when trading on financial markets is the change of price. 1). Constants and Variables The terms of constants and variables are introduced. . a constant is something continuous. Basics of MQL4 This section represents basic terms underlying programming language MQL4: Some Basic Concepts Such terms as 'tick' (a price change). What types of operations are there? What is typecasting 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 features of some operations. We will also consider in details examples of programs and parameters of informational environment of the client terminal. 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 of time.

In order to use the function from different locations in the program. An application operating with the client terminal may work within a long period of time. Requirements and specific examples of using operators are given. 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. A necessary action should not always be executed by a simple operator. The examples of using standard functions are given. Some Basic Concepts Thus. we don't characterize tick as just a new quote. The duration of Expert Advisor's operation depends on what program code is included in it. it is necessary to provide it with Function Parameters. Ticks are delivered to every client terminal by a server installed in a dealing center. but as an event to be processed by the client terminal. As appropriate to the current market situation. this affects symbol charts in the client terminal. An Expert Advisor is usually launched at the moment when a new tick comes. We will consider the process of the custom function creation. Within this time. several days or weeks. The Notion of Tick Tick is an event that is characterized by a new price of the symbol at some instant. . For this reason. Functions The necessity of getting a simple code brings us to the term of Function. Program Types Scripts. for example. The situation on financial markets changes continuously. make a trading decision. Each application is executed according to the rules set for programs of a certain type. For example. Ticks provide the client terminal with information about price changes on the market. the subject of our interest is a program written in MQL4. it is necessary to describe the basic concepts that characterize a program and its interrelations with information environment. this group should be included into one compound operator. Before we start a detailed presentation of the rules of writing programs. but each of them brings a new quote . ticks may be received more or less frequently. It is necessary to understand the purposes of each type of programs in order to use MetaTrader 4 Client Terminal in the best way. Normal EAs complete one information-processing cycle during some tenths or hundredths of a second. If it is required that a group of operators is executed as one big operator. the EA can have processed some parameters. The MetaTrader 4 Client Terminal is known to work online. an Expert Advisor (EA) does not work continuously all the time.the cost of one currency expressed in terms of another currency.Operators Simple and compound operators.

. 2 that shows the general nature of transferring control to. from and within a program. The client terminal. It continues working with maximum performance during the entire period of time it is launched on PC.provide the trader with some useful information. When a new tick is received. Its status is higher than that of the program. does not stop its operation. the program returns control to the client terminal and cannot be launched by its own. The Notion of Control Speaking about the code execution flow in a program. the client terminal transfers the control to the program. we will use the term of 'control'. Let's refer to Fig. when the control has already been transferred to the program. forced termination of the program) are an exemption. the program makes its appropriate operations again and returns to the waiting mode. Having finished this part of its work. it returns control to the client terminal by itself. 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. Control can be transferred within the program from one code line to another one. we are mostly interested in the part of control that is transferred within a program. Dynamic actions of the user (for example. In other words. Like speakers address a meeting and then give the floor to others. logically completed fragments of a program. Control is a process of carrying out of actions preset by the program algorithm and the client terminal features. Control is transferred in a way similar to that of giving someone the floor to speak at a meeting. the client terminal and the program transfer control to each other. the client terminal cannot return control from the program by itself. The program code starts to be executed at this moment. The detailed description of how the appearance of a new tick influences program operation follows below. the client terminal dominates. Before the program is launched. After it has completed its operation. This new tick launches the Expert Advisor again. etc. the control is under the supervision of the client terminal. like the authority of the chairman of a meeting is larger than those of an ordinary speaker. after it has transferred the control to the program. as well as from the program to the client terminal. whereas the current speaker takes the word for only a limited period of time). whereas the arrows between the circles show how control is transferred from one fragment to another. Circles shown in the figure characterize some small. the EA goes to waiting mode until a new tick comes. However. At that. as well as its interaction with the client terminal. When discussing the matters of performance and internal structures of programs.

What and according to what rules can be written in these lines will be considered below in all details. the control is transferred to another fragment.for example. general order of program execution consists in sequential transfer of control from one line to another in the top-down direction. The program contains program lines. etc. some mathematical calculations are made. Here. Until the current fragment of the program is executed. it is only important to emphasize that every logically completed fragment is executed . it retains the control. The sign of a one- . Comment is an optional and nonexecutable part of a program. 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. As soon as the last fragment is executed. a trade order is formed. It means that a ready program will work according to its code irrespective of whether there are comments in it or not. However. Thus. a message is displayed on the screen. A one-line comment is any sequence of characters following double slash (//). 2. control within a program is transferred from one logically completed fragment to another as they are executed. So. After it has been fully completed. comment is an optional part of a program. The Notion of Comment A program consists in two types of records: those making the program itself and those being explanatory texts to the program code.Fig. There are one-line and multi-line comments. the program will transfer (return) control to the client terminal. comments facilitate understanding of the program code very much.

in order to explain our codes and make them more intelligible. The term of constant in a program is similar to the same term used in mathematical equations. an object that has a value. Comments are widely used in coding. A multi-line comment starts with the characters of /* and is ended by */ (see Fig. To describe the nature of a constant used in an algorithmic language in as many details as possible. Constants of the kind cannot be considered similar to constants in an algorithmic language. We will use comments. let us refer to well-known physical and mathematical constants. 3. in mathematics: Pi = 3. It is an invariable value. Example of comments in a program. Those are. Comments are used to explain the program code. They are usually displayed in gray in codes.8 m/s/s. Constants and Variables The terms of 'constant' and 'variable' are considered in one section since these terms are very close in themselves. in physics: free fall acceleration that is always equal to 9. 3). The Notion of Constant Constant is a part of a program. The human race has discovered the constants. Fig. the values of which do not depend on us in any way.14. for example. too.line comment is ended by line feed. A good program always contains comments. .

so the terms of 'constant' and 'the value of a constant' are full synonyms. "Kazan" Fig. For example. 5. The state of the memory cell of a constant when setting the value to the program. The constant is characterized only by its value. numbers 3 and 7 are constants. A Constant in the memory of a PC. For each constant in the program. This is the closest analogy of constants used in MQL4 programs. The values of such constants are fully dependent on the will of the person that has made the equation. The Properties of 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. .The term of constant is also used in mathematical equations. true. the computer allocates a part of its memory of the necessary size. 5). 4. 3.14. The value of a constant cannot be changed during execution of the program neither by programmer nor by computer (Fig. Exemplary Constants: 37. in the equation of Y = 3 * X + 7. 6). Fig. A constant (as a value) is placed by a programmer in the code at the stage of its creation. The value of the constant remains always the same.

qwerty_123 The following identifiers of variables represent the names of different variables: a_22 and А_22.e. MQL4 is case-sensitive. beta. The Notion of Variable Variable is a program part that has a value and a name. The difference between them consists only in that the value of a variable in mathematics is always implied. The term of 'variable identifier' is the full synonym of 'variable name'. Let us refer to Fig. Fig. Massa and MASSA. However. 6. 3. digits. the computer allocates a part of its memory of the necessary size. The name (identifier) of a variable can consist of letters. Exemplary variable names: Alpha. true. NuMbEr.14. The variable is put into the code text by its author at the stage of coding as a variable name. The Properties of Variable The property of a variable is its capability to get a certain value from the program. it must start with a letter. It is impossible to change the value of a constant during the program operation. alFa. For each variable in the program. A_37. A37. The term of variable in MQL4 is similar to that accepted in mathematics. Num.. 7 and study the construction of a variable. i. S and s are not the same. underscore. whereas the value of variable in an executing program is stored in a special memory cell in the computer. Exemplary values of variables: 37. .The value of a constant cannot be changed during the program operation. retain it during the period of operation of the program and set this value to the program when requested by the program. "Kazan".

8).e. the variable retains its value. If a program has referred to a variable. If a program while being executed meets the name of a variable.. This results in that the preceding value of the variable is deleted. A variable is not related to the executing program for a certain period of time. There is a value of a variable in the memory cell of the computer. 9). the programmer can set any name for the variable. 7. 8.Fig. this value remains unchanged. At that. This value can be requested for processing and changed by the program. According to the algorithm of the program. The state of the memory cell of a variable when setting the value to the program. the program may refer to other variables or make necessary calculations. The name of a variable will never be changed. Fig. it keeps it unchanged. However. The name of a variable is never changed. the latter one sets its value to the program. During this period. neither programmer nor the computer. A Variable in the memory of a computer. In this case. whereas the program gets the copy of the value contained in the memory cell allocated for this variable (Fig. whereas a new value of the variable set by the program takes its place (Fig. the program refers to this variable in order to get its value for processing. it can become necessary to change the value of a variable. Between "sessions" of communication with the program. whereas the variable gets this value from the program. nor the program has any technical feasibility to change the name of the variable. the value of the variable remains the same. When the value of a variable is set to a program. i. When writing a code. the program sets to the variable its new value. All necessary modifications are made in the memory cell. . as soon as the ready program is launched.

there can be a line in the program that contains the following: В = 33. 5. The name of the variable is always unchanged. The program has found an expression to the right from the equality sign and is trying to calculate it. constants and variables can be found in operators. Variable В gets value 10 from the program. The program refers to variable A by the name. Variable A gets value 7 from the program. Executing these lines. 6. In the code below. A and B are variables. 4. 9. // Line 3 In this case. Line 2: 1. 7 and 3 are constants: A = 7. Constant 7 sets its value to the program.The value of a variable can be changed by the program. the program will make the following steps: Line 1: 1. B = A + 3. // Line 1 // Line 2 Fig. The state of the memory cell of a variable when getting the value from the program. 3. The program makes calculations (7 + 3). For example. 2. Variable A sets its value (7) to the program. 2. Exemplary Constants and Variables in a Program In a program. the following will be done at execution of the program: . Let us study how a program works with constants and variables. Constant 3 sets its value to the program. The value of a variable can be changed during the program operation.

two. blue. seven). amount of opened and pending orders (3 orders).1. A constant and a variable in a program. Variable B gets (new) value 33 from the program. color . Constant 33 sets its value to the program. and the values returned by functions): int . for example: amount of bars in the symbol window (16000 bars). Similar limitations can be found in most of modern algorithmic languages. string . double . For example. but apples cannot be added to square meters or to temperature. Type int The values of int type are integers. 10 shows constants and variables in the program code: Fig.integers. green). amount (one and a half. two.real numbers. Like normal objects of life have certain types characterizing their color (red. This type includes values that are integer by their nature. The name of variable B remains unchanged during all these events.Boolean (logical) values.values of color type. we will mean the type of the value of a constant. whereas the value of the variable will change. Speaking about data type. the following types are distinguished (for the values of constants. It is easy to notice that variable B gets value 10 at a certain stage of the program execution. three. distance in points between the current symbol price and the order Open Price (15 points). 10. In MQL4. variables. The following values are integers. For example. Fig. apples can be added to apples. There are 2 types of integer values: . sweet). and then it gets the value of 33. yellow.values of string type. 2. datetime . the amount of attempts to open an order cannot be equal to one and a half. bool . of a variable and the value returned by a function (the notion of function is considered in the section of Functions). Data Types It is a common knowledge that only equitype values can be added or subtracted. their taste (bitter. Amounts representing such objects as events can also be integers only. but only to one. MQL4 uses data of different types.values of date and time. etc. sour.

25.e.0 The values of real constants and variables consist of an integer part.5001 -765456.07 0. The amount of significant figures after decimal point can reach the value of 15.4 should be considered in the program as double. In the computer memory. The current value of a variable can have a fraction part consisting of only zeros. and a fractional part. since this value has a fractional part. -379. 2147483647. An example of using a variable of int type in a program: int int int int int Art B_27 Num Max Min = = = = = 10. the result of the program operation will be void. Example values of this type can be any values that have a fractional part: inclination of the supporting line. this reasoning is wrong. 1. It means that variable A = 2. symbol price. 0X1. The values of constants and variables of int type take 4 bytes of the memory of a computer. variable A has also to be of double type. 5. Sometimes you can face problems designating variables when writing your code. Let us consider a small example: A program has opened 12 orders within a week. 12. Example: 27. // // // // // Example Example Example Example Example integer integer integer integer integer variable variable variable variable variable Type double The value of double type are real numbers that contain a fractional part. If the value of a constant or a variable is beyond the above range. The values can be positive or negative. mean amount of orders opened within a day.7 * e-308 to 1. -1. -2147483648. Values of int type must be within the range from -2 147 483 648 to 2 147 483 647. the values of constants and variables of double type take 8 bytes.. 11.123456789012345 The values of double type may range from -1. 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.0 2. 0xff340.12 -1. 0xAC3 0X2DF23. The separating point must also be shown in the constant record in the program: А = 2. It is important that that value of this variable is real by its nature. -1. Hexadecimal values can consist of Latin letters from A to F or from a to f. a decimal point. 2. The integer part and the fractional part are made of digits from 0 to 9.7 * e308. However. digits from 0 to 9.Decimal values can consist of digits from 0 to 9 and be either positive or negative: 10. 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 is not always clear to a programmer what type (int or double) the variable belongs to. 21. They must begin with 0x or 0X and take positive or negative values: 0x1a7b. An example of using a variable of double type in a program: .0 198732. variable A can be considered as int. 0X13AAB. -12345. i. In this case.

They are not the values of color.. In MQL4. However. 3 List of Pupils Jones .. taste. The values of constants and variables of bool type take 4 bytes in the computer memory... Smith Textbook on Physics V V . store names. etc..double double double double double Art B_27 Num MMM Price_1 = = = = = 10. // Boolean variable аа has the value of true // Boolean variable B17 has the value of true // Boolean variable Hamma has the value of true // Boolean variable Asd // Boolean variable Nol // Boolean variable Prim has the value of has the value of has the value of Type string The value of string type is a value represented as a set of ASCII characters.123. either. let's consider a small example from our everyday life.. A string-type value is recorded as a set of characters placed in double quotes (not to be mixed . such values are named Boolean. = 0. bool Hamma = 1. 0). -1. FALSE. 0. Say.. In order to learn the notion of Boolean type. 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. V V The values in right columns can be of only 2 types: true or false. for example.07.2756. etc. In this case. In our everyday life.. -12. they bear an important sense. a teacher needs to account the presence of textbooks of the pupils. amount. An example of using a variable of bool type in a program: bool aa = True. bool B17 = TRUE. Constants and variables of bool type are characterized through that they can only take 2 possible values: true (True. These values cannot be attributed to either of the types considered above since they are not numbers at all. bool Asd false bool Nol false bool Prim false = False. For example. V - Textbook on Bio Brown Thompson 25 . TRUE. = FALSE. a similar content belongs to.0. car makes. or logical. 1) or false (False. values.. the teacher may use tick marks and dashes in the table: 1 2 . 1.5. // // // // // Example Example Example Example Example real real real real real variable variable variable variable variable Type bool The values of bool type are values of Boolean (logical) type that contain falsehood or truth.

The length of a string constant ranges from 0 to 255 characters. It may seem to be a bit unusual. = "History". It is a constant or a variable. red. the first of which is the reverse slash (\). The internal representation is a structure of 8 bytes.with doubled single quotes!). generally speaking. white. the value of which is a color. but it is very simple. green and blue (RGB). yellow. you should put a reverse slash (\) before it. The value of this kind starts with 'C' and is quoted by single quotes. A combination of two characters. The value itself is the totality of characters framed by the quotes.) is a common knowledge. etc. "10 pips". is commonly accepted and perceived by most programs as an instruction to execute a certain text formatting. OK". ="Upper Line\nLower Line". Quotes are used only to mark the beginning and the end of a string constant. The values of color constants and variables can be represented as one of three kinds: 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. Integer Representation .128' (gray). It is easy to imagine what a variable or a constant of color type may mean. Examples: C'128.128. the value of a color constant is a color. If there is a necessity to introduce a double quote ("). The meaning of 'color' (blue. If the length of a string constant exceeds its maximum. The numeric values of RGB intensity range from 0 to 255 and can be recorded both decimally and hexadecimally. \t demands tabulation. green. etc. "stoploss". the combination of \n indicates the necessity of a line feed.0x33. "Ssssstop_Loss". For example. This combination is not displayed in the text. Like the value of an integer constant is a number. " Stop Loss". C'0xFF. the excessive characters on the right-hand side will be truncated and compiler will give the corresponding warning. The quotes are used only to mark the value borders. Any special character constants following the reverse slash (\) can be introduced in a string. The string value as such is the set of characters.0xFF' (blue). C'0x00.0x00. // Example string // Example string // Example string // the text contains line Type color The value of color type is a chromatic value. The value of string type is recorded as a set of characters framed by double quotes: "MetaTrader 4".0x00' (red). An example of using a variable of string type in a program: string Prefix variable string Postfix variable string Name_Mass variable string text feed characters = "MetaTrader 4". = "_of_my_progr.

Examples: 0xFFFFFF (white). You have just to select a color in your editor and copy the values found in its description to the corresponding color value representation in your code. green and blue components in the selected value of color. Representation of the values of color type as integers and as hexadecimal literals is very user-friendly. and BB . They represent the decimal value of a hexadecimal integer representation. 0x008000 (green).green.Integer representation is recorded as a hexadecimal or a decimal number. A hexadecimal number is displayed as 0xRRGGBB where RR is the value of red intensity.blue. The majority of modern text and graphics editors provide information about the intensity of red. GG . 32768 (green). 16777215 (white). . Decimal constants are not directly reflected in RGB.

Red . Color Names The easiest way to set a color is to specify its name according to the table of web colors. 11. for example.the red color. In this case. the value of a color is represented as a word corresponding with the color. Maroon Black DarkGreen DarkGoldenrod MediumSpringGreen Orange Blue DarkViolet Indigo DarkSlateGray DarkSlateBlue LawnGreen Magenta Gold FireBrick MidnightBlue DarkBlue MediumVioletRed CadetBlue Yellow Red Sienna Olive DarkOliveGreen SaddleBrown MediumSeaGreen DarkOrchid Chartreuse Turquoise DarkGray Violet Silver Pink Gray MediumBlue Chocolate Lime Brown Green Teal ForestGreen Crimson Navy OliveDrab SteelBlue Aqua DimGray Purple LightSeaGreen DarkOrange Goldenrod SeaGreen DarkTurquoise LimeGreen Peru YellowGreen SlateGray Tomato LightSlateGray MediumPurple DarkSalmon PaleGreen LemonChiffon Lavender Moccasin Plum IndianRed DeepSkyBlue SpringGreen SlateBlue OrangeRed BlueViolet Orchid Tan MediumOrchid PaleVioletRed BurlyWood Thistle Beige Khaki DeepPink MediumTurquoise GreenYellow HotPink Coral MediumAquamarine CornflowerBlue Aquamarine PeachPuff Salmon DodgerBlue DarkSeaGreen RoyalBlue SandyBrown MediumSlateBlue LightSkyBlue LightGray Bisque Ivory LightCoral LightSteelBlue Wheat SkyBlue RosyBrown DarkKhaki LightPink MistyRose PowderBlue AntiqueWhite OldLace Gainsboro LightGreen LightSalmon NavajoWhite Linen LightBlue PaleGoldenrod PapayaWhip PaleTurquoise Cornsilk WhiteSmoke Seashell LightYellow LightGoldenrod BlanchedAlmond Honeydew LightCyan AliceBlue .Fig. Color parameters for literal and integer representation of the constant color value can be taken in modern editors.

A value represents the amount of seconds elapsed from 00:00 of the 1st of January 1970. month.01 00:00'. 32768. The values of constants and variables of datetime type take 4 bytes in the computer memory.0x00. 16777215.01. An example of using such a variable in a program: color Paint_1 = C'128. // The value of red was assigned to // The value of yellow was assigned to // The value of black // The value of white was assigned to was assigned to Type datetime The value of datetime type is the values of date and time. // // // // // New Year New Year May 12. = White. The constant is framed in single quotes and starts with 'D'. May 12. D'2005.0x33. year). and second. = Yellow.LavenderBlush MintCream Snow White Constants and variables of color type take 4 bytes in the computer memory. the variable color Colo = C'0x00. hour. The values of this type can be used in programs to analyze the moment of beginning or ending of some events. minute. etc. 0x008000.0x00' the variable color K_12 = the variable color N_3 = the variable color Color = the variable color Alfa = the variable color A the variable color B the variable color Colorit the variable color B_21 the variable 0xFF3300. 1970. day (or day.12 16:30:45'. The range of values: from January 1. // The value of gray // The value of blue // The value of red was assigned to was assigned to was assigned to // The value of red // The value of green // The value of white // The value of green was assigned to was assigned to was assigned to was assigned to = Red. D''.2005 16:30:45'.m. month. equivalent of D'[compilation . or just an empty value. to December 31. = Black. It is allowed to use truncated values: either without date or without time. D'12.05.0xFF'.128. 2005 4:30:45 p.05. the variable color BMP_4 = C'0xFF.2004'.128'. An example of using a variable of datetime type in a program: datetime datetime datetime datetime datetime Alfa Tim Tims N_3 Compile = = = = = D'2004. The constants of date and time can be represented as a literal line consisting of 6 parts that represent the numeric value of year. 2005 4:30:45 p. D'01. 2037. workday start/finish.m.01. including the releases of important news.

but its type and name remain unchanged. the initial value of the variable being 3. all of int type. // Declaration of several variables in one line This record means that there will be variables Var_1. The type of variables is never specified anywhere in the subsequent lines of the program. Every variable can be initialized. it is accepted in MQL4 to specify the types of variables at the very start of a program explicitly. it is accepted to specify the types of variables explicitly at their declaration. The type of a variable can be declared in single lines or operators. Box and Comm.7.date] // 00:00:00' Variable Declaration and Initialization In order to avoid possible 'questions' by the program about what type of data this or that variable belongs to. a numeric variable will be initialized by zero (0) and a string variable will be initialized by an empty line. Variable Declaration is the first mentioning of a variable in a program. every time the program calls a variable it "remembers" that this variable is of the type . Before a variable starts to participate in any calculations. its type should be specified. However. Variable Initialization means assignment to it a value corresponding with its type at its declaration. At declaration of a variable. it should be declared. In one line. A variable can be declared in a single line: int Var_1. Box. the value of the variable can change. operator // Variable initialization in an assignment This record means that there will be variable Var_5 of double type used in program. // Variable declaration in a single line This record means that there will be variable Var_1 (variable declaration as such) and the type of this variable will be int in the given program. It means that the variables listed above will be considered by the program as variables of integer type. In MQL4. several variables of the same type can be declared: int Var_1. If no initial value is set explicitly. When it is mentioned for the second and all subsequent times.7. used in the program. its type is not specified anymore. Comm. The type of a variable is declared at the first mentioning of the name of this variable. In the course of execution of the program. Variables can also be initialized within operators: double Var_5 = 3.

. 14. 13. you cannot judge about the type of a variable by its name. Example of variable initialization.. The name of a variable has no relation to its type. The type of variables is declared only once. Fig. As calculations progress in the program. the values of variables can change. Example of variable declaration in a single line. However. the type of any variable can be declared only once within one program. Example of variable declaration in a single line. Fig. A name given to a variable can also be used for variables of any types in different programs. 12.that has been specified at its declaration.e. a semicolon being put at the end of line. The type will not be specified anymore for the second and all subsequent times when the variable is mentioned. Fig. It is allowed to declare several variables of one type simultaneously. Examples of Variable Declaration and Initialization Variables can be declared in several lines or in a single line. i. but their type remains unchanged. at the first mentioning of the variable. variables are listed separated by commas. In this case. It is allowed to declare and initialize variables in operators. The type of declared variables will not be changed during execution of the program.

signs = and + are operational signs. relational operations. the calculated value of which is characterized by a data type. Here we will get into possible relationships between these data (square meters still cannot be added to apples). there are some natural limitations and the rules of using operations in expressions. no special analogies are needed. whereas n + m is an expression. it is the same as operations and expressions in simple arithmetic. Operation is an action made upon operands. that of array . Operations and Expressions In order to understand what importance operations and expressions have in MQL4. assignment operations. In the preceding section of the book. Practically. In MQL4. it is sufficient to understand operands as constants and variables we have already studied before). n and m are variables. at this present stage of learning. Types of Operations There are the following types of operations in MQL4: arithmetical operations.Fig. 'Operation'. an array component or a value returned by a function (the term of function is considered in the section of Functions. 15. a variable. Operation symbol is a preset character or a group of characters that order to execute an operation.in the section of Arrays. members f. Expression is a sequence of operands and operation symbols. Variable initialization in the header of a compound operator. 'Operation Symbol' and 'Expression' Operand is a constant. we learned about the necessity to present data of different types. Everybody understands that in the record of f = n + m. . Boolean (logical) operations. The Notions of 'Operand'. it is a program record.

if x is not equal to y . Arithmetical Operations Symbol + * - The following symbols belong to arithmetical operations symbols: Addition of values Operation x+2 3*x x/5 y++ y-- Subtraction of values or sign change Multiplication of values Quotient of division Residue of division x . otherwise. It is prohibited to use operations outside operators. you can use it. The possibility to use an operation is determined by the properties of operators (if the operator's properties allow you to utilize this specific operation. Only in operators their use makes sense and is realized in a program. you shouldn't utilize this operation).y ++ -- % / Addition of 1 to the value of the variable minutes = time Subtraction of 1 from the value of the variable Assignment Operations The following symbols belong to assignment operations symbols: Symbol += *= %= /= -= = Assignment of the value x to the variable y Increase of the variable y by x Reduction of the variable y by x Division of the variable y by x Operation у= у+ Multiplication of the variable y by x Residue of division of the variable y by x y- y* y/ y% Relational Operations The following symbols belong to relational operations symbols: Symbol == != True. function call. Operations are used in operators (see Operators).3.bitwise operations. comma operation. if x is equal to y Operation True. y = .

The binary representation of x is shifted by y places to the left. in which x and y have different binary values. in which x or y does not contain 0. x = x << y. if x is less than y True. and the value of the expression contains 0 (FALSE) in all other places. . x = x >> y. if x is equal to or more than y Boolean (Logical) Operations The following symbols belong to Boolean operations symbols: Symbol || ! NOT (logical negation) Operation !х Example TRUE(1). b = x ^ y.< <= >= > True. b = ~n. in which the values of the variable contain 1. The value of the expression contains 1 in all places. if any value of the values is true TRUE(1). b = x | y. The binary representation of x is shifted by y places to the right. The value of the expression contains 1 in the places. b = ((x & y) != 0). the emptied places to the left will be filled with zeros. The value of the expression contains 1 in all places. if all values are true Explanations && OR (logical disjunction) AND (logical conjunction) x < 5 || x > 7 x == 3 && y < 5 Bitwise Operations Bitwise operations can only be performed with integers. it means that all places emptied to the left will be filled with zeros. It contains 0 in all other places. The bitwise operation AND of the binary representations of x and y. if the value of the operand is FALSE(0). in which both x and y contain non-zero. The bitwise operation EXCLUSIVE OR of the binary representations of x and y. It contains 0 in all other places. if the TRUE(1). and it contains 0 in all places. The value of the expression contains 1 (TRUE) in all places. FALSE(0). if x is equal to or less than y True. in which the values of the variable contain 0. This right shift is logical. The following operations belong to bitwise operations: One's complement of the value of the variable. if x is more than y True. The bitwise operation OR of the binary representations of x and y.

the variables of double type. one may think that coding is a mysterious and very complicated process.Comma Operation Expressions separated by commas are calculated left to right. we considered the methods of variable declaration. Functions and in the chapter named Operators) My_function (Alf. operators and expressions. All side effects of calculations in the left expression can only occur before the right expression is calculated. Bet. let's consider some examples. for(i=0. Del) // Calling for a function with arguments Function Call Function call is described in all details in the section of Function Call. // The number of John's pencils // The number of Pete's pencils // Total number In this case.0. Looking at the symbols of operations. double C = A + B. for example. you just need to make head or tail of some intensions. i. Thus. Let us denote the number of John's pencils as variable A and the number of Pete's pencils as variable B.. John has 2 pencils. // Loop statement Operators and functions are considered in the sections of Operators. The value type of the expression: . there can be a half of a pencil). accessible only for for a kind of elite.e. Operations on Similar Operands If an elementary school pupil were told that. The answer will be: С = А + В In the section named Data Types. it is something that can basically exist as a part (for example. The transferred parameter list (see below) can be considered as an example. we will consider pencils as real variables. The type and value of the result coincide with the type and value of the right expression. Pete has 3 pencils. i<100. he or she would have to base his or her presentation on such terms as operands. the poor schoolchild would surely find it impossible. So we can code the solution.0.e. operation "+" applied to adding together the values of the one-type variables is quite illustrative. Gam. when solving the problem about the number of pencils. as follows: double A = 2. However. Pencils are things. How many pencils do these boys have?:) Solution. To be sure that this is really so. whereas the result will be denoted as C. coding isn't really difficult at all. double B = 3.. i++.j--) Print(array[i][j]). Problem 1. i.j=99.

Pupils go to the blackboard and answer in class. In this example. // Multiplication of two real numbers // Division of two real numbers Similar calculations can be performed with integers. double C = B . // // // // // Integer Integer Difference between two integers Product of two integers Quotient of two integers The situation is a bit different with the variables of string type: Problem 3. there is a grocery store named "Arctic". since we consider events that are integer by their nature (you cannot go to the blackboard 0. int Y = 3. the operation "-" is used in the similar simple manner: int int int int int X Y Z Z Z = = = = = 2.0. too. the answer at the blackboard can be good or poor. numbers // The number of John's pencils // The number of Pete's pencils // The difference between two real Other arithmetical operations are used in a similar manner: double C = B * A. Pete's passages as variable Y. there is an establishment named "Hairdressing Saloon". Pete went 3 times. product of or quotient of integers. Let us denote John's passages as variable X.5 times. this will be the double type. In our case. John went 2 times. The solution of this problem can be written as: int X = 2. but we're only interested in the number of such answers or passages). the result as Z. double C = B / A. Y . int Z = X + Y. Y * X.0.A + B will be the type of the variables that are components of the expression. double B = 3. We will get the similar answer for the difference between the values (How many more pencils does Pete have than John?): double A = 2. 3.5 times or 1.A. How many times did boys go to the blackboard in total? Solution. What is written on . At another corner of the same house. At one corner of the house. Problem 2. Y / X. // Number of John's passages // Number of Pete's passages // Total number In case of calculation of the difference between.X. we have to use the variables of int type.

// String 1 // String 2 // Sum of strings The value of variable Ans will be the string that appears as follows: ArcticHairdressing Saloon We obtained a not-much-to-look-at. string Ans = W1 + W2. whereas John has 2 pencils. it is wrong. How many in total? As far as the formal logic is concerned. It stands to reason that events cannot be added together with things. string W2 = "Hairdressing Saloon". there is a grocery store named "Arctic". Let's consider some problems that deal with typecasting.:) With the same degree of hopelessness (as far as normal reasoning is concerned) we can ask either: 1. How many in total?. Before execution of operations (all but assignment operations). string Ans= W1 / W2. but absolutely correctly formed value of string type. whereas Pete went 3 times to the blackboard. in the sequence they are mentioned in the expression. It is easy to code a program that would give us the necessary answer: string W1 = "Arctic". What is written on the house? .W2. If we add together variables of string type. whereas before execution of assignment operations they are modified to the target type. Problem 5. or 2. At one corner of the house. string Ans= W1 * W2. Of course. we should consider gaps and other punctuation in our practical coding of such problems. they are modified to a type of the highest priority. // Not allowed // Not allowed // Not allowed Typecasting Typecasting is modifying (mapping) of types of the values of an operand or an expression. the ill-posedness of the problem is obvious. you are allowed to add together the values of string constants and variables. In MQL4. John has 2 pencils. Problem 4. Any other arithmetical operations with variables of string type are prohibited: string Ans= W1 . strings are simply added one by one.the house? Solution.

The values of int. Fig. datetime and double. double and string. we can only choose between three data types:int. you should refer to typecasting rules. belong to the numeric data type. So.e. what type will be the value of an expression composed of operands of different types? In MQL4. The values of string type are represented in the computer memory as a sequence of characters. whereas the variables of doubletype are represented as double-precision numbers with a floating point. The values of double type are represented in the computer memory as real numbers. color. color and datetime types are represented in the computer memory as integers. bool. We mentioned above that the values of the variables of int. color and datetime types are represented in the computer memory as integers. colorand datetime type is a number. bool. Representation of different data types in the computer memory. double. datetime and double types are the values of numeric type. The values of int. real numbers. bool. whereas those of doubletype . i. color and datetime types will prove themselves in an expression in the same way as the values of int type. The values of bool.. 16. The variables of int. The values of string type are the values ofcharacter type. The internal representation of constants and variables of int. 16).If you want to solve both problems above correctly in MQL4. we have to talk about how variables of different types are represented in the computer memory. if we want to find out about the type of an expression that consists of variables of different types. The value of constants and variables of string type is a set of characters (Fig. the rule of implied typecasting is accepted: . Data types. bool. such as int. bool. color and datetime types are represented in the computer memory as integers. So. bool. color.as real numbers. First.

whereas the double type has a higher priority. Well. During execution of the assignment operation: First. To cast the type of expression A+Y. we applied the first part of the implied typecasting rule. then this result becomes the value of the integer variable F. but not about the type of variable F that is to the left of the assignment operation sign. the types int.int type. int Y = 3.2. int Y = 3. Calculation of the result of int type: double A = 2. int F = A + Y. color and datetime have equal priorities.0. Solution 4.0. // The number of John's pencils // The number of Pete's passages // Total number This situation differs from the preceding one by that the target type of variable F (to the left of the assignment operation sign). if we try to have a result as a value of double type: double A = 2. In compliance with the rule of implied typecasting. double F = A + Y. There can be two solutions for it. if the type of the expression to the right of the assignment operation sign does not coincide with the type of the variable to the left of the assignment operation sign. we need to know the value of the expression provided its operands are of different types. too: the type of expression A+Y is double. the type of expression A+Y is casted as int (according to the rule of integer calculations) and becomes integer 5. operands of two data types are used: А . the value of this expression will be a number of double type. the types mismatch. Y . the expression type will be transformed into the type having the highest priority. bool. the value of this expression is cast as the type of the variable to the left of the assignment operation sign. In the expression: A + Y. it is prohibited to cast the values of string type to any other target type. it is double type.if the expression contains operands of different types. A similar situation occurs.0. coincides with the type (double) of . whereas the type of variable F is int. this is called 'target-type cast'. The calculations have been performed according to the second part of the implied typecasting rule . Please note: We are talking only about the type of expression A+Y.'target-type cast'. in our case. the assignment operation is executed.1. let's return to Problem 4. The final result of calculations and manipulations is as follows: The value of the integer variable F is integer 5. In this case.double type. // The number of John's pencils // The number of Pete's passages // Total number First of all. Solution 4. and the string type has the highest priority. The value of this expression is real number 5. After calculation of the expression A+Y.

the value of variable Sum will be the following string: Arctic2. Features of Integer Calculations Integers are known to be the numbers without a fractional part. you will get an intuitive result. you must cast all differing types to a type with the highest priority. the value of variable A will first be cast to the string type (since this type is of a higher priority). According to the rule of implied typecasting. string Sum = W1 + A. double A = 2.0. This solution is wrong: string W1 = "Arctic". However. the target-type cast must be performed. we add together the values of two variables: the one of string type. if you execute a multiplication operation: int Z = X * Y. At the next stage. For example.2.of double type. // String 1 // Number of John's pencils // This is inadmissible In this case. If you add them together or subtract them. No questions come up at initialization of variables: string W1 = "Arctic". if: int X = 2. When the assignment operation is executed.00000000 Solution 5. // Addition operation. Typecasting with lowered priority is allowed only for numeric values. double A = 2. is string. Generally. The type of the resulting value to the right of the assignment operation sign will be string. there is no problem to calculate the value of variable Z: 2 + 3 = 5 Similarly. we break a prohibition of target-type cast for the values of string type.1. Let's now find a solution for Problem 5. and the other one . double A = 2. this value will be assigned to the string variable Sum. The result of calculations (the value of the double-type variable F) is real number 5. A possible solution for this problem: string W1 = "Arctic". // String 1 // Number of John's pencils // Implied transformation to the right Here. double Sum = W1 + A. so we don't have any target-type cast here. whereas strings cannot be transformed into numbers. // String 1 // The number of John's pencils Solution 5. As a result. int Y = 3. according to the rule. the rules given in this section are clear and simple: If you calculate any values. . The type of the value of expression W1+A. and then the one-type values will be added together (concatenation). in the right part. the string-type target cast to the types of lower priority is prohibited. // Multiplication operation. // First int variable // Second int variable and: int Z = X + Y. This is an error that will be detected by MetaEditor at creation of the program (at compilation).the expression A+Y. like in the preceding solution.

e. in this case. In the above example. other values of variables X and Y will produce other results. // Division operation It's easy to write 2 / 3.0*( 3*X/Z . consists of two summands. And this means that the type of expression X/Y is int. 3*X/Z .N) + D. . First. This expression contains two operations (multiplication and division) of the same rank.N) + D. the program will calculate the value and the type of the expression 3*X/Z . Order of Operations The calculating rule consists in the following: The value of an expression is calculated according to the priorities of arithmetical operations and left to right.N. if our program has to execute a division operation? int Z = X / Y. namely: 2 and (3*X/Z . This value (zero) will be assigned to variable Z at the end.of the expression 2. In order to calculate the expression to the right from the equality sign. so we will calculate this expression left to right. // The value of an int variable // The value of an int variable // Division operation.of the entire expression 2. However. The summand 2. Correspondingly. // Exemplary expression The expression to the right of the equality sign consists of two summands: 2.N. if: int X = 7.0*( 3*X/Z . then . int Y = 3. Let's consider the calculating order for an expression in the following example: Y = 2. X and Z. no typecasting takes place. its type being calculated according to the typecasting rule. we will calculate the value of expression 3*X. After that. each intermediate outcome being calculated according to the typecasting rules. For example. int Z = X / Y. then the value of 7 / 3 for the expression X / Y and variable Z is equal to 2 (two). So the result of finding the integer value of expression X/Y (= 2/3) is 0 (zero).N) and D.0*( 3*X/Z .the result is highly predictable: 2 * 3 = 6 But what result do we get. the summand 3*X/Z consisting of three factors. namely: 3. and the last . first. the expression to the right of the equality sign contains only integers.0*( 3*X/Z . what will be the value of expression X/Y and variable Z? The rule of integer calculations consists in that the fractional part is always discarded. the type of this expression being the same as the type of the variable X. in its turn. So. calculate the value of expression 3*X/Z.N). we will.. it is not an integer. The expression in parentheses.N).N) consists of two factors. i.0*( 3*X/Z . Then we will calculate the value of expression 3*X/Z.

When calculating expressions containing integers. an error may occur in your code.As is easy to see. In such a case. the final result may fully depend on a randomly formed fragment containing division of integers. Calculation of the expression 0*С (zero multiplied by С). the term and general properties of operators are considered. and С. 1. Problem 6. 3. the final result will be the same. If we calculate the values of expressions composed of the operands of int type. In the above example. If we replace these variables with constants with the same values. The answer is obvious: after the fractional part has been discarded. the value of the expression (3/5) is integer 0 (zero). The result is integer 0 (zero). First (from left to right) the value of the expression A/B will be calculated. this statement is true only for real numbers. Particularly (unlike the rules accepted in mathematics). General result (the value of variable Res_2) is integer 3 (three). the order of operands in an expression is very important. 2. in both cases. the former one differs in calculating of the types of values in intermediate outcomes. В. However. 2. Operators . The value of this expression is integer 18 (3*6=18). Res_2 = A*C/B. However. C = 6. B = 5. 3. if you use operands of different types in one complex expression. Calculation of A*C. we should always consider the intermediate outcome. (18/5) is integer 3 (three). the order of operations in a program is similar to that in mathematics. we consider just a small code fragment. According to the above rules. whereas the special properties of each operator are described in the chapter namedOperators. Such troubles do not occur in calculations using real numbers. Otherwise. which would be very difficult to find and fix later (especially in large programs). To demonstrate this. which exercises a significant influence on the final result of calculations. Calculation of the expression 18/B. General result (the value of the variable Res_1) is integer 0 (zero). The result of calculation is intuitively expected to be the same. you must pay greater attention to the contents of your program lines. the sequence of operands is of fundamental importance: int int int int int A = 3.Calculate the values of expressions А/В*С and А*С/В for integers А. in which the values of the variables of int type are calculated. Let's now follow the developments of calculating the expression A*C/B. let's consider a small example. Res_1 = A/B*C. However. // // // // // Value of Value of Value of Result 0 Result 3 int type int type int type (zero) (three) Let's follow the process of calculating the expression A/B*C: 1. In the section of Operators.

Specific Properties of Operators There are several kinds of operators. instructions) contained in the operators. Operator as such is just a record. If your PC has executed some transformations of data according to the instruction contained in an operator. when a computer is executing a program. nothing happens in operators as such. the computer that has all those memory cells and links between them experiences all the transformations inside. For example. Coding seems to be impossible for the person that has not completely learned this term. . For a computer. the property of an assignment operator is its ability to assign a certain value to the given variable. Any program contains operators. We can say that operator is an instruction containing the guide to operations (the description of an order).a common property and specific properties of different operators. We will only say here that all types of operators have their own properties that are typical only for their type and are not repeated in any other types. it is a phrase in an algorithmic language that prescribes a certain method of data conversion.they all are executed. The closest analogy to 'operator' is a sentence. Just as normal sentences compose the text of a story or of a novel. they continue staying in the program as composed by the programmer. Specific properties of operators are considered in all details in the corresponding sections of chapter Operators in this book. the sooner this programmer starts writing his or her own programs. wires or memory cells. Operator does not have any levers. The sooner and more properly a programmer learns what operators are and how they are applied in a program. the property of a loop operator is its multiple executions. Common Property of Operators All operators have one common property . executing a program running on it means (consecutively passing from one operator to another) complying the orders (prescriptions. Types of Operators There are two types of operators: simple operators and compounds. Operators of each type have their specific properties. so operators compose a program. you say: the operator has been executed. However. This is why.The Term of Operator One of the key notions of any programming language is the term of 'operator'. a certain sequence of characters. etc. Operator is a part of a program. Properties of Operators There are two kinds of properties of operators .

Go_My_Function_ind(). Using this separator. // Simple operator // Simple operator // Several operators in a line One operator.Mas_Big[s][1])." and is enclosed in braces. Compound Operators (Compounds) A compound operator consists of several simple ones separated by character "..TimeDay(Mas_Big[s][0]). in several . the PC can detect where one operator ends and another one starts.TimeHour(Mas_Big[s][0]). One operator may take several lines.Mas_Big[s][0]." (semicolon) is as necessary in a program as character ".Simple Operators Simple operators in MQL4 end with the character ". // Hour="." (semicolon)." (semicolon). // Mas_Big[s][1]= ". Every simple operator ends with character ". // Minute=". The compound operator contains a list of executable operators. i++.. Character ". lines Print(" " " " " Day= ". is located. In order to be able to use several operators where only one is expected to be located. The list of operators in a compound is separated by braces.TimeMinute(Mas_Big[s][0]). programmers use a compound operator (they also call it "block" or "block of code")." (full stop) is necessary in a normal text to separate sentences.// Mas_Big[s][0]= ". a=3. b=a*x+n. .. It starts with the conditional operator if(expression) followed by a compound. Examples of simple operators: Day_Next= TimeDayOfWeek(Mas_Big[n][0]+60). An exemplary use of a compound in a conditional operator. The presence of a closing brace marks the end of a compound operator. Several operators may be placed in one line.

. Compound operator. tt<=Kol_Point[7]. Examples of compound operators: // // // break. one.. . case 3: Buf_3[Pok-f+i]= Prognoz.// Nested operators (operator body) Ind = Nabor_Koef[ii][vv][0] + f. // Nested operators (operator body) } // Closing brace.Fig. // Nested operator (operator body) } // Closing brace. // . // . shows where the compound operator ends The body of a compound is always enclosed in braces and can consist of zero. } operator ends //---------------------------------------------------------------------------------------// Exemplary use of loop for (tt=1. The body of a compound operator is enclosed in braces. // // // Example of operator switch Operator switch(expression) Opening brace Nested operators (operator body) Nested operators (operator body) Nested operators (operator body) Closing brace.... // break. Examples of simple operators: . shows where the compound operator ends //---------------------------------------------------------------------------------------// Example of conditional operator if if (TimeDay(Mas_Big[f][0])!= 6) // if (expression) { // Opening brace Sred =(Nabor_Koef[ii][vv][2]+ NBh)*Point.. 17.Ind). // Nested operators (operator body) Print(" Ind= ". shows where the compound switch(ii) { case 1: Buf_1[Pok-f+i]= Prognoz. Every compound operator ends with a closing brace. or several operators. // break. tt++) // Operator for(expressions) { // Opening brace Numb = Numb + Y_raz[tt]*X_raz[ii][tt]. case 2: Buf_2[Pok-f+i]= Prognoz..

Operators cannot be executed for no reason or by exception. You should understand the phrase "operator format" as a set of format rules typical for the given type of operator. This use is fully acceptable. No operator may be composed beyond these rules.//--------------------------------------------------------------------------------// Example of operator for for (n=1. } // // // // Opening brace Simple operator Simple operator Closing brace. Requirements for Operators Operators must be written in the text of a program according to the format rules (how they must be represented in a code). // first operator (suboperator 1) else // Else-condition Norma = false. but absolutely admissible construction. Operator formats are in all details considered in the corresponding sections in chapter Operators of this book. In MQL4. This means that the program containing the wrong operator cannot be used. This is a rare.. If the program contains an operator composed against the format rules. in which they occur in the program. n++) // for(expressions) Mas[n]= Const_1+ n*Pi. the operators enclosed in braces are called "a block of operators". An exemplary block of operators: { Day_Next= TimeDayOfWeek(Mas_Big[n][0]+60). // second operator (suboperator 2) //--------------------------------------------------------------------------------- Several simple operators may be combined in a compound operator without any strict necessity. MetaEditor will produce an error message at compilation. // Nested operator (operator body) //--------------------------------------------------------------------------------// Example of conditional operator if if (Table > Chair) // if (expression) Norma = true. The direction of operators execution is accepted as left . Order of Operators Execution A very important characteristic of any program is the order of operators execution in it. Each type of operator has its own format. n<=Numb. b=a*x+n. This is the programmer who decides whether to enclose operators in braces or not. In this case. just for the sake of convenient code representation. the following order of operators execution is accepted: Operators are executed in the order.

The notes given in Solution 1 represent some dependences in paper form. Operators composing a compound operator are executed in the same way: any operator in the block of code starts being executed only after the previous one has been executed. A normal text on a sheet of paper: 1. This means that both simple and compound operators are executed just one by one (like the lines in poems: first we read the top line. Any assignment operator gives the machine the following order. All operators without any exceptions represent precise instructions that allow no ambiguities. they should be executed consecutively.Х = 2 2. X = Y . Х = 5 . They can only be used to inform the programmer about the relations between the variables. Solution 1. Writing and Execution of Operators: Examples The text of a program containing operators is not dissimilar in aspect to a normal text or a mathematical notation. let's see how an assignment operator works. // Line 1 // Line 2 Both in the first and in the second solutions. As an example. the lines in Solution 1 cannot be used in a program as they are. in operators. and so on). left to right. Nevertheless. Operators in a program are assigned for other purposes . literally: . However. We have an equation system: Y=5 Y-X=2 The numeric value of variable X is to be found. We'll solve a simple linear equation system and compare the representation of some mathematical calculations in a normal text and in a program code. because their appearance does not comply with the assignment operator format. Х = 3 Solution 2. whereas you must keep a well-defined order in a program. then the next lower. this similarity is only formal. one by one.they inform the machine what operations and in what order it must execute. 5 . Both operators in Solution 2 are the assignment operators. If there are several operators in one line. A normal text allows the notes to be placed in any sequence. then the next.to right and downwards. Problem 7.2 3. A text in a program: Y = 5. the notes (lines) have a completed content.2. then operators are executed in the nearest lower line in the same order.

many intermediate calculations are made when solving mathematical problems. They can help a mathematician to find a proper solution. For example. the programmer must well realize what and in what order will be executed in this program. not all mathematical calculations will be put in a program. Calculating the numeric value of the right part of the operator (5 . the record below . Passing on the next operator (line 2). Referencing to the right part of the operator (the right part is located between the equality sign and the semicolon). Any workable program contains expressions of a familiar sight. For this reason. 3. 5. because the set of characters 5 . but you can also find such expressions that you will be able to understand only if you rate them as possible operators in your program. Recording the numeric value (5) in the memory cell of variable Y. Only meaningful solutions can be included into a program. Recording the numeric value (3) in the memory cell of variable Х. it is sometimes necessary to pre-prepare operators. The computer has detected that the right part of the operator contains an expression. but turn out to be useless from the viewpoint of programming. In order to code a workable program.Х is not a variable. 7. and the second operator provides the formula to calculate the value of the variable X we are interested in.2). 9. For example. Performing steps 1-4 by the computer is execution of the first operator (line 1).Х = 2 used in the first solution contains an error.Calculate the value of the expression to the right of the equality sign and assign the obtained value to the variable to the left of the equality sign. Y = 5. 1. In the preceding example. Referencing to the right part of the operator. // Line 1 2. for example: original values of variables or formulas to calculate the values of other variables. Passing on the operator (line 1). This is why there is no memory cell for placing the numeric value of the expression calculated to the right of the equality sign. Let's follow the computer during execution of operators of the second solution. The computer has detected that the right part of the operator contains a numeric value. a record of 5 . // Line 2 6.2. the first operator bears information about the numeric value of variable Y. Performing steps 5-9 by the computer is execution of the second operator (line 2). 4. nothing else but variable can be located to the left of the equality sign in an assignment operator. 8. X = Y . For example. Particularly.

as well as the idea implemented by the engineer.. Such program construction has some incontestable advantages: first. is the analogue of a function. Similarly. The driver presses the pedal down. Function is a named. which will release the programmer from the necessity to insert the same fragments of the code in each newly created program. third. then the function of the same name will be called and executed. a function can be composed as a single file and use it in other programs. if a function call occurs in a program.X = X + 1. In our everyday life. whereas brake pedal is the analogue of function call.e. The general sense of a function is in taking a logically completed part of the code outside the basic text of the program.). Such a possibility exists in MQL4. Function description is a specific named part of a program intended for execution. second. whereas only the call for this part of the code remains inside the basic text of the program. calculates the expression in the right part of the assignment operator (3 + 1). Speaking about functions. the new value of this variable will be calculated and stored up to the next possible change. it is this operator that is widely used in coding). Take. i. the program text composed in such a manner is read much easier. too. we will consider two aspects: function description and function call. execution of which results in execution of a function. displaying a message or opening an order. Functions The Term of Function The most important technological breakthrough in computer engineering is the possibility of creation and storage of separate code fragments that describe the rules of data processing for solving a problem or a small task. a certain sequence of calculations or other actions will be performed (for example. the braking system of a car. The actuating mechanism that properly performs braking. . we calculate a new value of variable X: when executing the assignment operator (i. we can find many analogues of the function. etc. However. and writes the obtained value (4) in the memory cell provided for variable X.stop the car. and the actuating mechanisms perform some actions and . if necessary. for example. The machine will store this value of variable X until the variable X occurs in the left part of the equality sign in another assignment operator. one can easily see and.e. In this operator.. it is quite acceptable if you consider it as an operator (by the way. Function call (function reference) is a record. // Example of a counter seems to be wrong from the standpoint of mathematical logic and common sense. the computer refers to the memory cell containing the numeric value of variable X (for example. calculating the value of the right part of the operator). modify the text of a function without making any changes in the basic code of the program. specific part of a program that describes the method of data conversion. it turns out to be equal to 3 at the moment of referring to it). In this case. Execution of this assignment operator results in that the variable X gets the new value (4).

This approach became widespread and is a standard now.We can say that the most part of the code in programs composed using MQL4 is written in form of functions. Problem 8. Compose a part of the given program code as a function.mq4. The same program using a function is shown in Fig. In this program. a part of calculations is composed as a function. In this program. 19. . all calculations are located together. 18. in which they occur in the program (from the top down). 18) that finds the length of hypotenuse using two other sides of the right triangle and Pythagorean theorem. The code of single program pifagor. Suppose we have a small program (Fig. Fig. the operators are executed one by one in the order. a function can be described and called. It would be reasonable to make a function using the two lines that find the search value. The description of the user-defined function is located outside (after) the basic code. The basic code contains a user-defined function call. Let's consider an example. Composition of a Function Thus.

The body of a function is enclosed in braces. datetime. At the same time. bool. 19. The code of a program that contains the description of and the call for user-defined function gipo. double. Both versions of the program will give the same result. The type of the value returned using operator . function name and the list of formal parameters. 19) a part of calculations is executed in a function called from the basic text. the calculations in the main code will be continued. The value returned by the function is given in the parentheses of operator return(). If you don't call the function. The list of formal parameters are enclosed in parentheses and placed after the function name. Function Description The description of a function consists of two basic parts . whereas in the second version (Fig. we have to call it (refer to it). if you call a nonexistent function. This is why the function is practically represented in two parts: the code itself composing the function (function description) and the function call used to launch the function (referring to the function).mq4. its type can be denoted as void ("without contents. The function body may contain simple and/or compound operators. or string. empty") or as any other type. Upon completion of the calculations separated into the function. However. this will result in nothing (MetaEditior will give an error message if you try to compile such a program in MQL4). 18). it will not be executed.Fig. the code is composed as a single module in the first version (Fig. color. The header of a function consists of the type of the return value. The type of the return value can be one of the types we already know: int. To have the function executed. If the function does not return any value. as well as calls for other functions.function header and function body.

Function Types There are three types of functions . Any function call is always specified within another function (i. Function description. 20. predefined) functions.special functions.return(). and user-defined functions. Fig. Function call (reference to a function). The function call can be represented as a separate operator or as a part of an operator. not inside of a function.. but outside it). Special Functions .e. The list of transferred parameters is enclosed in parentheses. Function Call Function call represents the function name and the list of transferred parameters. Fig. The function description must be located separately in the program. but inside one of them). not outside all other functions. outside any other functions (i. must match with the function type specified in the function header. The description of the function is ended with a closing brace..e. 21. standard (built-in.

whereas the latter one is for messaging a certain text enclosed in parentheses to the screen. The properties of standard functions are considered in more details in section Standard Functions. In our example (Fig. 18. 19). The special feature of standard functions is that they are not described in the text of the program. or predefined functions. The special feature of special functions is the fact that they are called for execution by the client terminal. We only say here that the basic code of a program is located inside these functions (Fig. it is not recommended to do so. User-defined Properties of Functions Function Execution . 18. and deinit() that may not be used in the names of any other functions. For example. printing messages in the system journal or on the screen all these and many other standard functions are executed according to the predefined algorithm. The former one is intended for computing of square roots. programmers create and use their own functions. The user needn't to learn the contents of these functions. Function description and function call used in programs for functions of different types. Standard Functions MQL4 has a number of useful functions that don't need being described when coding a program. Here we will note that these records represent standard function calls. The detailed consideration of special functions is given in chapter Special Functions. 19). they are not usually called from the program if this program is coded properly. two standard functions are used: MathSqrt() and Alert(). computing square roots. Although special functions have all properties of functions in general. User-Defined Functions In some cases. They have predefined names: init(). Standard functions can also be named built-in. User-defined functions are utilized in programs with both function descriptions and function calls. whereas no descriptions of these functions can be found in the program. there are 3 special functions in total. Function Type Standard Special Function Description Not applicable Applicable Applicable (*) Although special functions can be technically called from a program. start(). You may use any of these terms. The standard functions are called in the program in the same manner as when using any other functions (it's a common practice). Table 1.In MQL4. He or she can just be sure that all standard functions are developed by professionals properly and according to the best possible algorithm. We call these functions userdefined functions.

The number. variable. In our example. The return value is specified in the parentheses of the operator return() (see Function Description and the Operator "return"). 22. The requirement of matching the types of passed and formal parameters can be seen in Fig. The passed parameters are usually separated by commas. The function may also omit using the passed parameters. MetaEditor will give you an error message. an empty list of parameters is specified. types and order of the passed parameters in the function call must match with those of formal parameters specified in the function description. Functions are executed according to their codes. types and order of the passed parameters in the function call must match with those of formal parameters specified in the function description (the call for a function that has default parameters is an exemption . A function can get and process one or several parameters from the program that has called this function for execution. i. Constants. The passed parameters are specified by enclosing in parentheses after the name of the function to be called. a function is like a standard calculator. . Only variables can be used in the header of the function description as formal parameters. the passed parameters are variables A and B (Fig. If they don't match. It is also possible that a function does not return any value. expressions and arrays may be used as passed parameters.e. whereas the return value is variable c (Fig.see Function Call and Function Description and the Operator "return"). In this case. 21). The number of parameters passed to the function must not exceed 64. In this case. and you will obtain one value as an answer. You can type (using its keyboard) a certain expression that consists of several values entered one by one. you just put an opening parenthesis and a closing parenthesis directly after the function name. Passed Parameters and Return Value As to information received and returned. giving) one parameter as an answer to this program. nothing is specified in the parentheses of the operator return().The main property of all functions is that the called functions are executed.. 20). and the function will finish its operation by returning (transmitting. The number. The type of the value returned using operator return() must match with the type of the function given in the function header.

types and order of passed and formal parameters. in their value). 22. it wouldn't be convenient for . Only variables. We mentioned before that one function could be used in several programs. Match in the number. different programs use different names for the variables. Formal parameters are a list of variables specified in the header of the function description. correspondingly. expressions and constants can be used as passed parameters.Fig. Only variables are used as passed parameters. Formal Parameters Fig. A high point of functions is the use of formal parameters. types and order of passed and formal parameters. If functions required strict matching in the names of variables (and. an expression. A constant. However. and variables of the corresponding type are used as passed parameters. 23. Match in the number.

or a constant can be used as return value. if any. This does not have any effect on variables A and B. we will consider more details about local variables in the section Types of Variables). we used the identifiers of formal parameters a and b. The program calls the function of the same name. in the function the calculations are performed using formal parameters. 19). so we have to use in the function aand b. Of course. the calculations are made that involve formal parameters a and b. However. Indeed. and C. They are just different variables. we could use any others. 20 and 21 once again. which allows us to create functions using arbitrary names of variables. Thus. In this example. for example. variables A and B being specified in its parentheses. the variables used inside functions have no relations to the variables used in a program. which has formal parameters a and b specified in its header. Since we have given a and b in the header. m and n. you should specify in the function body the calculations that use the names of variables that are given in the header. if you exit the function. The executable function performs calculations using the values of variables a and b. calling function is special function start() (it contains the line for calling the user-defined function). The value of variable B is assigned to variable b. Let's refer to Fig. In a function. It should be noted that the names of the passed parameters (A and B are given in the parentheses of the function call) do not match with the names of the parameters (a and b) specified in the function description. The value of variable A is assigned to variable a.programmers. there is no error in this code. the result of an expression. In our case. B. this is the value of local variable c (local variable is a variable declared within a function. This means that this value will now be assigned to variable C. Thus. fortunately. there occurs a function call. can be performed with the variables declared within the calling function. any allowed actions may be perform on formal parameters a and b (including the changes in the values of these variables). not m and n. irrespective of the names of values actually used in the program. . In our case. The return value calculated in the function is given in the parentheses of the operator return(). or Kat_1 and Kat_2. In a function. The function returns into the program the value of local variable c (Fig. It is allowed to use any names of formal parameters (that don't coincide with the names of the variables used in the program). The value of a variable. B and b considered here are different names of variables. However. How It Works In the program. We noticed in the section Constants and Variables that MQL4 is case-sensitive. However. when writing a program. Only variables. the names A and a. Further calculations in the program. but not variables A and B. you would then have to compose each newly developed program in the names of variables that had already been used in your functions before. The variables (formal parameters) used in the function description are not related to the variables used in the basic code of the program. whereas the variables declared within the calling function are A. the values of all local variables will be lost. but not constants. can be specified in the function header as formal parameters.

8. you can easily distinguish the standard function call by its appearance: they are highlighted in MetaEditor with dark blue (programmer may choose colors voluntarily). Assignment of the value 25 to variable C_2. 2. The result of the calculations is the value of 25 (the details of how a program refers to variables to take their values are considered in the section Constants and Variables. Calculation of the right part of the assignment operator. We should note that the entire code of the program is located inside the special function start(). The control is given to the next line: int B = 4. let's consider the behavior of the program shown in Fig. The value returned by the function is now the content of the record: . its value is 3. // Calculation of hypotenuse The program seeks to execute the assignment operator. The program calls for execution the standard function MathSqrt() (that calculates square roots). its value is 4. 9. In our case. Note that there is no description of this standard function anywhere in the program. 18. the right part of which contains a call for the standard function: int C = MathSqrt( C_2). The descriptions of standard functions must not be located in programs. // Second cathetus 3. 6. It returns the obtained value. // First cathetus 1. this value is equal to 25) will be used as the passed parameter. The standard function MathSqrt() has completed its calculations. 4. Let's follow the execution of the program starting with the assignment operator: int A = 3. The value of variable C_2 (in our case. The next line represents an assignment operator. The value of 3 (the value of the right part) is assigned to variable A (that locates to the left of the equality sign in the assignment operator). // Sum of the squares of catheti 5. it is the value of 5 (the square root of 25). it executes calculations to the right of the equality sign first. At this training phase. 7. The right part of the assignment operator contains the specified constant.Example: Standard Functions in a Program First of all. The calculations are made in the standard function MathSqrt(). For this purpose. we won't pay special attention to this (special functions and their properties are considered in more details in the section Special Functions). The value of 4 is assigned to variable B. so we aren't particularizing this point here now). The right part of the assignment operator contains the specified constant. In the text of a program. The program goes to execution of the next line: int C_2 = A*A + B*B.

// Function exit operator The work of the program is finished at this point. Whether a user-defined function returns the value or not. // Message on the screen The standard function Alert() opens a dialog box where the values of the passed parameters are displayed. complex variable.MathSqrt( C_2) This record can be considered as a special. return. On continuing execution of the assignment operator.. 19).the value of integer variable C: 5 It was noted above that not all functions must return the value (that is the result of the function execution). or the Help File of MetaEditor. 10.it must display the text on the screen. C). the function has taken two values as the passed parameters: . After these calculations have been completed. and what not? The answer to this question is obvious: In order to find the detailed descriptions of built-in functions. The next line contains operator that references to the standard function Alert() (function call). our value is the value of the right part of the assignment operator. A question may arise: How can we know what function will return the value. inside which the calculations are performed. in the window of this function the following line will appear: Hypotenuse = 5 12. The last operator in this program completes the work of the special function start(). depends on its algorithm (the decision is made by the programmer at the stage of writing the program code of the function). In this case. A certain part of the code that could previously to be found in the special . you should read the reference documentation in MQL4. in a special window. The standard function Alert() does not return any value. a kind of a thing. the thing takes a value. The determining is here the fact that the value returned by the function can be assigned to another variable or considered somehow in any other calculations. 11. since it has another task .community. Alert("Hypotenuse = ". the program will assign the value of 5 to variable C. The properties of a user-defined function are specified in its description.the value of string constant: Hypotenuse = . Example: User-Defined Function in a Program Let's consider how the same calculations are made in the program containing a user-defined function (Fig. the website launched by MetaQuotes Software Corp. As a result of execution of the standard function Alert(). In this case.

and after that it will assign the obtained value (in our case.2.2. in our specific case. Calling for variable A in order to get its value (in our case. the program will first of all call the user-defined function. Calling for variable B in order to get its value (in our case. It is replaced with the call for the user-defined function. // Sum of the squares of catheti 7.. . is unavailable now. 3) 6. this rule applies to all functions). 7. The first two lines. outside the special function). the program will perform the following: 6. the program will do the following: 7. The first operator in the function body is: int c2 = a*a + b*b.e. the values of variables in the calling program will not get lost.function start(). the special function start() is followed by the description of the user-defined function. During the whole time of execution of the user-defined function (no matter how long it takes). Note: The description of the user-defined function must be present in your program and placed immediately after the brace that closes the special function start() (i. The control is passed to the user-defined function. int b) // User-defined function On executing the user-defined function. The value of 4 (the second value in the list of passed parameters) will be assigned to variable b (the second variable in the list of formal parameters). A and B) are not supposed to change due to application of the userdefined function. In referring to the user-defined function. nothing changes in their execution: int A = 3. However.3. the program calculates the value in the right part of the assignment operator. // First cathetus // Second cathetus In the third line we have the assignment operator. Consequently.1. Its right part contains the call for the userdefined function: int C = Gipo(A. but will be stored. remain the same. 3*3 + 4*4 = 25) to variable c2. On executing this operator. int B = 4.1. nor they really change. Then the control will be passed to the function body for it to execute its algorithm. The value of 3 (the first value in the list of passed parameters) will be assigned to variable a (the first variable in the list of formal parameters). The first line in the description of the user-defined function is its header: int Gipo(int a. 7. // Calculation of hypotenuse 6. the program gets just a copy of the values of variables used as passed parameters. On executing this operator. in which integer variables A and B take numeric values. whereas the values of these variables themselves (in this case.B). 4) Note: As soon as the program starts to call the user-defined function (the function is userdefined.

it is the value of 5). namely: in a special window. // Function exit operator. the program will assign the value of 5 to the variable C. 8. // Function exit operator On executing this operator. there will a message appear: Hypotenuse = 5 10. 9. we have operator: return(c). the control is given to the call site. // Message on the screen. 5.B) at the stage of returning the value. Here we find the square root of the value of variable c2. // Hypotenuse 7. At this point. The last operator in this program.5. it is the value of variable c. The order of operations is the same as in the previous example. On completing the execution of the assignment operator.The next operator: int c = MathSqrt(c2). the program will return (to the call site of the user-defined function) the value enclosed in the parentheses of this operator. In our case. It is easy to verify that programming with user-defined functions has some incontestable advantages. The description of standard function is not used either. takes the value calculated in the function (in our case.4. C). will be executed in the same way as in the previous example. completes the work of the special function start(). i.B). return. In the next line. . // Hypotenuse calculation The record (the user-defined function call) Gipo(A.e. Let's consider some implementation versions of the above user-defined function. The execution of the assignment operator will result in assigning the value of 5 to variable c. Recall that the user-defined function was called from the operator int C = Gipo(A. 7. the execution of the user-defined function is over. Alert("Hypotenuse = ". The next operator.and simultaneously completes the work of the entire program (the properties of special functions are considered in more details in the section Special Functions).

Previously Considered Implementation of User-Defined Function Gipo()
In this function, the formal parameters "resemble" the variables used in the basic program. However, this is just a formal similarity, because A and a are the different names of variables.
//----------------------------------------------------------------------int Gipo(int a, int b) // User-defined function { int c2 = a*a + b*b; // Sum of the squares of catheti int c = MathSqrt(c2); // Hypotenuse return(c); // Function exit operator } //-----------------------------------------------------------------------

Implementation of User-Defined Function Gipo(): Version 2
In this case, the names of formal parameters do not "resemble" the names of variables used in the basic program. However, this doesn't prevent us from using this function in the program.
//-------------------------------------------------------------------int Gipo(int alpha, int betta) // User-defined function { int SQRT = alpha*alpha + betta*betta; // Sum of the squares of catheti int GIP = MathSqrt(SQRT); // Hypotenuse return(GIP); // Function exit operator } //--------------------------------------------------------------------

Implementation of User-Defined Function Gipo(): Version 3
In this example, the variable alpha is reused in the program and changes its value twice. This fact has no effect on the actual variables specified in the function calls of the main program.
//-------------------------------------------------------------------int Gipo(int alpha, int betta) // User-defined function { alpha= alpha*alpha + betta*betta; // Sum of the squares of catheti alpha= MathSqrt(alpha); // Hypotenuse return(alpha); // Function exit operator } //--------------------------------------------------------------------

Implementation of User-Defined Function Gipo(): Version 4
In this user-defined function, all calculations are collected in one operator. The return value is calculated directly in the parentheses of the operator return(). The subduplicate is calculated directly in the location where the passed parameter must be specified in the standard function MathSqrt().This solution may seem to be strange or wrong at the beginning. However, there is

no error in this implementation of the user-defined function. The number of operators used in the function is smaller than in other implementations, so the code turns out to be more compact.
//-------------------------------------------------------------------int Gipo(int a, int b) // User-defined function { return(MathSqrt(a*a + b*b)); // Function exit operator } //--------------------------------------------------------------------

Thus, the application of user-defined functions has some incontestable advantages in the programming practice: the names of variables in the basic text of the program have no relations to the names of formal parameters in a user-defined function; user-defined functions can be reused in different programs, there is no need to change the code of a user-defined function; libraries can be created, if necessary. These very useful properties of functions allow to create really large programs in a corporation, for example. Several programmers can be involved in this process simultaneously, and they a released from the necessity to agree about the names of variables they use. The only thing to be agreed is the order of variables in the header and in the function call.

Program Types
Starting to write a program in MQL4, the programmer must, first of all, answer the question about what type of programs will it be. The contents and functionality of the program fully depend on this. In MQL4, there are 3 types of application programs: Expert Advisors, scripts, and custom indicators. Any program developed by a programmer will belong to one of these types. They all have their purposes and special features. Let's consider these types in more details. Expert Advisor (EA) is a program coded in MQL4 and called by the client terminal to be executed at every tick. The main purpose of Expert Advisors is the programmed control over trades. Expert Advisors are coded by users. There are no built-in EAs in the client terminal. Script is a program coded in MQL4 and executed by the client terminal only once. Scripts are intended to perform any allowed operations that should be executed only once. Scripts are coded by users. They are not delivered with the client terminal as built-in programs. Custom indicator is a program coded in MQL4 and called by the client terminal to be executed at every tick. It is basically intended for graphical displaying of preliminarily calculated dependences as lines. Indicators cannot trade. There are two types of indicators: technical (builtin) indicators and custom indicators. Indicators are considered in more details in the sections of Usage of Technical Indicators and Creation of Custom Indicators. The programmer chooses the type of the program to be written depending on what is the purpose of this specific program and on properties and limitations of programs of different types.

Properties of Programs

Launching a Program for Execution
There is a criterion that distinguishes Expert Advisors and custom indicators from scripts. This is their run duration. In the section Some Basic Concepts, we mentioned already that programs were launched the amount of time that is multiple of the amount of ticks. This statement is true for EAs and custom indicators, but it is false for scripts. Expert Advisor and custom indicator. Once you have attached a program (EA or custom indicator) to the symbol window, the program makes some preparations and switches to the tickwaiting mode. As soon as a new tick comes, the program will be launched by the client terminal for execution, then it makes all necessary operations prescribed by its algorithm, and, upon completion, passes the control to the client terminal, i.e., switches to the tick-waiting mode. If a new tick comes when the program is being executed, this does not make any effect on the program execution - the program continues being executed according to its algorithm and passes the control to the client terminal only upon completion. This is why not all the ticks result in launching an EA or a custom indicator, but only those that income when the control is in the client terminal and when the program is in the tick-waiting mode. The new tick launches the program for execution. Thus, an Expert Advisor or a custom indicator can operate within a long period of time, being attached to the symbol window and starting to run from time to time (as multiple of the amount of incoming ticks). Besides, an Expert Advisor differs from an indicator by the execution order at the first launch of the program. This difference is determined by the specific properties of special functions in the program of a certain type (see Special Functions). Once attached to the symbol window, an Expert Advisor makes necessary preparations (function init()) and switches to the tick-waiting mode to start function start(). Unlike EAs, a custom indicator both executes function init() and calls function start() one time to make the first, preliminary calculation of the indicator value. Later on, at a new tick, the program is launched by calling only function start(), i.e., operators are executed according to the algorithm of function start(). Script. Unlike Expert Advisors or indicators, a script will be launched for execution immediately after it has been attached to a symbol window, without waiting for a new tick. The entire code of the script will be executed on time. After all program lines have been executed, the script finishes its operations and is unloaded from the symbol window. A script is helpful if you want to make one-time operations, for example, to open or close orders, to display texts on the screen, to install graphical objects, etc. The differences in execution of Expert Advisors, scripts and custom indicators is determined by the properties of their special functions the will be considered in more details in the section Special Functions.

One of the main criteria that mark the above programs is the possibility to make trading instructions. A trading instruction is a control that a program passes to the trading server in order to open, close, or modify orders. Trading instructions are formed in the programs using built-in functions that we call "trading functions".

Main properties of Expert Advisors. However. you may simultaneously launch the programs of the same type in different windows of one symbol. one script and several indicator in one symbol window at the same time. scripts. The programs of all types can create global variables available for all other programs launched in the client terminal. Calling Programs for Execution Programs of all types can only be executed at the user's will. Simultaneous Use The programs also differ from each other by the amount of programs of different types simultaneously attached to a symbol window. The only exemption is the built-in function iCustom() that allows you to refer to a custom indicator for some data. one of them can give instructions to open orders. Custom indicator. or an indicator for execution programmatically. It is prohibited to use trading functions in custom indicators. This may cause occurring of a long sequence of useless trades that results in the total loss. The referring to function iCustom() or to the functions of technical indicators does not result in displaying the lines of indicators in the symbol window (see Simple Programs in MQL4). including those launched in the windows of different symbols. whatever programs of other types are launched simultaneously. if you want to launch two Expert Advisors for one symbol. or one EA and one indicator. your Expert Advisors will work simultaneously. you can launch one EA. the simultaneous use of several Expert Advisors is prohibited. Expert Advisor.Only Expert Advisors and scripts have the right to use trading functions (only if the corresponding option is enabled in the EA/script settings). a script. you may not launch several EAs or scripts in one symbol window. However. and custom indicators. Table 2. You can attach only one EA in one symbol window. you cannot call an Expert Advisor. For example. In this case. Property of the Program Expert Advisor . whereas the other one can instruct to close orders. You can attach several indicators in one symbol window simultaneously. the simultaneous use of several scripts is prohibited. you must take into consideration that EAs launched in this manner may form contradictory trading instructions. you can launch one EA in one window of this symbol and another one in another window of the same symbol. For example. For example. The order of using global variables will be specially considered in the sectionGlobalVariables. they will not interfere with each other. and to the functions of technical indicators. In MQL4. At the same time. You can attach only one script in one symbol window. Script. The programs of all types can be launched simultaneously in one symbol window provided their compliance with the limitations of each type. This allows the machine to coordinate the simultaneous operations of all programs.

. Expert Advisors. we should write an EA or a script. an Expert Advisor. File System MetaEditor stores all source codes of MQL4 programs in its own structured catalog on a hard disk. MetaEditor is a multifunction specialized editor intended for creating. Creating and Using Programs It is very easy to create a program in MQL4 . an indicator. if we want a program that would manage trading according to a certain algorithm. scripts and indicators . indicators or Expert Advisors. Expert Advisors are located right in the directory ClientTerminal_folder \experts. MetaEditor In this section we will dwell on the general order of creating application programs using MetaEditor. You can modify templates for creating scripts. scripts and custom indicators that a trader is going to use in his practical work should be located in corresponding directories (see Fig. if we want to have a certain dependence graphically displayed. The editor has a user-friendly interface that allows a user to easily navigate when writing and checking out a program. an include-file or a library. editing and compiling application programs written in MQL4.Run duration Trading Displaying of lines Over a long period Allowed No O A Simultaneous use of several programs of the same type Calling for execution programmatically Prohibited Prohibited N P P Thus. The created code will be automatically saved in a corresponding folder of MetaEditor file system. All application programs are concentrated in the directory ClientTerminal_folder \experts. we should use an indicator. However. The location of a program in MQL4 is determined by its purpose: a script.built-in tools will help you. 24). File System The client terminal recognizes program types by their location in subordinate directories.in subdirectories ClientTerminal_folder\experts\scripts and ClientTerminal_folder \experts\indicators.

mqh or WinUser. scripts and indicators at the stage of compilation.mqh) or the description of common constants and variables (stderror. an Expert Advisor or an indicator. The ex4 file name does not point to the program type . Files of mq4 type cannot be used for execution in the client terminal. As a result of a source code compilation. it can be saved and later opened for modification. Files of mq4 type represent a program source code. For starting a program's execution. As a rule. It is a source text of frequently used blocks of custom programs. If a program needs to be modified. indicators).e. Files with ex4 extension can be used as library files. a file of the same name with the extension ex4 is created. this should be done in its source code (a file of mq4 type): it should be edited and then compiled again. Files of this type contain source texts of all types of programs (Expert Advisors.mqh or WinUser32. When a code is fully or partially created. A user can create other directories for storing some files. the usage of ready programs located in such directories is not provided in the client terminal. 24. Files of this type cannot be edited. However. Such files can be included into source texts of Expert Advisors.whether it is a script. because they are usually "included" at the stage of compilation to the main source file using the #include directive.Fig. A file of ex4 type is a compiled program ready for practical use in the client terminal. Usually include files contain the description of imported functions (as example. created by a user. Files of mqh type are include files. see files stdlib. As include . i. scripts. Directory for storing files. it should be first compiled. they do not require compilation for getting executable files of ex4 type. ex4 and mqh. For the creation of program codes MetaEditor is used. files of mqh type are stored in the directoryClientTerminal_folder\experts\include. Include files are called so.mqh). Despite the fact that files of mqh type can contain a program source code and can be compiled by MetaEditor. File Types In MQL4 there are three types of files that carry a program code: mq4. they are not independent and selfcontained.

Files compiled in older versions of MetaEditor cannot be started and are displayed in a grey color. It contains general information necessary for the creation of new programs. but are used in the creation of application programs.exeor on a shortcut located preliminarily on the desktop. a program can be created out of several separate files or using a library created earlier.exe) is provided as part of the client terminal and is located in the root directory of the terminal. MetaEditor has built-in toolbars: "Navigator" (Ctrl+D) and "Toolbox" (Ctrl+T). Libraries cannot start by themselves. one can use mq4 files that should be stored in ClientTerminal_folder\experts\include .files. It is recommended to store libraries in the directory ClientTerminal_folder\experts\libraries. In the first part of the book "Programming in MQL4" we will analyze mq4 files of source texts and compiled ex4 files. The Userguide of MetaEditor is opened by pressing F1. scripts and indicators . Structure of the Client Terminal For the convenience of operation. For example. Sections "Expert Advisors".Expert Advisors.are created using MetaEditor. The executable file of MetaEditor (MetaEditor. Creating and Using Programs Application programs written in MQL4 . The editor can be opened by clicking on the file name MetaEditor. "Custom Indicators" and "Scripts" of the client terminal navigator will show only the names of files that have the extension ex4 and are located in the corresponding folder. Using include files is more preferable than using libraries because of additional consumption of computer resources at library function calls. A user can create libraries of custom functions intended for storing frequently used blocks of user programs. There are other types of files that do not make a complete program. . Files of mq4 and ex4 can be used as library files.

Location of windows in MetaEditor. To create a new program. Usually during the creation of a new program.Fig. 25. The text of the program is located in the editor window. After all these actions "Expert Advisor Wizard" will offer you a list of program types for choosing one to be created: . the toolbox windows are auxiliary. toolbox and navigator windows are hidden. use the editor menu File >> Create or a button for the creation of new files . Thus the attention of a user is concentrated on a created program. Windows of the navigator and toolbox have moving boundaries and can be shown/hidden in the Creating a New Program editor using the buttons and .

Suppose it is called create. If you need to create an Expert Advisor. check Expert Advisor and click Next. The name of a created file is written without its extension (type indication). Choosing a program type to be created. In the next window it is necessary to indicate the name of a created Expert Advisor.Fig. 26.mq4. The Expert Advisor Wizard will show a window with several fields to be filled in: .

Fig. 27. After clicking Ok a text will appear in the main window and the full name of the created Expert Advisor create. Fig.mq4 will appear in the file system and in the navigator window. . Displaying a created file of an Expert Advisor in the file system and navigator window. 28. A window for indicating general parameters of an Expert Advisor.

mq4 | //| John Smith | //| www. } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0). start() and deinit().company. } //+------------------------------------------------------------------+ You see. } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---//---return(0). Each function contains only one operator . using which a programmer can create a new program. If any of the functions will not be used. There are three special functions in the program: init(). it's description can be deleted. Thus a program code generated by the Expert Advisor Wizard is only a pattern. They are present in the pattern only because as a rule a usual medium-level program contains all these functions. We already know that comments constitute a nonobligatory part of a program and the text of comments is not processed by the program.com" .return(0) .company.com" //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---//---return(0). The following lines of the program code can also be omitted: #property copyright "John Smith" #property link "www. the code contains mainly comments.company.Let us see the program text generated by MetaEditor: //+------------------------------------------------------------------+ //| create. The final program code can does not obligatorily contain all the indicated special functions.an operator for exiting a function.com | //+------------------------------------------------------------------+ #property copyright "John Smith" #property link "www.

). Any long line can be separated into several lines so that all they would be fully visible on the screen. its main characteristics and limitations and other useful information. program allocation (whether it is a complete trading program or a library function). a comment can be started from the 81st position. A correctly coded program definitely contains comments. For a monitor with 1024 x 768 pixel resolution the maximal line length is 118 symbols. Let's view the main characteristics of any acceptable appearance styles. Secondly. can be forgotten (or unknown in a product by another programmer) and without string comments it is difficult. it should be started from the 76th position (recommended for 17" monitors with 1024 x 768 pixel resolution). This limitation is not the language syntax formal requirement. Program Appearance Using comments in programs is strongly recommended and in some cases it is strongly essential. Variable declaration is done at the program beginning. 2. but also reads them. if required. It would be executed like any other program (though. comments allow to separate one logically detached program part from another. a tabulation size indent must be used (usually 3 symbols). It is recommended to write a descriptive comment for each variable: shortly explain their meaning and. 5. 3. Style offered by MQL4 developers is presented in the Expert Advisor create. but reading a program containing long lines is not convenient. It is much easier to read a wisely formatted text than a straight text. e-mail. If there is a comment in a line. And it must be emphasized that a programmer not only creates programs. string comments allow to explain in plain words what a programmer meant in each separate code line. 4.Although the program is of no practical use. The experience of many programmers shows that the reasoning logics. in the upper part of a program. Each programmer can choose a convenient style of comments. 6. The main advantages of comments are: Firstly. on the basis of which a program was developed. This requirement is not obligatory. sometimes even impossible to understand code fragments. And this program could be compiled and started.mql4. general information about a program may be specified: an author's name and contacts (including the author's web-site. . if a code line takes 80 positions. etc. continuous line comments of the full width are used (118 symbols). it is written correctly from the point of view of syntax. there would be no calculations because there are none in the source code). Sometimes considerable difficulties may occur when reading a program. it is not necessarily divided into two lines. When braces are used. 1. A comment line length must not exceed the main window size. For dividing logically separate fragments. Thirdly. For example. Usually the program code part contains 50 symbol long lines and the string comment looks like a text column in the right part of a screen. Each operator is better placed on a separate line. peculiarities of usage.

deinit() triggered at exit").Price). // Ticks counter Alert("New tick ". return. For example. // Alert return.Price)." Price = ".mq4) may have the following form: //-------------------------------------------------------------------// create. return. This is a way to detach special. The value of comments can be fully appreciated if a program does not contain any and some problems with algorithm understanding occur when reading the program. //-------------------------------------------------------------------int Count=0. } int start() { double Price = Bid. funct. it will be more difficult to read it. A commented program (Expert Advisor create. // Exit init() } //-------------------------------------------------------------------int start() // Spec. We are interested in the program appearance. init() { Alert ("Funct. int init() { Alert (Funct. Alert("New tick ".Count. start() { double Price = Bid. but the author himself will not be able to puzzle out the part after some period of time. user-defined functions and the head part of a program: //-------------------------------------------------------------------- Variables are declared in a separate block where each variable is described. In this case the program algorithm logics is not discussed. even though the program is quite simple and short: int Count=0. // Exit start() } //-------------------------------------------------------------------int deinit() // Spec.mq4 // To be used as an example in MQL4 book. The right part of each code line contains an explanatory comment. funct.Let us see. but if it occurs." Price = ". Count++. funct. such a comment must be necessarily placed.// Alert return. // Global variable //-------------------------------------------------------------------int init() // Spec. } int deinit(){ . // Alert return.Count. This is a rare case. how an Expert Advisor may look like after a program code is written in it. otherwise not only another programmer. deinit() { Alert ("Funct. // Local variable Count++. Sometimes programs contain variables. init() triggered at start"). for describing which comments in several lines should be used. if the same code is presented without comments and block separation. // Exit deinit() } //-------------------------------------------------------------------- It is easy to see that complete meaningful blocks of the program are separated by comments continuous lines. init() triggered at start").

it must be compiled. If during compilation errors are detected in a program. Displaying the name of an Expert Advisor in the client terminal navigator window. Editor message about a successful program compilation. 29. 30. If a program does not contain any errors. script or indicator) has been successfully compiled and its name has appeared in the client terminal navigator window. MetaEditor will show the corresponding error message. deinit() triggered at exit"). This is a program ready for operation in the client terminal MetaTrader4. A successful program compilation is possible only if there are no errors in the program. a new file create.mq4) will be saved in the same directory.} Program Compilation To make a program usable in practice. it will be compiled and a message will occur in the toolbox: Fig. fix errors and try to compile the program once again. Alongside with that a line with the name of the created Expert Advisor will appear in the section Expert Advisors of the client terminal navigator window: Fig. return.Alert (""Funct. Using a Program in Practice If an application program (Expert Advisor. It is done by dragging the corresponding icon form the navigator window into a security window . In such a case one should get back to editing the source text. it can be used in practice. During compilation the last version of the source text of the program under the same name (in our case it is the file create. Besides.ex4 will appear in the corresponding directory (in this case in Terminal_directory\experts) . For this purpose the button (F5) in MetaEditor should be used.

thus conducting trade management. . During a program execution (depending on its algorithm) trading orders may be formed and sent to a server. indicator. he should switch on a computer. It means the program will be attached to a security chart and started for execution. A usual script will stop operating itself after executing its algorithm. It is important to note here once again that: Any application programs (Expert Advisor.using a mouse ('drag & drop' method). open MetaTrader 4 Client Terminal and start an executable file *.ex4 in a security window. None of the programs can be installed on a server or used in terminals of other developers. script) can be used for trading only as part of MetaTrader 4 Client Terminal when it is connected to s server (dealing center) via Internet. In other words if a trader wants to use any application program. An Expert Advisor and an indicator will operate until a user terminates the program execution manually.

Sign up to vote on this title
UsefulNot useful