# /

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

Preface
It is a sort of difficulty to start writing a textbook on programming for beginners, because the area of knowledge under consideration involves some new concepts that are not based on anything previously known or usual.

Generally speaking, a problem of this kind may occur in any other field of knowledge. For example, point is known in mathematics as infinitesimal circle, whereas the circle itself is defined as a set of points ordered in a certain manner. As is easy to see, these terms are defined through each other. At the same time, this 'inadvertence' did not become a stumbling block for mathematics. Both circles, points, as well as other terms adopted in mathematics go well together. Moreover, everybody understands by insight what a point is and what a circle is.

It is easy to find out that the vast majority of ordinary terms have indeterminate boundaries. Some of those boundaries are so fuzzy that they cast some doubt on the existence of the very object or phenomenon defined by the term. However, the nature of man is that this strange (in terms of normal logic) situation does not come between a man and his existence and fruitful activities. After a term has been used for a certain amount of time, it takes on its complete sense for us. It's difficult to answer the question of how and why it happens this way. But

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.

Preface

Introduction to MQL4
Basics of MQL4

Some Basic Concepts Constants and Variables Data Types Operations and Expressions Operators Functions Program Types MetaEditor File System Creating and Using Programs Program in MQL4 Program Structure Special Functions Program Execution Examples of Implementation Operators Assignment Operator Conditional Operator 'if-else' Cycle Operator 'while' Cycle Operator 'for' Operator 'break' Operator 'continue' Operator 'switch' Function Call Function Description and Operator 'return' Variables Predefined Variables and RefreshRates Function Types of Variables GlobalVariables Arrays

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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

and BB . green and blue components in the selected value of color.Integer representation is recorded as a hexadecimal or a decimal number. Examples: 0xFFFFFF (white). 32768 (green). The majority of modern text and graphics editors provide information about the intensity of red. 16777215 (white). Representation of the values of color type as integers and as hexadecimal literals is very user-friendly. GG . They represent the decimal value of a hexadecimal integer representation. 0x008000 (green).green. A hexadecimal number is displayed as 0xRRGGBB where RR is the value of red intensity. .blue. Decimal constants are not directly reflected in RGB. 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.

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 . 11. Color Names The easiest way to set a color is to specify its name according to the table of web colors. In this case. the value of a color is represented as a word corresponding with the color.Fig. Color parameters for literal and integer representation of the constant color value can be taken in modern editors. for example. Red .the red color.

D'12.0x00.128. It is allowed to use truncated values: either without date or without time.01 00:00'. The constants of date and time can be represented as a literal line consisting of 6 parts that represent the numeric value of year. // 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. 2037. day (or day. A value represents the amount of seconds elapsed from 00:00 of the 1st of January 1970. hour. // 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.2004'.12 16:30:45'. D'2005.0x33. = Yellow. = White. or just an empty value. the variable color BMP_4 = C'0xFF. 16777215. month.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. month. // // // // // New Year New Year May 12.05. D''. 32768. = Black.0xFF'.LavenderBlush MintCream Snow White Constants and variables of color type take 4 bytes in the computer memory. and second. the variable color Colo = C'0x00. 1970. minute.m. workday start/finish. The values of constants and variables of datetime type take 4 bytes in the computer memory. The range of values: from January 1. equivalent of D'[compilation . etc. 2005 4:30:45 p. including the releases of important news. 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.m.01. The constant is framed in single quotes and starts with 'D'. to December 31. D'01. 0x008000. An example of using such a variable in a program: color Paint_1 = C'128. May 12.05. year).01.2005 16:30:45'. 2005 4:30:45 p. The values of this type can be used in programs to analyze the moment of beginning or ending of some events.128'.

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

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

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

if x is equal to y Operation True. y = .3. function call. 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). Operations are used in operators (see Operators). comma operation. 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 .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. otherwise.bitwise operations. if x is not equal to y . It is prohibited to use operations outside operators. you can use it.

FALSE(0).< <= >= > True. The binary representation of x is shifted by y places to the right. . The binary representation of x is shifted by y places to the left. if any value of the values is true TRUE(1). b = ~n. It contains 0 in all other places. The value of the expression contains 1 in all places. The bitwise operation OR of the binary representations of x and y. in which the values of the variable contain 0. in which both x and y contain non-zero. The bitwise operation AND of the binary representations of x and y. The value of the expression contains 1 in all places. This right shift is logical. x = x << y. It contains 0 in all other places. The value of the expression contains 1 (TRUE) in all places. b = x ^ y. if x is less than y True. the emptied places to the left will be filled with zeros. 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) != 0). in which x and y have different binary values. 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. if x is equal to or less than y True. b = x | y. if x is more than y True. if the TRUE(1). in which x or y does not contain 0. in which the values of the variable contain 1. The following operations belong to bitwise operations: One's complement of the value of the variable. The value of the expression contains 1 in the places. The bitwise operation EXCLUSIVE OR of the binary representations of x and y. and it contains 0 in all places. x = x >> y. and the value of the expression contains 0 (FALSE) in all other places. it means that all places emptied to the left will be filled with zeros. if the value of the operand is FALSE(0).

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

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

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

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

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

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

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

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

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

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

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

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

Х = 2 2. 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. All operators without any exceptions represent precise instructions that allow no ambiguities. Nevertheless.to right and downwards. A text in a program: Y = 5. whereas you must keep a well-defined order in a program. 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. 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.they inform the machine what operations and in what order it must execute. 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. Operators in a program are assigned for other purposes . then operators are executed in the nearest lower line in the same order. the notes (lines) have a completed content. and so on). left to right. the lines in Solution 1 cannot be used in a program as they are. let's see how an assignment operator works. Any assignment operator gives the machine the following order. then the next lower. The notes given in Solution 1 represent some dependences in paper form. then the next. A normal text on a sheet of paper: 1.2.2 3. If there are several operators in one line. 5 . We have an equation system: Y=5 Y-X=2 The numeric value of variable X is to be found. this similarity is only formal. Х = 5 . As an example. X = Y . literally: . Х = 3 Solution 2. in operators. one by one. Both operators in Solution 2 are the assignment operators. A normal text allows the notes to be placed in any sequence. they should be executed consecutively. They can only be used to inform the programmer about the relations between the variables. Problem 7. because their appearance does not comply with the assignment operator format. Solution 1. // Line 1 // Line 2 Both in the first and in the second solutions. However.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

25. After all these actions "Expert Advisor Wizard" will offer you a list of program types for choosing one to be created: . Usually during the creation of a new program. 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. the toolbox windows are auxiliary.Fig. To create a new program. toolbox and navigator windows are hidden. Location of windows in MetaEditor. The text of the program is located in the editor window. 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.mq4. 26. The name of a created file is written without its extension (type indication).Fig. check Expert Advisor and click Next. Choosing a program type to be created. The Expert Advisor Wizard will show a window with several fields to be filled in: . If you need to create an Expert Advisor. In the next window it is necessary to indicate the name of a created Expert Advisor.

27.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. Fig.Fig. After clicking Ok a text will appear in the main window and the full name of the created Expert Advisor create. A window for indicating general parameters of an Expert Advisor.

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