EA-Manual

March 24, 2018 | Author: Yonathan Ulung | Category: Control Flow, Boolean Data Type, Data Type, String (Computer Science), Integer (Computer Science)


Comments



Description

MQL4 COURSEBy Coders’ guru www.forex-tsd.com -1- WELCOME -------------------- Welcome to the MQL4 course. In this series, I will try to strip the mystique and confusion from MQL4 by giving you comprehensive tutorials with a straight forward example. In this series of lessons, I will show you how to use the MQL4 for building your own Expert Advisors, Custom Indicators and Scripts. If you are programming in C (or its superset C++) then you know a lot of MQL4 before even I start my lessons, if you didn’t write in any programming language before, no problem, I’ll guide you to understand the concept of programming in general as well. So, let’s start from the beginning. MQL4? What, Why and Where? MQL4 stands for MetaQuotes Language 4. MetaQuotes is the company who built the MetaTrader Trading Platform. And to make it stronger than the other trading platforms the company extended it by a built-in programming language that enables the user (you) to write his own trading strategies. The language enables you to create one of the following: 1- Expert Advisors. 2- Custom Indicators. 3- Scripts. • Expert Advisor is a program which can automate trading deals for you. For example it can automate your market orders, stops orders automatically, cancels/replaces orders and takes your profit. • Custom Indicator is a program which enables you to use the functions of the technical indicators and it cannot automate your deals. • Script is a program designed for single function execution. Unlike the Advisor, scripts are being held only once (on demand), and not by ticks. And of course has no access to indicator functions. These were “What” MQL4 is? “Why” to use MQL4? Now, “Where” do I write MQL4? To write your MQL4 code and as anything else in world, you can choose one of two ways, the hard way and the easy way. 1- The hard way The hard way is using your favorite text editor and the command prompt to compile your program. Notepad is not bad choice, but do not forget two things: 1- To save the file you have created in plain text format. 2- To save the file as .mp4 (that’s to be easy to reopen it with Metaeditor), but you can save it as any extension you prefer. After saving your program there is an extra step to make your code comes out to the light. It’s the Compiling step. Compiling means to convert the human readable script that you have just wrote to the machine language that your computer understands. MetaTrader has been shipped with its own compiler (the program which will convert your script to the machine language) called MetaLang.exe. Metalang.exe is a console program which takes 2 parameters and output an .ex4 file (the file which Metatrader understands). The first parameter is “options” parameter and the only option available is –q quit The second parameter is the full path to your .mql file. The syntax will be in this format. metalang [options…] filename Example 1- Find your metalang.exe path, it will be the same path of MetaTrader (here my path is D:\Program Files\MetaTrader 4) 2- Create a batch file and name it compile.bat (or any name you prefer). 3- Write these lines into the bat file then save it. cd D:\Program Files\MetaTrader 4 metalang -q "D:\Program Files\MetaTrader 4\my_first_mql4_script.mq4" (Don’t forget to change the path to you MetaTrader installed path) 4- Run the batch file and if you are lucky person like me you will get a screen like this. Figure 1 Metalang compiler As you see you will get the output file “my_first_mql4_script.ex4” 2-The easy way Metatrader has been shipped with a good IDE (integrated development editor) called MetaEditor which has these features: 1- A text editor has the feature of highlighting different constructions of MQL4 language while you are writing/reading code. 2- Easy to compile your program, just click F5 and the MetaEditor will make all the hard work for you and produces the “ex4” file. Besides it’s easy to see what the wrong in your program is (in the Error Tab – see figure 2). 3- Built-in a dictionary book which you can access by highlight the keyword you want to know further about it then press F1. Figure 2 MetaEditor 4 In the coming lessons we will know more about MetaEditor. Today I just came to say hello, tomorrow we will start the real works. Tomorrow we will study the Syntax of MQL4? I welcome very much the questions and the suggestions. See you Coders’ Guru 19-10-2005 MQL4 COURSE By Coders’ guru www.forex-tsd.com -2- SYNTAX -------------------- I hope you enjoyed the “Welcome” lesson which tried to answer the very basic questions; what MQL4 is, why MQL4 and where (to write) MQL4? Always the biggest and the most important question(s) are how, and the entire coming lessons are the answer. Now, I want you to empty your mind from any confusion and read carefully the next few concepts. We are talking today about the SYNTAX rules of MQL4. And as I told you before, If you are programming in C (or its superset C++) then you know a lot of MQL4 before even I start my lessons. That’s because the syntax of MQL4 is very like of the syntax of C. The dictionary means of the word SYNTAX of a programming language is: “The set of allowed reserved words and their parameters and the correct word order in the expression is called the syntax of language”. “Wikipedia” So, when we are studying the syntax of the language we are studying its grammar and writing rules which consist of: • Format • Comments • Identifiers • Reserved words Let’s slice the cake. 1- Format: When you write your code, you can freely use any set of spaces, tabs and empty lines you want to separate your code and your line of code to make them readable and eyes pleasing. For example all of these lines are valid in MQL4: double MacdCurrent, MacdPrevious, SignalCurrent; double MacdCurrent, MacdPrevious, SignalCurrent; double MacdCurrent, MacdPrevious, SignalCurrent; But, as you see, the first line is more readable and easy to understand. And as everything in the world there are exceptions to the rule: 1- You can’t use new line in the “Controlling compilation” You will know more about “Controlling compilation” in next lesson but just remember this is an exception. For example the next line of code is invalid and the MQL4 compiler will complain: #property copyright "Copyright © 2004, MetaQuotes Software Corp." This is the valid “Controlling compilation”: #property copyright "Copyright © 2004, MetaQuotes Software Corp." 2- You can’t use new line or space in the middle of Constant values, Identifiers or Keywords. For example this line is valid: extern int MA_Period=13; “extren” and “int” here are Keywords , “MA_Period” is an Identifier and “13” is a Constant value.. You will know more in the next lessons. For example the next lines are invalids: extern int MA_Period=1 3; extern int MA_Period=1 3; Notice the tab between 1 and 3. ex tern int MA_Period=13; 2- Comments: To make the programming world easier, any programming language has its style of writing comments. You use Comments to write lines in your code which the compiler will ignore then but it clears your code and makes it understandable. Assume that you write a program in the summer and in the winter you want to read it. Without comments -even you are the code’s creator- you can’t understand all these puzzled lines. MQL4 (& C/C++) uses two kinds of comments styles: 1- Single line comments The Single line comment starts with “//” and ends with the new line. For example: //This is a comment extern int MA_Period=13; extern int MA_Period=13; //This is another comment 2- Multi-line comments The multi-line comment start with “/*” and ends with “*/”. And you can comment more than line or more by putting “/*” at the start of the first line, and “*/” at the end of the last line. For example: /* this is multi line comment*/ You can also nest single line comment inside multi lines comment like that: /* this is multi //another comment nested here. line comment*/ This is a valid comment too: extern int /*HELLO! I’m a comment*/ MA_Period=13; But this is invalid comment: extern int //test MA_Period=13; 3- Identifiers: An identifier is the name you choose to your variables, constants and functions. For example MA_Period here is an identifier: extern int MA_Period=13; There are few rules and restrictions for choosing those names: 1- The length of the Identifier must not exceed 31 characters. 2- The Identifier must begin with a letter (capital or small) or the underlining symbol _. So, it can’t be started with a number or another symbol except the underlining symbol. 3- You can’t use any reserved words as an Identifier. You will see the list of the reserved words too soon. 4- The identifiers’ names are case sensitive. So, MA_PERIOD not the same as ma_period or MA_Period Let’s take some examples: Name1 Valid _Name1 Valid 1Name Invalid (don’t start with number) ~Name1 Invalid (you can only use underline symbol) N~ame1 Invalid (you can only use underline symbol) i_love_my_country_and_my_country_loves_all_the_world Invalid (you can’t exceed the 31 characters length) Color Valid color Invalid (you can’t use reversed word, and color is one of them) 4- Reserved words: There are “words” which the language uses them for specific actions. So, they are reserved to the language usage and you can’t use them as an identifier name or for any other purpose. This is the list of the reserved words (from the MQL4 guide): Data types Memory classes Operators Other bool extern break false color static case true datetime continue double default int else string for void if return switch while For example the next lines of code are invalid: extern int datetime =13; int extern =20; double continue = 0; I hope you enjoyed the lesson. The next lesson will be about the “Data Types”. So, Be Ready, the real hard work is coming! I welcome very much the questions and the suggestions. See you Coders’ Guru 20-10-2005 MQL4 COURSE By Coders’ guru www.forex-tsd.com -3- DATA TYPES -------------------- Welcome to my third lesson in my MQL4 course. I hope you enjoyed the “SYNTAX” lesson, which tried to give you the answers for: • What format you can use to write MQL4 code? • How to make the world better by commenting your code? • What the Identifiers are, and what are the rules of choosing them? • What are the MQL4 Reserved words? If you didn’t read the “SYNTAX” lesson please download it from here: http://forex-tsd.com/attachment.php?attachmentid=399 And you can download the “Welcome” lesson from here: http://forex-tsd.com/attachment.php?attachmentid=372 Don’t forget to login first. Now, let’s enjoy the DATA TYPES. What’s the Data type mean? Any programming language has a set of names of the memory representation of the data. For example if the memory holds numbers between -2147483648 to 2147483647, the most of the programming languages will name this data as “Integer” data type. Variables? Variables are the names that refer to sections of memory into which data can be stored. To help you think of this as a picture, imagine that memory is a series of different size boxes. The box size is memory storage area required in bytes. • In order to use a box to store data, the box must be given a name; this process is known as declaration. • In the declaration process you use a word tell the computer what’s the kind and size of the box you want to use, this word known as keyword. • It helps if you give a box a meaningful name that relates to the type of information which make it easier to find the data, this name is the variable constant. • Data is placed into a box by assigning the data to the box. • When we set the value of the box you have created in the same line you declared the variable; this process is known as initialization. When we create a variable we are telling the computer that we want him to assign a specified memory length (in bytes) to our variable, since storing a simple number, a letter or a large number is not going to occupy the same space in memory, so the computer will ask us what’s the kind of data and how much the length of the data? That is the Data type for. For example if we said this line of code to the computer: int MyVaraible=0; That’s mean we are asking the computer to set a block of 4 bytes length to our variable named “MyVaraiable”. In the previous example we have used: int Keyword int Integer data type. int Declaration MyVaraible Variable’s constant. =0 Initialization We will know more about variables in a coming lesson. In MQL4, these are the kinds of Data types: • Integer (int) • Boolean (bool) • Character (char) • String (string) • Floating-point number (double) • Color (color) • Datetime (datetime) 1- Integer An integer, is a number that can start with a + or a - sign and is made of digits. And its range value is between -2147483648 to 2147483647. MQL4 presents the integer in decimal or hexadecimal format. For example the next numbers are Integers: 12, 3, 2134, 0, -230 0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7 We use the keyword int to create an integer variable. For example: int intInteger = 0; int intAnotherIntger = -100; int intHexIntger=0x12; Decimal and Hexadecimal: Decimal notation is the writing of numbers in the base of 10, and uses digits (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9) to represent numbers. These digits are frequently used with a decimal point which indicates the start of a fractional part, and with one of the sign symbols + (plus) or − (minus) to indicate sign. Hexadecimal is a numeral system with a base of 16 usually written using the symbols 0–9 and A–F or a–f. For example, the decimal numeral 79 can be written as 4F in hexadecimal. 2- Boolean Boolean variable is a data type which can hold only two values, true and false (or their numeric representation, 0 and 1). And it occupies 1 bit of the memory. In MQL4, false,FALSE,False,true,TRUE and True are equals. Boolean named like this in the honor of the great mathematician Boole George. We use the keyword bool to create a boolean variable. For example: bool I = true; bool bFlag = 1; bool bBool=FALSE; 3- Character MQL4 names this Data type “Literal”. A character is one of 256 defined alphabetic, numeric, and special key elements defined in the ASCII (American Standard Code for Information Interchange) set. Characters have integer values corresponding to location in the ASCII set. You write the character constant by using single quotes (') surrounding the character. For example: 'a' , '$' , 'Z' We use the keyword int to create a character variable. For example: int chrA = 'A'; int chrB = '$'; Some characters called Special Characters can’t present directly inside the single quotes because they have a reserved meanings in MQL4 language. Here we use something called Escape Sequence to present those special characters, And that by prefixing the character with the backslash character (\). For example: int chrA = '\\'; //slash character int chrB = '\n'; //new line This is the list of Escape Sequence characters used in MQL4. carriage return \r new line \n horizontal tab \t reverse slash \\ single quote \' double quote \" hexadecimal ASCII-code \xhh ASCII table Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex ------------------------------------------------------------------------------------- (nul) 0 0000 0x00 | (sp) 32 0040 0x20 | @ 64 0100 0x40 | ` 96 0140 0x60 (soh) 1 0001 0x01 | ! 33 0041 0x21 | A 65 0101 0x41 | a 97 0141 0x61 (stx) 2 0002 0x02 | " 34 0042 0x22 | B 66 0102 0x42 | b 98 0142 0x62 (etx) 3 0003 0x03 | # 35 0043 0x23 | C 67 0103 0x43 | c 99 0143 0x63 (eot) 4 0004 0x04 | $ 36 0044 0x24 | D 68 0104 0x44 | d 100 0144 0x64 (enq) 5 0005 0x05 | % 37 0045 0x25 | E 69 0105 0x45 | e 101 0145 0x65 (ack) 6 0006 0x06 | & 38 0046 0x26 | F 70 0106 0x46 | f 102 0146 0x66 (bel) 7 0007 0x07 | ' 39 0047 0x27 | G 71 0107 0x47 | g 103 0147 0x67 (bs) 8 0010 0x08 | ( 40 0050 0x28 | H 72 0110 0x48 | h 104 0150 0x68 (ht) 9 0011 0x09 | ) 41 0051 0x29 | I 73 0111 0x49 | i 105 0151 0x69 (nl) 10 0012 0x0a | * 42 0052 0x2a | J 74 0112 0x4a | j 106 0152 0x6a (vt) 11 0013 0x0b | + 43 0053 0x2b | K 75 0113 0x4b | k 107 0153 0x6b (np) 12 0014 0x0c | , 44 0054 0x2c | L 76 0114 0x4c | l 108 0154 0x6c (cr) 13 0015 0x0d | - 45 0055 0x2d | M 77 0115 0x4d | m 109 0155 0x6d (so) 14 0016 0x0e | . 46 0056 0x2e | N 78 0116 0x4e | n 110 0156 0x6e (si) 15 0017 0x0f | / 47 0057 0x2f | O 79 0117 0x4f | o 111 0157 0x6f (dle) 16 0020 0x10 | 0 48 0060 0x30 | P 80 0120 0x50 | p 112 0160 0x70 (dc1) 17 0021 0x11 | 1 49 0061 0x31 | Q 81 0121 0x51 | q 113 0161 0x71 (dc2) 18 0022 0x12 | 2 50 0062 0x32 | R 82 0122 0x52 | r 114 0162 0x72 (dc3) 19 0023 0x13 | 3 51 0063 0x33 | S 83 0123 0x53 | s 115 0163 0x73 (dc4) 20 0024 0x14 | 4 52 0064 0x34 | T 84 0124 0x54 | t 116 0164 0x74 (nak) 21 0025 0x15 | 5 53 0065 0x35 | U 85 0125 0x55 | u 117 0165 0x75 (syn) 22 0026 0x16 | 6 54 0066 0x36 | V 86 0126 0x56 | v 118 0166 0x76 (etb) 23 0027 0x17 | 7 55 0067 0x37 | W 87 0127 0x57 | w 119 0167 0x77 (can) 24 0030 0x18 | 8 56 0070 0x38 | X 88 0130 0x58 | x 120 0170 0x78 (em) 25 0031 0x19 | 9 57 0071 0x39 | Y 89 0131 0x59 | y 121 0171 0x79 (sub) 26 0032 0x1a | : 58 0072 0x3a | Z 90 0132 0x5a | z 122 0172 0x7a (esc) 27 0033 0x1b | ; 59 0073 0x3b | [ 91 0133 0x5b | { 123 0173 0x7b (fs) 28 0034 0x1c | < 60 0074 0x3c | \ 92 0134 0x5c | | 124 0174 0x7c (gs) 29 0035 0x1d | = 61 0075 0x3d | ] 93 0135 0x5d | } 125 0175 0x7d (rs) 30 0036 0x1e | > 62 0076 0x3e | ^ 94 0136 0x5e | ~ 126 0176 0x7e (us) 31 0037 0x1f | ? 63 0077 0x3f | _ 95 0137 0x5f | (del) 127 0177 0x7f 4- String The string data type is an array of characters enclosed in double quote ("). The array of characters is an array which holds one character after another, starting at index 0. After the last character of data, a NULL character is placed in the next array location. It does not matter if there are unused array locations after that. A NULL character is a special character (represented by the ASCII code 0) used to mark the end of this type of string. See figure 1 for a simple representation of the string constant “hello” in the characters array. Figure 1 – Characters array MQL4 limits the size of the string variable to 255 characters and any character above 255 characters will generate this error: (too long string (255 characters maximum)). You can use any special character -mentioned above- in your string constant by prefixing it with the backslash (\). We use the keyword string to create a string variable. For example: string str1 = "Hello world1, with you coders guru”; string str2 = "Copyright © 2005, \"Forex-tsd forum\"."; //Notice the use of (") character. string str3 = "1234567890"; 5- Floating-point number (double) Floating point number is the Real Number (that is, a number that can contain a fractional part beside the integer part separated with (.) dot).Ex: 3.0,-115.5, 15 and 0.0001. And its range value is between 2.2e-308 to 1.8e308. We use the keyword double to create a floating-point variable. For example: double dblNumber1 = 1000000000000000; double dblNumber3 = 1/4; double dblNumber3 = 5.75; 6- Color Color data type is a special MQL4 data type, which holds a color appears on the MetaTrader chart when you create your own Expert Advisor or Custom Indictor and the user can change it from the property tab of your Expert Advisor or Custom Indictor. You can set the Color variable constant in three ways: 1- By the color name: For the well know colors (called Web Colors Set) you can assign the name of the color to the color variable, see the list of the Web Colors Set. 2- By Character representation (MQL4 named it this name): In this method you use the keyword (C) followed by two signal quotations ('). Between the two signal quotations you set the value of the red, green and blue (know as RGB value of the color). These values have to be between: 0 to 255. And you can write these values in decimal or hexadecimal format. 3- By the integer value: Every color in the Web Colors Set has its integer value which you can write it in decimal or hexadecimal format. And you can assign the Integer value of the color to the color variable. The hexadecimal color format looks like this: 0xBBGGRR where BB is the blue value, GG is green value and RR is the red value. For example: // symbol constants C'128,128,128' // gray C'0x00,0x00,0xFF' // blue // named color Red Yellow Black // integer-valued representation 0xFFFFFF // white 16777215 // white 0x008000 // green 32768 // green We use the keyword color to create a color variable. For example: color clr1= Red; color clr1= C'128,128,128' ; color clr1=32768; Web Colors Set Black DarkGreen DarkSlateGray Olive Green Teal Navy Purple Maroon Indigo MidnightBlue DarkBlue DarkOliveGreen SaddleBrown ForestGreen OliveDrab SeaGreen DarkGoldenrod DarkSlateBlue Sienna MediumBlue Brown DarkTurquoise DimGray LightSeaGreen DarkViolet FireBrick MediumVioletRed MediumSeaGreen Chocolate Crimson SteelBlue Goldenrod MediumSpringGreen LawnGreen CadetBlue DarkOrchid YellowGreen LimeGreen OrangeRed DarkOrange Orange Gold Yellow Chartreuse Lime SpringGreen Aqua DeepSkyBlue Blue Magenta Red Gray SlateGray Peru BlueViolet LightSlateGray DeepPink MediumTurquoise DodgerBlue Turquoise RoyalBlue SlateBlue DarkKhaki IndianRed MediumOrchid GreenYellow MediumAquamarine DarkSeaGreen Tomato RosyBrown Orchid MediumPurple PaleVioletRed Coral CornflowerBlue DarkGray SandyBrown MediumSlateBlue Tan DarkSalmon BurlyWood HotPink Salmon Violet LightCoral SkyBlue LightSalmon Plum Khaki LightGreen Aquamarine Silver LightSkyBlue LightSteelBlue LightBlue PaleGreen Thistle PowderBlue PaleGoldenrod PaleTurquoise LightGrey Wheat NavajoWhite Moccasin LightPink Gainsboro PeachPuff Pink Bisque LightGoldenRod BlanchedAlmond LemonChiffon Beige AntiqueWhite PapayaWhip Cornsilk LightYellow LightCyan Linen Lavender MistyRose OldLace WhiteSmoke Seashell Ivory Honeydew AliceBlue LavenderBlush MintCream Snow White 7- Datetime Datetime data type is a special MQL4 data type, which holds a date and time data. You set the Datetime variable by using the keyword (D) followed by two signal quotations ('). Between the two signal quotations you write a character line consisting of 6 parts for value of year, month, date, hour, minutes, and seconds. Datetime constant can vary from Jan 1, 1970 to Dec 31, 2037. For example: D'2004.01.01 00:00' // New Year D'1980.07.19 12:30:27' D'19.07.1980 12:30:27' D'19.07.1980 12' //equal to D'1980.07.19 12:00:00' D'01.01.2004' //equal to D'01.01.2004 00:00:00' We use the keyword datetime to create a datetime variable. For example: datetime dtMyBirthDay= D'1972.10.19 12:00:00'; datetime dt1= D'2005.10.22 04:30:00'; I hope you enjoyed the lesson. The next lesson will be about the “Operations & Expressions”. I welcome very much the questions and the suggestions. See you Coders’ Guru 22-10-2005 MQL4 COURSE By Coders’ guru www.forex-tsd.com -4- Operations & Expressions -------------------- Welcome to the fourth lesson in my course about MQL4. The previous lesson “Data Types” presented a lot of new concepts; I hope you understand it, and above all you enjoyed it. You can download the previous lesson from here: http://forex-tsd.com/attachment.php?attachmentid=399 http://forex-tsd.com/attachment.php?attachmentid=372 http://forex-tsd.com/attachment.php?attachmentid=469 Don’t forget to login first. Now, let’s enjoy the Operations & Expressions. What’s the meaning of Operations & Expressions? You know the operations very well. If I told you that (+,-,*, /) are the basic arithmetical operators, you will remember very fast what’s the operator means. I hear you saying “OK, I know the operations; could you tell me what’s the meaning of the expression?” Identifiers (do you remember them? If not, Review the SYNTAX lesson) together with the Operations produce the Expressions. Puzzled? Let’s illustrate it in an example: x = (y*z)/w; x,y,z and w, here are identifiers. =,* and / are the operators. The whole line is an expression. When the expressions combined together it makes a statement. And when the statements combined together it makes a function and when the functions combined together it makes a program. In the remaining of this lesson we are going to talk about the kinds operators used in MQL4. So, let’s start with the basic arithmetical operators: 1- Arithmetical operators: In MQL4 there are 9 Arithmetical operations This is the list of them with the usage of each: Operator Name Example Description + Addition operator A = B + C; Add B to C and assign the result to A. - Subtraction operator A = B - C; Subtract C from B and assign the result to A. + - Sign changer operators A = -A; Change the sign of A from positive to negative. * Multiplication operator A = B * C; Multiply B and C and assign the result to A. / Division operator A = B / C; Divide B on C and assign the result to A. % Modulus operator A =A % C; A is the reminder of division of B on C. (ex: 10%2 will produce 0, 10%3 will produce 1). ++ Increment operator A++; Increase A by 1 (ex: if A =1 make it 2). -- Decrement operator A--; Decrease 1 from A (ex: if A =2 make it 1). Note: The remainder operator works by dividing the first number by the second number for the first integer results and then returns the remaining number. For example: 10%5=0 This is because if you divide 10 by 5 you will get 2 and there no remaining value, so the remainder is 0. 10%8=2 This is because if you divide 10 by 8 you will get 1 (1*8=8), so the remainder is (10-8 = 2). 100%15=10 This is because if you divide 100 by 15 you will get 6 (6*15=90), so the remainder is (100-90=10). What about 6%8? It will be 6 because if you divide 6 by 8 you will get 0 (8*0=0), so the remainder is (6- 0=6). Note: You can’t combine the increment and decrement operator with other expressions. For example you can’t say: A=(B++)*5; But you can write it like that: A++; B=A*5; Note: How the above example works? Let’s assume: int A=1; //set A to 1 int B; A++; //increase A by 1, now A=2 B=A*5; //which means B=2*5 2- Assignment operators: The purpose of any expression is producing a result and the assignment operators setting the left operand with this result. For example: A = B * C; Here we multiply B and C and assign the result to A. (=) here is the assignment operator. In MQL4 there are 11 assignments operations This is the list of them with the usage of each: Operator Name Example Description = Assignment operator A = B; Assign B to A. += Additive Assignment operator A += B; It’s equal to: A = A + B; Add B to A and assign the result to A. -= Subtractive Assignment operators A -= B; It’s equal to: A = A - B; Subtract B from A and assign the result to A. *= Multiplicative Assignment operator A *= B; It’s equal to: A = A * B; Multiply A and B and assign the result to A. /= Divisional Assignment operator A /= B; It’s equal to: A = A / B; Divide A on B and assign the result to A. %= Modulating Assignment operator A %= B; It’s equal to: A = A % B; Get the reminder of division of A on B and assign the result to A. >>= Left Shift Assignment operator A >>= B; It shifts the bits of A left by the number of bits specified in B. <<= Right Shift Assignment operator A <<= B; It shifts the bits of A right by the number of bits specified in B. &= AND Assignment operator A &= B; Looks at the binary representation of the values of A and B and does a bitwise AND operation on them. |= OR Assignment operator A |= B; Looks at the binary representation of the values of A and B and does a bitwise OR operation on them. ^= XOR Assignment operator A ^= B; Looks at the binary representation of the values of two A and B and does a bitwise exclusive OR (XOR) operation on them. 3- Relational operators: The relational operators compare two values (operands) and result false or true only. It’s is like the question “Is John taller than Alfred? Yes / no?” The result will be false only if the expression produce zero and true if it produces any number differing from zero; For example: 4 == 4; //true 4 < 4; //false 4 <= 4 //true; In MQL4 there are 6 Relational operations This is the list of them with the usage of each: Operator Name Example Description == Equal operator A == B; True if A equals B else False. != Not Equal operator A != B; True if A does not equal B else False. < Less Than operators A < B; True if A is less than B else False. > Greater Than operator A > B; True if A is greater than B else False. <= Less Than or Equal operator A <= B; True if A is less than or equals B else False. >= Greater Than or Equal operator A >= B; True if A is greater than or equals B else False. 4- Logical operators: Logical operators are generally derived from Boolean algebra, which is a mathematical way of manipulating the truth values of concepts in an abstract way without bothering about what the concepts actually mean. The truth value of a concept in Boolean value can have just one of two possible values: true or false. MQL4 names the Logical operators as Boolean operators MQL4 uses the most important 3 logical operators. This is the list of them with the usage of each: Operator Name Example Description && AND operator A && B; If either of the values are zero the value of the expression is zero, otherwise the value of the expression is 1. If the left hand value is zero, then the right hand value is not considered. || OR operator A || B; If both of the values are zero then the value of the expression is 0 otherwise the value of the expression is 1. If the left hand value is non-zero, then the right hand value is not considered. ! NOT operator !A; Not operator is applied to a non- zero value then the value is zero, if it is applied to a zero value, the value is 1. 5- Bitwise operators: The bitwise operators are similar to the logical operators, except that they work on a smaller scale -- binary representations of data. The following operators are available in MQL4: Operator Name Example Description & AND operator A & B; Compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0. | OR operator A | B; Compares two bits and generates a result of 1 if the bits are complementary; otherwise, it returns 0. ^ EXCLUSIVE-OR operator A ^ B; Compares two bits and generates a result of 1 if either or both bits are 1; otherwise, it returns 0. ~ COMPLEMENT operator ~A; Used to invert all of the bits of the operand. >> The SHIFT RIGHT operator A >> B; Moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half. << The SHIFT LEFT operator A << B; Moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. Each move to the left effectively multiplies op1 by 2. Note Both operands associated with the bitwise operator must be integers. 6- Other operators: There are some operators which used in MQL4 and don’t belong to one of the previous categories: 1- The array indexing operator ([]). 2- The function call operator (()); 3- The function arguments separator operator -comma (,) We will know more about the Arrays and Functions in the next lessons, so just remember these 3 operators as “Other operators”. Operators Precedence: If you don't explicitly indicate the order in which you want the operations in a compound expression to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators with a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Thus, the two following statements are equivalent: x + y / 100 x + (y / 100) //unambiguous, recommended When writing compound expressions, you should be explicit and indicate with parentheses () which operators should be evaluated first. This practice will make your code easier to read and to maintain. The following table shows the precedence assigned to the operators in the MQL4. The operators in this table are listed in precedence order: The higher in the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with a relatively lower precedence. Operators on the same group have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right. Assignment operators are evaluated right to left. () Function call From left to right [] Array element selection ! Negation From left to right ~ Bitwise negation - Sign changing operation * Multiplication From left to right / Division % Module division + Addition From left to right - Subtraction << Left shift From left to right >> Right shift < Less than From left to right <= Less than or equals > Greater than >= Greater than or equals == Equals From left to right != Not equal & Bitwise AND operation From left to right ^ Bitwise exclusive OR From left to right && Logical AND From left to right || Logical OR From left to right = Assignment From right to left += Assignment addition -= Assignment subtraction *= Assignment multiplication /= Assignment division %= Assignment module >>= Assignment right shift <<= Assignment left shift &= Assignment bitwise AND |= Assignment bitwise OR ^= Assignment exclusive OR , Comma From left to right I hope you enjoyed the lesson. I welcome very much the questions and the suggestions. See you Coders’ Guru 23-10-2005 MQL4 COURSE By Coders’ guru www.forex-tsd.com -5- Loops & Decisions Part 1 ---------------------------- Welcome to the fifth lesson in my course about MQL4. You can download the previous lesson from here: http://forex-tsd.com/attachment.php?attachmentid=399 http://forex-tsd.com/attachment.php?attachmentid=372 http://forex-tsd.com/attachment.php?attachmentid=469 http://forex-tsd.com/attachment.php?attachmentid=481 Don’t forget to login first. The normal flow control of the program you write in MQL4 (And in others languages as well) executes from top to bottom, A statement by a statement. A statement is a line of code telling the computer to do something. For example: Print("Hello World"); return 0; A semicolon at end of the statement is a crucial part of the syntax but usually easy to forget, and that's make it the source of 90% of errors. But the top bottom execution is not the only case and it has two exceptions, They are the loops and the decisions. The programs you write like -the human- decides what to do in response of circumstances changing. In these cases the flow of control jumps from one part of the program to another. Statements cause such jumps is called Control Statements. Such controls consist of Loops and Decisions. LOOPS ----------------- Loops causing a section of your program to be repeated a certain number of times. And this repetition continues while some condition is true and ends when it becomes false. When the loop end it passes the control to next statement follow the loop section. In MQL4 there are two kinds of loops: The for Loop -------------------------- The for loop considered the easiest loop because all of its control elements are gathered in one place. The for loop executes a section of code a fixed number of times. For example: int j; for(j=0; j<15; j++) Print(j); How does this work? The for statement consists of for keyword, followed by parentheses that contain three expressions separated by semicolons: for(j=0; j<15; j++) These three expressions are the initialization expression, the test expression and the increment expression: j=0 initialization expression j<15 test expression J++ increment expression The body of the loop is the code to be executed the fixed number of the loop: Print(j); This executes the body of the loop in our example for 15 times. Note: the for statement in not followed by a semicolon. That's because the for statement and the loop body are together considered to be a program statement. The initialization expression: The initialization expression is executed only once, when the loop first starts. And its purpose to give the loop variable an initial value (0 in our example). You can declare the loop variable outside (before) the loop like our example: int j; Or you can make the declaration inside the loop parentheses like this: for(int j=0; j<15; j++) The previous two lines of code are equal, except the Scope of each variable (you will know more about the variable declaration and scopes in the Variables lesson). The outside declaration method makes every line in the code block to know about the variable, while the inside declaration makes only the for loop to know about the variable. You can use more that one initialization expression in for loop by separating them with comma (,) like this: int i; int j; for(i=0 ,j=0;i<15;i++) Print(i); The Test expression: The test expression always a relational expression that uses relational operators (please refer to relational operators in the previous lesson). It evaluated by the loop every time the loop executed to determine if the loop will continue or will stop. It will continue if the result of the expression is true and will stop if it false. In our example the body loop will continue printing i (Print(i)) while the case j<15 is true. For example the j = 0,1,2,3,4,5,6,7,8,9,10,11,12,13 and 14. And when j reaches 15 the loop will stops and the control passes to the statement following the loop. The Increment expression: The increment expression changes the value of the loop variable (j in our example) by increase it value by 1. It executed as the last step in the loop steps, after initializing the loop variable, testing the test expression and executing the body of the loop. Figure 1 shows a flow chart of the for loop. Figure 1 - Flow chart of the for loop Like the initialization expression, in the increment expression you can use more than one increment expression in the for loop by separating them with comma (,) like this: int i; int j; for(i=0 ,j=0;i<15,i<;i++,j++) Print(i); But you can only use one test expression. Initialization expression Test expression Exit Body of loop Increment expression False Another notice about the increment expression, it’s not only can increase the variable of the loop, but it can perform and operation it like for example decrements the loop variable like this: int i; for(i=15;i>0,i<;i--) Print(i); The above example will initialize the i to 15 and start the loop, every time it decreases i by 1 and check the test expression (i>0). The program will produce these results: 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1. Multi statement in the loop body: In our previous examples, we used only one statement in the body of the loop, this is not always the case. You can use multi statements in the loop body delimited by braces like this: for(int i=1;i<=15;i++) { Print(i); PlaySound("alert.wav"); } In the above code the body of the loop contains two statements, the program will execute the first statement then the second one every time the loop executed. Don’t forget to put a semicolon at the end of every statement. The Break Statement: When the keyword presents in the for loop (and in while loop and switch statement as well) the execution of the loop will terminate and the control passes to the statement followed the loop section. For example: for(int i=0;i<15;i++) { if((i==10) break; Print(i); } The above example will execute the loop until i reaches 10, in that case the break keyword will terminate the loop. The code will produce these values: 0,1,2,3,4,5,6,7,8,9. The Continue Statement: The break statement takes you out the loop, while the continue statement will get you back to the top of the loop (parentheses). For example: for(int i=0;i<15; i++) { if(i==10) continue; Print(i) } The above example will execute the loop until i reaches 10, in that case the continue keyword will get the loop back to the top of the loop without printing i the tenth time. The code will produce these values: 0,1,2,3,4,5,6,7,8,9,11,12,13,14. Latest note: You can leave out some or all of the expressions in for loop if you want, for example: for(;;) This loop is like while loop with a test expression always set to true. We will introduce the while loop to you right now. The while Loop --------------------- The for loop usually used in the case you know how many times the loop will be executed. What happen if you don’t know how many times you want to execute the loop? This the while loop is for. The while loop like the for loop has a Test expression. But it hasn’t Initialization or Increment expressions. This is an example: int i=0; while(i<15) { Print(i); i++; } In the example you will notice the followings: • The loop variable had declared and initialized before the loop, you can not declare or initialize it inside the parentheses of the while loop like the for loop. • The i++ statement here is not the increment expression as you may think, but the body of the loop must contain some statement that changes the loop variable, otherwise the loop would never end. How the above example does work? The while statement contains only the Test expression, and it will examine it every loop, if it’s true the loop will continue, if it’s false the loop will end and the control passes to the statement followed the loop section. In the example the loop will execute till i reaches 16 in this case i<15=false and the loop ends. Figure 2 shows a flow chart of the while loop. Figure 2 - Flow chart of the while loop I told you before that the while loop is like the for loop, these are the similar aspects: Test expression Exit Body of loop False True 1. You can use break statement and continue in both of them. 2. You can single or multi statements in the body of the loop in both of them, in the case of using multi statements you have to delimit them by braces. 3. The similar copy of for(;;) is while(true) I hope you enjoyed the lesson. I welcome very much the questions and the suggestions. See you Coders’ Guru 24-10-2005 MQL4 COURSE By Coders’ guru www.forex-tsd.com -6- Loops & Decisions Part 2 ---------------------------- Welcome to the sixth lesson in my course about MQL4. I hope you enjoyed the previous lessons. In the previous lesson, we have talked about the Loops. And we have seen that the Loops are one of two ways we use to change the normal flow of the program execution -from top to bottom. The second way is the Decisions. Decisions in a program cause a one-time jump to a different part of the program, depending on the value of an expression. These are the kinds of decisions statements available in MQL4: The if Statement -------------------------------- The if statement is the simplest decision statement, here’s an example: if( x < 100 ) Print("hi"); Here the if keyword has followed by parentheses, inside the parentheses the Test expression ( x < 100), when the result of test expression is true the body of the if will execute (Print("hi");) ,and if it is false, the control passes to the statement follows the if block. Figure 1 shows the flow chart of the if statement: Figure 1 - Flow chart of the if statement Multi Statements in the if Body: Like the loops, the body of if can consist of more than statement delimited by braces. For example: if(current_price==stop_lose) { Print("you have to close the order"); PlaySound("warning.wav"); } Notice the symbol == in the Test expression; it's one of the Relational Operators you have studied in the lesson 4, operations & expressions. This is a source of a lot of errors, when you forget and use the assignment operator =. Nesting: The loops and decision structures can be basted inside one another; you can nest ifs Test expression Exit Body of if False True inside loops, loops inside ifs, ifs inside ifs, and so on. Here's an example: for(int i=2 ; i<10 ; i++) if(i%2==0) { Print("It's not a prime nomber"); PlaySound("warning.wav"); } In the previous example the if structure nested inside the for loop. Notice: you will notice that there are no braces around the loop body, this is because the if statement and the statements inside its body, are considered to be a single statement. The if...else Statement ------------------------------------------ The if statement let's you to do something if a condition is true, suppose we want to do another thing if it's false. That's the if...else statement comes in. It consist of if statement followed by statement or a block of statements, then the else keyword followed by another statement or a block of statements. Like this example: if(current_price>stop_lose) Print("It’s too late to stop, please stop!"); else Print("you playing well today!"); If the test expression in the if statement is true, the program one message, if it isn’t true, it prints the other. Figure 2 shows the flow chart of the if…else statement: Figure 2 - Flow chart of the if..else statement Nested if…else Statements You can nest if…else statement in ifs statements, you can nest if…else statement in if…else statement, and so on. Like this: if(current_price>stop_lose) Print("It’s too late to stop, please stop!"); if(current_price==stop_lose) Print("It’s time to stop!"); else Print("you playing well today!"); There’s a potential problem in nested if…else statements, you can inadvertently match an else with the wrong if. To solve this case you can do one of two things: Test expression Exit Body of if False True Body of else 1- you can delimited the if…else pairs with braces like this: if(current_price>stop_lose) { Print("It’s too late to stop, please stop!"); if(current_price==stop_lose) Print("It’s time to stop!"); else Print("you playing well today!"); } 2- If you can’t do the first solution (in the case of a lot of if…else statements or you are lazy to do it) take it as rule. Match else with the nearest if. (Here it’s the line if(current_price==stop_lose)). The switch Statement ------------------------------------------ If you have a large decision tree, and all the decisions depend on the value of the same variable, you can use a switch statement here. Here’s an example: switch(x) { case 'A': Print("CASE A"); break; case 'B': case 'C': Print("CASE B or C"); break; default: Print("NOT A, B or C"); break; } In the above example the switch keyword is followed by parentheses, inside the parentheses you’ll find the switch constant, this constant can be an integer, a character constant or a constant expression. The constant expression mustn’t include variable for example: case X+Y: is invalid switch constant. How the above example works? The switch statement matches the constant x with one of the cases constants. In the case x=='A' the program will print "CASE A" and the break statement will take you the control out of the switch block. In the cases x=='B' or x=='C', the program will print "CASE B or C". That’s because there’s no break statement after case 'B':. In the case that x != any of the cases constants the switch statement will execute the default case and print "NOT A, B or C". Figure 3 shows the flow chart of the switch statement Figure 3 - Flow chart of the switch statement I hope you enjoyed the lesson. I welcome very much the questions and the suggestions. See you Coders’ Guru 25-10-2005 switch variable equals first case constant Exit False First case body switch variable equals second case constant switch variable equals third case constant Second case body Third case body Default body False False True True True MQL4 COURSE By Coders’ guru www.forex-tsd.com -7- Functions ------------------- Welcome to the world of MQL4 Functions. The functions in any language take two phases: Learning them which sometimes a boring thing. Using them which always a lifeboat. I want to tell you my traditional sentence: I hope you enjoyed the previous lessons, which you can download them from here: 1- Lesson 1 - Welcome to the MQL4 course. http://www.forex-tsd.com/attachment.php?attachmentid=372 2- Lesson 2 – SYNTAX. http://www.forex-tsd.com/attachment.php?attachmentid=399 3- Lesson 3 - MQL4 Data types. http://www.forex-tsd.com/attachment.php?attachmentid=469 4- Lesson 4 - MQL4 Operations & Expressions. http://www.forex-tsd.com/attachment.php?attachmentid=481 5- Lesson 5- Loops & Decisions (Part1). http://www.forex-tsd.com/attachment.php?attachmentid=504 6- Lesson 6 - Loops & Decisions (Part2). http://www.forex-tsd.com/attachment.php?attachmentid=547 Let’s start the seventh lesson. What’s the meaning of functions? The function is very like the sausage machine, you input the meat and the spices and it outs the sausage. The meat and the spices are the function parameters; the sausage is the function return value. The machine itself is the function body. There’s only one difference between the functions and your sausage machine, some of the functions will return nothing (nothing in MQL4 called void). Let’s take some examples: double // type of the sausage – return value my_func (double a, double b, double c) // function name and parameters list (meat & spices) { return (a*b + c); // sausage outs - returned value } As you see above, the function starts with the type of the returned value “double” followed by the function name which followed by parentheses. Inside the parentheses you put the meat and spices, sorry, you put the parameters of the function. Here we have put three parameters double a, double b, double c. Then the function body starts and ends with braces. In our example the function body will produce the operation (a*b + c). The return keyword is responsible about returning the final result. Return keyword: The return keyword terminate the function (like the break keyword does in the loop), and it gives the control to the function caller (we will know it soon). The return keyword can include an expression inside its parentheses like the above example return (a*b + c); and this means to terminate the function and return the result of the expression. And it can be without expression and its only job in this case is to terminate the function. Notice: Not all the functions use the return keyword, especially if there’s no return value. Like the next example: void // void mean there’s no sausage – returned value. my_func (string s) // function name and parameters list (meat & spices) { Print(s); } The function above will not return value, but it will print the parameter s you provided. When the function has no return value you use “void” as the funciotn returns type. These kinds of functions in some programming language called “Methods”, but MQL4 calling them functions. Function call: We know very well now what the function is (I hope)? How to use the functions in your MQL4? There’s an extra steps after writing your function to use the function in you program. This step is calling it (using it). Assume you have a function which collects the summation of two integers. This is the function: int collect (int first_number, int second_number) { return(first_number+ second_number); } You know how the previous function works, but you want to use it. You use it like this: int a = 10; int b = 15; int sum = collect(a,b); Print (sum); The example above will print 25 (is it a magic). But how did it know? The magic line is int sum = collect(a,b); here you declared a variable (sum) to hold the function return value and gave the function its two parameters (a,b). You basically called the function. MQL4 when see your function name, it will take you parameters and go to the function and it will return –soon- with the result and place them in same line. It’s very like copying all the lines of the function instead of the place you called the function in, easy right? Nesting functions inside function: You can nest function (or more) inside the body of another function. That’s because the caller line is treated like any normal statement (it’s actually a statement). For example: We will use the collect function described above inside another new function which its job is printing the result of the collection: void print_collection (int first_number, int second_number) { int sum = collect(first_number, second_number); Print(sum); } Here we called the collect function inside the print_collection function body and printed the result. void means there’s no return vale (do you still remember?). MQL4 Special functions init(), deinit() and start(): In MQL4, every program begins with the function “init()” (initialize) and it occurs when you attach your program(Expert advisor or Custom indicator) to the MetaTrader charts or in the case you change the financial symbol or the chart periodicity. And its job is initializing the main variables of your program (you will know about the variables initialization in the next lesson). When your program finishes its job or you close the chart window or change the financial symbol or the chart periodicity or shutdown MetaTrader terminal, the function "deinit()" (de-initialize) will occur. The third function (which is the most important one) “start()” will occur every time new quotations are received , you spend 90 of your programming life inside this function. We will know a lot about these functions in our real world lessons when we write our own Expert advisor and Custom Indictor. I hope you enjoyed the lesson. I welcome very much the questions and the suggestions. See you Coders’ Guru 25-10-2005 MQL4 COURSE By Coders’ guru www.forex-tsd.com -8- Variables -------------------- Welcome to my MQL4 variables. I hope you enjoyed the previous lessons and I hope you are ready for the variables challenge: I recommend you to read the “DATA TYPES” lesson before reading this lesson. You can download it here: http://forex-tsd.com/attachment.php?attachmentid=469 Now, let’s enjoy the Variables. What are the variables mean? As I told you the secret before, the variables are the names that refer to sections of memory into which data can be stored. To help you think of this as a picture, imagine that memory is a series of different size boxes. The box size is memory storage area required in bytes. • In order to use a box to store data, the box must be given a name; this process is known as declaration. • In the declaration process you use a word tell the computer what’s the kind and size of the box you want to use, this word known as keyword. • It helps if you give a box a meaningful name that relates to the type of information which make it easier to find the data, this name is the variable constant. • Data is placed into a box by assigning the data to the box. • When we set the value of the box you have created in the same line you declared the variable; this process is known as initialization. When we create a variable we are telling the computer that we want him to assign a specified memory length (in bytes) to our variable, since storing a simple number, a letter or a large number is not going to occupy the same space in memory, so the computer will ask us what’s the kind of data and how much the length of the data? That is the Data type for. For example if we said this line of code to the computer: int MyVaraible=0; That’s mean we are asking the computer to set a block of 4 bytes length to our variable named “MyVaraiable”. In the previous example we have used: int Keyword int Integer data type. int Declaration MyVaraible Variable’s constant. =0 Initialization We will know more about variables in a coming lesson. In MQL4, these are the kinds of Data types: • Integer (int) • Boolean (bool) • Character (char) • String (string) • Floating-point number (double) • Color (color) • Datetime (datetime) I’ve copied the previous few lines from the DATA TYPES lesson for you. To know what’s the variable, now how do to declare the variables: Declaration: Declaring a variable means to introduce it to the world and specify its type. By using the keywords you have learned in the DATA TYPES lesson (int, double, char, bool, string, color and datetime) with the name you chose to the variable. For example: int MyVaraible; Here you declared a variable named MyVaraible which is an integer type. And before the declaration you can’t use the MyVariable in your code. If you used it without declaration the MQL4 compiler will complain and will tell you something like this:'MyVaraible' - variable not defined. 1 error(s), 0 warning(s). Initialization: Initializing the variable means to assign a value to it, for example MyVaraible=0; You can initialize the variable at the same line of the declaration like the example: int MyVaraible=0; And you can declare the variable in one place and initialize it in another place like this: int MyVaraible; … … MyVaraible=5; But keep in your mind this fact: the declaration must be before the initialization. Scopes of variables: There are two scopes of the variables, Local and Global. Scope means, which part of code will know about the variable and can use it. Local variable means they are not seen to outside world where they had declared. For example the variables declared inside function are local to the function block of code, and the variables declared inside the loop or decisions block of code are local to those blocks and can be seen or used outside them. For example: double my_func (double a, double b, double c) { int d ; return (a*b + c); } In the above example the variables a,b,c and d are local variables, which can be used only inside the function block of code ( any thing beside the braces) and can’t be used by outside code. So we can’t write a line after the function above saying for example: d=10; because d is not seen to the next line of the function because it’s outside it. The second kind of the scopes is the Global variables, and they are the variables which had declared outside any block of code and can be seen from any part of your code. For example: int Global_Variable; double my_func (double a, double b, double c) { return (a*b + c + Global_Variable); } Here the variable Global_Variable declared outside the function (function level declaration) so, it can be seen by all the functions in you program. The Global variables will automatically set to zero if you didn’t initialize them. Extern variables: The keyword “extern” used to declare a special kind of variables; those kinds of variables are used to define input date of the program, which you can set them form the property of your Expert advisor or Custom indicator. For example: extern color Indicator_color = C'0x00,0x00,0xFF'; // blue int init() { ... } Here the variable Indicator_color had defined as an extern variable which you will see it the first time you attach your indicator (or EA) to the MetaTrader chart and which you can change it from the properties sheet windows. Look at Figure 1. Figure 1: Property sheet of MA indicator Here the variables Period, Shift, MA_method, Apply_to and Style are variables defined using the “extern” keyword so they appear in the property sheet. Any variable you want the user of your program be able to change and set, make it extern variable. I hope you enjoyed the lesson. I welcome very much the questions and the suggestions. See you Coders’ Guru 29-10-2005 MQL4 COURSE By Coders’ guru -9- Preprocessors -------------------- Welcome to my last theoretical lesson in this series. In the next series of lessons we will start to build our first Customer Indicator, So I recommend you to read all the nine lessons carefully before the real work starts. Now, let’s enjoy the Preprocessors: What are the Preprocessors mean? Preprocessors are the instructions you give to the compiler to carry them out before starting (processing) your code. For example if you used the preprocessor directive #include <win32.h> that’s mean you telling the compiler to include the content of the file “win32.h” in the place you wrote the include keyword before processing your code. In MQL4 there are four of preprocessors directives: 1- define directive: define directive used to generate a constant. The constant is very like the variable with only one different, you set its value only once and you can not change its value in your code like the variable. For example: #define my_constant 100 As you can notice in the above example there’s no assignment symbol (=) but only space between the constant name (my_constant ) and its value (100). And you can notice too that the line didn’t end with semi-colon but it ended with a carriage-return character (new line). The name of constant obeys the same rules you had learnt about choosing the identifier names (lesson 2 SYNTAX), for example you can’t start the constant name with a number or exceeds 31 characters. The value of the content can be any type you want. The compiler will replace each occurrence of constant name in your source code with the corresponding value. So you can use the above constant in your code like that: sum = constant1 * 10; 2- property directive: There are predefined constants called “Controlling Compilation” included in the MQL4 language, which you can set them in your program. They are the properties of your program which you can set them using the compiler directive “property” and the compiler will write them in the settings of your executable program (ex4 file). For example: #property link "http://www.forex-tsd.com" #property copyright "Anyone wants to use" This is the list of the MQL4 predefined constants: Constant Type Description link string a link to the company website copyright string the company name stacksize int stack size indicator_chart_window void show the indicator in the chart window indicator_separate_window void show the indicator in a separate window indicator_buffers int the number of buffers for calculation, up to 8 indicator_minimum int the bottom border for the chart indicator_maximum int the top border for the chart indicator_colorN color the color for displaying line N, where N lies between 1 and 8 indicator_levelN double predefined level N for separate window custom indicator, where N lies between 1 and 8 show_confirm void before script run message box with confirmation appears show_inputs void before script run its property sheet appears; disables show_confirm property 3- include directive: When you asking the compiler to include a file name with the “include” directive, it’s very like when you copy the entire file content and paste it in the place of the line you write include. For example: #include <win32.h> In the above example you telling the compiler to open the file “win32.h” and reads all of its content and copy them in the same place of the include statement. Note: in the above example you enclosed the file name with Angle brackets (<>) and that’s mean you telling the compiler to use the default directory (usually, terminal_directory\experts\include) to search for the file win32.h and don’t search the current directory. If the file you want to include located at the same path of your code, you have to use quotes instead of angle brackets like this: #include “mylib.h” In the both cases if the file can’t be found you will get an error message. You can use include at anywhere you want but it usually used at the beginning of the source code. Tip: It’s a good programming practice to write the frequently used code in a separate file and use include directive to put it in your code when you need (just an advice). 4- import directive: It’s like include directive in the aspect of using outside file in your program. But there are differences between them. You use import only with MQL4 executables files (.ex4) or library files (.dll) to import their functions to your program. For example: #import "user32.dll" int MessageBoxA(int hWnd,string lpText,string lpCaption, int uType); int MessageBoxExA(int hWnd,string lpText,string lpCaption, int uType,int wLanguageId); #import "melib.ex4" #import "gdi32.dll" int GetDC(int hWnd); int ReleaseDC(int hWnd,int hDC); #import When you import functions from “ex4” file you haven’t to declare their functions to be ready for use. While importing the functions from a “.dll” file requires you to declare the functions you want to use like this: int MessageBoxA(int hWnd,string lpText,string lpCaption, int uType); And only the functions you has declared you can use in your code. You must end the import directives with a blank import line #import (without parameters). I hope you enjoyed the lesson. And I hope you are ready now for your first Custom Indicator. I welcome very much the questions and the suggestions. See you Coders’ Guru 30-10-2005 MQL4 COURSE By Coders’ guru -10- Your First Indicator Part 1 ------------------------------- Welcome to the practical world of MQL4 courses; welcome to your first indicator in MQL4. I recommend you to read the previous nine lessons very carefully, before continuing with these series of courses, that’s because we will use them so much in our explanations and studies of the Expert Advisors and Custom Indicators which we will create in this series of lessons. Today we are going to create a simple indictor which will not mean too much for our trade world but it means too much to our MQL4 programming understanding. It simply will collect the subtraction of High [] of the price – Low [] of the price; don’t be in a hurry, you will know everything very soon. Let’s swim! MetaEditor: This is the program which has been shipped with MT4 (MetaTrader 4) enables you to write your programs, read MQL4 help, compile your program and More. I’ve made a shortcut for MetaEditor on my desktop for easily access to the program. If you want to run MetaEditor you have three choices. 1- Run MT4, then click F4, choose MetaEditor from Tools menu or click its icon on the Standard toolbar (Figure 1). 2- From Start menu Programs, find MetaTrader 4 group then click MetaEditor. 3- Find the MT4 installation path (usually C:\Program Files\MetaTrader 4), find the MetaEditor.exe and click it (I recommend to make a shortcut on you desktop). Figure 1 – MetaTrader Standard Toolbar Any method you have chosen leads you to MetaEditor as you can see in figure 2. As you can see in figure 2, there are three windows in MetaEditor: 1- The Editor window which you can write your program in. 2- The Toolbox window which contains three tabs: a. Errors tab, you see here the errors (if there any) in your code. b. Find in files tab, you see here the files which contain the keyword you are searching for using the toolbar command “Find in files” or by clicking CTRL +SHIFT+ F hotkeys. c. Help tab, you can highlight the keyword you want to know more about it and click F1, and you will see the help topics in this tab. 3- The Navigator window which contains three tabs: a. Files tab, for easy access to the files saved in the MT4 folder. b. Dictionary tab enables you to access the MQL4 help system. c. Search tab enables you to search the MQL4 dictionary. Figure 2 – MetaEditor Windows I recommend you to navigate around the MetaEditor Menus, Toolbar and windows to be familiar with it. Now let’s enjoy creating our first custom indicator. Editor window Toolbox window Navigator Window Custom Indicator is a program which enables you to use the functions of the technical indicators and it cannot automate your deals. First three steps: Now you have run your MetaEditor and navigated around its Menus, Toolbar and windows, let’s USE it. To create a custom indicator you have to start with three steps (you will learn later how to skip these boring steps (my personal opinion). Step 1: Click File menu New (you use CTRL+N hotkey or click the New Icon in the Standard toolbar). You will get a wizard (Figure 3) guiding you to the next step. Choose Custom Indicator Program option, and then click next. Figure 3 - New project wizard Step 2: When you clicked Next, you will get the second step wizard (Figure 4) which will enable you to edit the properties of your program. In this step you can enter these properties: 1- Name of your program, this is the name which the world will call you program with and it will be saved as the_name_you_have_chosen.mq4 2- Author name, the creator of the program name. 3- Link to your web site. 4- External variables list: I want to pause here to remember you about external variable. External variables are the variables which will be available to the user of you indicator to set from the properties tab of your indicator in MetaTrader. For example: MA_Period in the very popular EMA indicator. And these variables will be declared with the “extern” keyword in your code (Please review Variables lesson). So, this section of the wizard enables you to add these kinds of variables. In our first indicator example we will not need any external variables just write the values you see in figure 4 and let’s go to step 3 by clicking Next button. Figure 4 – Program properties wizard. Step 3: The third wizard you will get when you clicked Next button is the Drawing properties wizard (Figure 5). Its job is enabling you to set the dawning properties of the lines of your indicator, for example: how many lines, colors and where to draw your indicator (in the main chart or in separate windows). This wizard contains the following options: 1- Indicator in separate window option: by clicking this option, your indicator will be drawn in separate windows and not on the main chart window. If you didn’t check the option, your indicator will be drawn in the main chart window. 2- Minimum option: it will be available (enabled) only if you have checked the Indicator in separate window option, and its job is setting the bottom border for the chart. 3- Maximum option: it will be available (enabled) only if you have checked the Indicator in separate window option, and its job is setting the top border for the chart 4- Indexes List: here you add your indicator line and set its default colors. I want you to wait to the next lesson(s) to know more about these options and don’t be in a hurry. For our first indicator example, choose Indicator in separate window option and click Add button, when you click add button the wizard will add a line to the indexes list like you see in figure 5. Figure 5 - Drawing properties wizard. When you click Finish button the Magic will start. You will see the wizard disappeared and the focus returned to the MetaEditor environment and… guess what? You have ready to use first indicator draft code. This is the code you will get: //+------------------------------------------------------------------+ //| My_First_Indicator.mq4 | //| Codersguru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Codersguru" #property link "http://www.forex-tsd.com" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Red //---- buffers double ExtMapBuffer1[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- indicators SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,ExtMapBuffer1); //---- return(0); } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { int counted_bars=IndicatorCounted(); //---- //---- return(0); } //+------------------------------------------------------------------+ As you see in the above code, the wizard has written a lot of code for you, now I have to thank the wizard and to thank you too. In the next lesson we will discover every line of code you have seen above and add our code to make our first indicator. To this lesson I hope you be ready! Please don’t forget to download the source code of the first indicator and warm yourself for the next lesson. I welcome very much the questions and the suggestions. See you Coders’ Guru 01-11-2005 MQL4 COURSE By Coders’ guru www.forex-tsd.com -11- Your First Indicator Part 2 ------------------------------- Welcome to the second part of “Your First Indicator” lesson. In the previous lesson we didn’t write any line of code, that’s because the New Project Wizard wrote all the code for us. Thanks! Today we are going to add few lines to the code the wizard had generated to make our program more useful. Afterwards, we are going to explain the whole of the code line by line. Let’s coding Code we have added: We have added the code which in a bold dark blue to our previous code: //+------------------------------------------------------------------+ //| My_First_Indicator.mq4 | //| Codersguru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Codersguru" #property link "http://www.forex-tsd.com" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Red //---- buffers double ExtMapBuffer1[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- indicators SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,ExtMapBuffer1); string short_name = "Your first indicator is running!"; IndicatorShortName(short_name); //---- return(1); } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { int counted_bars=IndicatorCounted(); //---- check for possible errors if (counted_bars<0) return(-1); //---- last counted bar will be recounted if (counted_bars>0) counted_bars--; int pos=Bars-counted_bars; double dHigh , dLow , dResult; Comment("Hi! I'm here on the main chart windows!"); //---- main calculation loop while(pos>=0) { dHigh = High[pos]; dLow = Low[pos]; dResult = dHigh - dLow; ExtMapBuffer1[pos]= dResult ; pos--; } //---- return(0); } //+------------------------------------------------------------------+ How will we work? We will write the line(s) of the code we are going to explain then we will explain them afterwards, if there are no topics, we will explain the line(s) of code directly. But at the most of the time we will pause to discuss some general topics. I want to here your suggestion about this method please! Now let’s crack this code line by line. //+------------------------------------------------------------------+ //| My_First_Indicator.mq4 | //| Codersguru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ Comments: The first five lines of code (which are in gray color) are comments. You use Comments to write lines in your code which the compiler will ignore them. You are commenting your code for a lot of reasons: • To make it clearer • To document some parts like the copyright and creation date etc. • To make it understandable. • To tell us how the code you have written is work. • … You can write comments in two ways: Single line comments: The Single line comment starts with “//” and ends with the new line. Multi-line comments: The multi-line comment start with “/*” and ends with “*/” and you can comment more than one line. In our program the MQL4 wizard gathered from the data we entered the name of the program, author and the link and wrote them as comments at the top of our program. #property copyright "Codersguru" #property link "http://www.forex-tsd.com" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Red Property directive: As you notice all of these lines start with the word (#property). That’s because they are kind of the Preprocessors directives called property directives. The Preprocessors are the instructions you give to the compiler to carry them out before starting (processing) your code. The property directives are predefined constants called “Controlling Compilation” built in the MQL4 language; their job is setting the properties of your program. For example: is your Indicator will appear in the main chart window or in a separate window? Who is the writer of the program? Note: The preprocessors lines end with a carriage-return character (new line) not a semi-colon symbol. We will try to discuss here the property directives available in MQL4. link: This property setting the web link to your web site which you asked to enter it in step 2 in the Expert Advisor Wizard (review the previous lesson). The data type of this property is string. copyright: It’s the name of the author of the program, same as the link property you asked to enter it in step 2 in the Expert Advisor Wizard. The data type of this property is string. stacksize: It’s an integer value sets the memory size for every thread, the default value is 16384. The data type of this property is integer. indicator_chart_window: When you set this property, your indicator will be drawn in the main chart window (Figure 1). You have to choose one of two options for your Indicators, drawing them in the main chart windows by using this property, or drawing them in separate windows by choosing the indicator_separate_window. You can’t use the both of them at the same time. The data type of this property is void, which means it takes no value. indicator_separate_window: When you set this property, your indicator will be drawn in a separate window (Figure 1). You can set the scale of the separate indicator window using two properties indicator_minimum for the minimum value and indicator_maximum for the maximum value of the scale. And you can set the level of your indicators on these scales using the property indicator_levelN where’s the N is the indicator number. Both of the properties indicator_chart_window and indicator_separate_window are void data type, which mean they don’t take value and you just write them. In our program we will draw our indicator in a separate window: #property indicator_separate_window Figure 1 indicator_minimum: With the aid of this property we are setting the minimum value of the separate windows scale, which is the bottom border of the windows. For example: #propery indicator_minimum 0 #propery indicator_ maximum 100 Here we have set the bottom border of the window to 0 and the top border to 100 (see indicator_ maximum), hence we have a scale ranged from 0 to 100 in our separate window which we are drawing our indicator. The data type of this property is integer. indicator_maximum: With the aid of this property we are setting the maximum value of the separate windows scale, which is the top border of the windows. This value must be greater than the indicator_minimum value. The data type of this property is integer. Main chart window Separate window indicator_levelN: With the aid of this property we are setting the level of the indicator in the scale we have created with the properties indicator_minimum and indicator_maximum, this value must be greater than the indicator_minimum value and smaller than the indicator_maximum value. N is the indicator number which we are setting its level, it must range from 1 to 8 (because we are allowed only to use up to 8 indicator buffers in our program, so we can set the indicator_level for each of them using its number). For example: #propery indicator_minimum 0 #propery indicator_minimum 100 #propery indicator_level1 10 //set the first indicator buffer level #propery indicator_level2 65.5 //set the second indicator buffer level The data type of this property is double. indicator_buffers: With the aid of this property we are setting the number of memories spaces (Arrays) allocated to draw our line(s). When we set the number (ranged from 1 up to 8) we are telling MQL4: “Please allocate a memory space for me to draw my indicator line”. In our program we used only one buffer. #property indicator_buffers 1 That’s because we will draw only one line. indicator_colorN: We can use up to 8 lines in our indicator, you can set the color of each of them using this property indicator_colorN , where the N is the line number which defined by indicator_buffers. The user of your Indicator can change this color from the properties dialog of your Indicator (Figure 2). In our program the indicator line color will be red. #property indicator_color1 Red The data type of this property is color. Figure 2 double ExtMapBuffer1[]; Arrays: In our life we usually group similar objects into units, in the programming we also need to group together the data items of the same type. We use Arrays to do this task. Arrays are very like the list tables, you group the items in the table and access them the number of the row. Rows in the Arrays called Indexes. To declare an array you use a code like that: int my_array[50]; Here, you have declared an array of integer type, which can hold up to 50 items. You can access each item in the array using the index of the item, like that: My_array[10] = 500; Here, you have set the item number 10 in the array to 500. You can initialize the array at the same line of the declaration like that: int my_array[5] = {1,24,15,66,500}; In our program we used this line of code: double ExtMapBuffer1[]; Here we have declared and array of double type. We will use array to calculate our values which we will draw them on the chart. int init() { } Special functions: Functions are blocks of code which like a machine takes inputs and returns outputs (Please review lesson 7 – Functions). In MQL4 there are three special functions init(): Every program will run this function before any of the other functions, you have to put here you initialization values of you variables. start(): Here’s the most of the work, every time a new quotation have received your program will call this function. deinit(): This is the last function the program will call before it shutdown, you can put here any removals you want. SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,ExtMapBuffer1); string short_name = "Your first indicator is running!"; IndicatorShortName(short_name); Custom indicator functions: I can’t give you a description for all of the indicators functions in this lesson. But we will use them all in our next lessons with more details. So, we will study here the functions used in our program. SetIndexStyle: void SetIndexStyle( int index, int type, int style=EMPTY, int width=EMPTY, color clr=CLR_NONE) This function will set the style of the drawn line. The index parameter of this function ranges from 1 to 7 (that’s because the array indexing start with 0 and we have limited 8 line). And it indicte which line we want to set its style. The type parameter is the shape type of the line and can be one of the following shape type’s constants: DRAW_LINE (draw a line) DRAW_SECTION (draw section) DRAW_HISTOGRAM (draw histogram) DRAW_ARROW (draw arrow) DRAW_NONE (no draw) The style parameter is the pen style of drawing the line and can be one of the following styles’ constants: STYLE_SOLID (use solid pen) STYLE_DASH (use dash pen) STYLE_DOT (use dot pen) STYLE_DASHDOT (use dash and dot pen) STYLE_DASHDOTDOT (use dash and double dots) Or it can be EMPTY (default) which means it will be no changes in the line style. The width parameter is the width of line and ranges from 1 to 5. Or it can be EMPTY (default) which means the width will not change. The clr parameter is the color of the line. It can be any valid color type variable. The default value is CLR_NONE which means empty state of colors. In our line of code: SetIndexStyle(0,DRAW_LINE); We have set the index to 0 which means we will work with the first (and the only) line. And we have set the shape type of our line to DRAW_LINE because we want to draw a line in the chart. And we have left the other parameters to their default values. SetIndexBuffer: bool SetIndexBuffer( int index, double array[]) This function will set the array which we will assign to it our indicator value to the indicator buffer which will be drawn. The function takes the index of the buffer where’s 0 is the first buffer and 2 is the second, etc. Then it takes the name of the array. It returns true if the function succeeds and false otherwise. In our program the array which will hold our calculated values is ExtMapBuffer1. And we have only one indicator buffer (#property indicator_buffers 1). So it will be the buffer assigned. IndicatorShortName: void IndicatorShortName( string name) This function will set the text which will be showed on the upper left corner of the chart window (Figure 3) to the text we have inputted. In our program we declared a string variable and assigned the value “You first indicator is running” to it, then we passed it to the IndicatorShortName function. string short_name = "Your first indicator is running!"; IndicatorShortName(short_name); Figure 3 return(0); This is the return value of the init() function which terminate the function and pass the program to the execution of the next function start(). int deinit() { //---- //---- return(0); } Nothing new to say about deinit() function. We will continue with remaining of the code in the next lesson. I hope you enjoyed the lesson and I welcome your questions. See you Coders’ Guru 06-11-2005 The short name MQL4 COURSE By Coders’ guru www.forex-tsd.com -12- Your First Indicator Part 3 ------------------------------- Welcome to the third part of “Your First Indicator” lesson. In the previous lesson we studied the code of our first indicator line by line and we reached the function dinit(). I hope you’ve came from the previous lessons with a clear idea about what we have done. Today we are going to study start() function and its content. And –finally- we will compile and run our first Indicator. Are you ready? Let’s hack the code line by line: Our Code: //+------------------------------------------------------------------+ //| My_First_Indicator.mq4 | //| Codersguru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Codersguru" #property link "http://www.forex-tsd.com" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Red //---- buffers double ExtMapBuffer1[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- indicators SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,ExtMapBuffer1); string short_name = "Your first indicator is running!"; IndicatorShortName(short_name); //---- return(1); } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { int counted_bars=IndicatorCounted(); //---- check for possible errors if (counted_bars<0) return(-1); //---- last counted bar will be recounted if (counted_bars>0) counted_bars--; int pos=Bars-counted_bars; double dHigh , dLow , dResult; Comment("Hi! I'm here on the main chart windows!"); //---- main calculation loop while(pos>=0) { dHigh = High[pos]; dLow = Low[pos]; dResult = dHigh - dLow; ExtMapBuffer1[pos]= dResult ; pos--; } //---- return(0); } //+------------------------------------------------------------------+ int start() {... return(0); } As I told you before, we will spend 90% of programming life inside the braces of start() function. That’s because it’s the most important MQL4 Special functions. On the contrary of the init() and deinit function, start() will not be called (by the terminal client) only one time, But every time a new quotation arrives to MetaTrader terminal client, every time the start() function has been called. start() function returns an integer value like all of the MQL4 special function, where 0 means no error and any number else means an error has been occurred. int counted_bars=IndicatorCounted(); Here, we have defined the variable counted_bars as an integer type, and we have assigned to it the returned value of the function IndicatorCounted(). int IndicatorCounted() This function will return an integer type value holds the count of the bars which our indicator has been calculated them. In the first launch of your indicator this count will be 0 because the indicator didn’t calculate any bars yet. And after that it will be the count of total bars on the chart -1. (Please see the function Bars below). if (counted_bars<0) return(-1); We have got the number of counted_bars in the previous line of code by using IndicatorCounted() function. This number must be 0 or greater if there’s no errors have been occurred. If it’s less than 0 that’s means we have an error and we have to terminate the start() function using the return statement. if (counted_bars>0) counted_bars--; We are checking here if the counted_bars are greater than 0. If that’s true we decrease this number by subtracting 1 from it. That’s because we want to recount the last bar again. We use the decrement operator (please review Lesson 4 - Operations & Expressions) for decreasing the value of counted_bars by 1. Note: We can write the expression counted_bars-- like this: counted_bars = counted_bars-1; int pos=Bars-counted_bars; Here, we are declaring the variable pos to hold the number of times our calculation loop will work (see while loop later in this lesson). That’s by subtracting the counted_bars from the count of total bars on the chart, we get the total bars count using Bars() function. It’s a good time to discuss Bars() function and its brother. Pre-defined MQL4 variables: Ask, Bid, Bars, Close, Open, High, Low, Time and Volume are functions although MQL4 called them Pre-defined variables. And I’ll proof to you why they are functions. Variable means a space in memory and data type you specify. Function means do something and return some value, For example Bars collects and returns the number of the bars in chart. So, is it a variable? Another example will proof for you that they are not variables: If you type and compile this line of code: Bars=1; You will get this error: 'Bars' - unexpected token That’s because they are not variables hence you can’t assign a value to them. Another proof, the next line of code is a valid line and will not generate and error in compiling: Alert(Bars(1)); You can’t pass parameter to a variable, parameters passed only to the functions. I’m so sorry for the lengthiness, let’s discuss every function. int Bars This function returns an integer type value holds count of the total bars on the current chart. double Ask This function (used in your Expert Advisors) returns a double type value holds the buyer’s price of the currency pair. double Bid This function (used in your Expert Advisor) returns a double type value holds the seller’s price of the currency pair. Note: For example, USD/JPY = 133.27/133.32 the left part is called the bid price (that is a price at which the trader sells), the second (the right part) is called the ask price (the price at which the trader buys the currency). double Open[] This function returns a double type value holds the opening price of the referenced bar. Where opening price is the price at the beginning of a trade period (year, month, day, week, hour etc) For example: Open[0] will return the opening price of the current bar. double Close[] This function returns a double type value holds the closing price of the referenced bar. Where closing price is the price at the end of a trade period For example: Close[0] will return the closing price of the current bar. double High[] This function returns a double type value holds the highest price of the referenced bar. Where it’s the highest price from prices observed during a trade period. For example: High [0] will return the highest price of the current bar. double Low[] This function returns a double type value holds the lowest price of the referenced bar. Where it’s the lowest price from prices observed during a trade period. For example: Low [0] will return the lowest price of the current bar. double Volume[] This function returns a double type value holds the average of the total amount of currency traded within a period of time, usually one day. For example: Volume [0] will return this average for the current bar. int Digits This function returns an integer value holds number of digits after the decimal point (usually 4). double Point This function returns a double value holds point value of the current bar (usually 0.0001. datetime Time[] This function returns a datetime type value holds the open time of the referenced bar. For example: Time [0] will return the open time of the current bar. double dHigh , dLow , dResult; We declared three double type variables which we will use them later. Notice the way we used to declare the three of them at the same line by separating them by coma. Comment("Hi! I'm here on the main chart windows!"); This line of code uses the Comment function to print the text “Hi! I'm here on the main chart windows!” on the left top corner of the main chart (figure1). There are two similar functions: void Comment( ... ) This function takes the values passed to it (they can be any type) and print them on the left top corner of the chart (figure 1). void Print ( ... ) This function takes the values passed to it (they can be any type) and print them to the expert log (figure 2). void Alert( ... ) This function takes the values passed to it (they can be any type) and display them in a dialog box (figure 3) Figure 1 – Comment Figure 2- Expert log Figure 3 - Alerts while(pos>=0) { dHigh = High[pos]; dLow = Low[pos]; dResult = dHigh - dLow; ExtMapBuffer1[pos]= dResult ; pos--; } Now, it’s the time to enter the loop for calculating our indicator points to draw them. Any value we assign to the array ExtMapBuffer1[] will be drawn on the chart (because we have assign this array to the drawn buffer using SetIndexBuffer function). Before we enter the loop we have got the number of times the loop will work by subtracting the counted_bars from the total count of the bars on chart. The number of times the loop will work called Loop variable which it’s pos variable in our example. We use the loop variable as a current bar of the calculation for example High[pos] will return the highest price of the pos bar. In the loop body we assign to the variable dHigh the value of the highest price of the current loop variable. And assign to the variable dLow the value of the lowest price of the current loop variable. The result of subtracting dLow from dHigh will be assigned to the variable dResult. Then we using the dResult to draw or indicator line, by assigning it to the drawn buffer array ExtMapBuffer1[]. The last line of the loop is a decrement expression which will decrease the loop variable pos by 1 every time the loop runs. And when this variable reaches -1 the loop will be terminated. Finally, we can compile our indicator. Press F5 or choose Compile from file menu. That will generate the executable file “My_First_indicator.ex4” which you can load in your terminal client. To load your indicator click F4 to bring the terminal client. Then From the Navigator window find the My_First_indicator and attach it to the chart (figure4). Note: The indicator will not do much, but it believed that the subtraction of the highest and lowest of the price gives us the market's volatility. Figure 4 – My_First_Indicator I hope you enjoyed your first indicator. And be prepared to your first Expert Advisor in the next lesson(s). I welcome very much your questions and suggestions. Coders’ Guru 13-11-2005 MQL4 COURSE By Coders’ guru www.forex-tsd.com -13- Your First Expert Advisor Part 1 -------------------- In the previous lesson we created our first indicator. Although this indicator wasn’t useful for us as trader, but it was very useful for us as programmers. The indicators –in general- are very important for the technical analysis of the market in trying to predict the future prices. But with the indicators we observe the chart then use our hands to sell, buy and modify our orders manually. You have to set in front of your terminal, and keep your eyes widely open. If you get tired, want to drink a cup of tea or even take a short vacation. You have to consider one of these solutions: You may rent someone to observe the terminal for you and calling your mobile phone every five minutes to tell you what’s going on. If this employee is an expert, he will cost you the pips you earn. And if he is novice one, he will cost you your capital. The second solution is using a program to automate your trades. That’s what the Expert Advisor is for. The Expert advisor is a program wrote in MQL4 (we are studying MQL4 huh?) uses your favorite indicators and trade methods to automate your orders. It can buy, sell and modify the orders for you. It enables you to drink a cup of tea and save the salary you gave out to your employee or the bunch of flowers you bring to your assistant wife. Today we are going to create our first expert advisor so let’s go. First two steps: Step1: If you didn’t open your MetaEditor yet, I think it’s the time to run it. From the MetaEditor File menu click New (you can use CTRL+N hotkey or click the New icon in the standard toolbar). That will pop up the new program wizard which you have seen when you created your first indicator (Figure 1). This time we will choose the first option “Expert Advisor program” then click Next button. Figure 1 – the first step wizard Step2: When you clicked Next, you have got the general properties wizard (Figure 2). This wizard enables you to set the properties of your expert advisor and to set the external variables you will use in your expert advisor. In this step you can set these properties: 1- Name of your expert advisor, in our sample we will use My_First_EA. 2- Author name of the program, type your name (I typed mine in the sample). 3- Link to your web site. 4- External variables list: This is the list of the external variables you allow the user of your expert advisor to change them from the Expert properties window. To add a new variable you click the Add button, clicking it will add a new record to the external variables list. Every record has three fields: Name: double click this field to set the name (identifier) of the variable. Type: double click this field to set the data type of the variable. Initial value: double click this field to give your variable initialization value. This field is optional which means you can leave it without setting In our sample we have added three variables: Varaible Type initial value --------------------------------------- TakeProfit double 350 Lots double 0.1 TrailingStop double 35 Figure 2 – the second step wizard Now click the Finish button to close the wizard, and MetaEditor will bring to you the code created by the wizard and saves the file My_First_EA.mq4 in the MetaTrader 4 \experts path. Note: you have to put the expert advisors in MetaTrader 4\experts path and the indicators in MetaTrader 4\experts\indicators path, otherwise they will not work. This is the code we have got from the wizard: //+------------------------------------------------------------------+ //| My_First_EA.mq4 | //| Coders Guru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.forex-tsd.com" //---- input parameters extern double TakeProfit=250.0; extern double Lots=0.1; extern double TrailingStop=35.0; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---- //---- return(0); } //+------------------------------------------------------------------+ As you see above, the code generated by the wizard is a template for you to add your code without bothering you by typing the main functions from scratch. Now let’s add our own code: //+------------------------------------------------------------------+ //| My_First_EA.mq4 | //| Coders Guru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.forex-tsd.com" //---- input parameters extern double TakeProfit=250.0; extern double Lots=0.1; extern double TrailingStop=35.0; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } int Crossed (double line1 , double line2) { static int last_direction = 0; static int current_dirction = 0; if(line1>line2)current_dirction = 1; //up if(line1<line2)current_dirction = 2; //down if(current_dirction != last_direction) //changed { last_direction = current_dirction; return (last_direction); } else { return (0); } } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---- int cnt, ticket, total; double shortEma, longEma; if(Bars<100) { Print("bars less than 100"); return(0); } if(TakeProfit<10) { Print("TakeProfit less than 10"); return(0); // check TakeProfit } shortEma = iMA(NULL,0,8,0,MODE_EMA,PRICE_CLOSE,0); longEma = iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0); int isCrossed = Crossed (shortEma,longEma); total = OrdersTotal(); if(total < 1) { if(isCrossed == 1) { ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point, "My EA",12345,0,Green); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice()); } else Print("Error opening BUY order : ",GetLastError()); return(0); } if(isCrossed == 2) { ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0, Bid-TakeProfit*Point,"My EA",12345,0,Red); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice()); } else Print("Error opening SELL order : ",GetLastError()); return(0); } return(0); } for(cnt=0;cnt<total;cnt++) { OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(isCrossed == 2) { OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(),OrderOpenPrice(),Bid- Point*TrailingStop,OrderTakeProfit(),0,Green); return(0); } } } } else // go to short position { // should it be closed? if(isCrossed == 1) { OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if((OrderOpenPrice()-Ask)>(Point*TrailingStop)) { if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) { OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop, OrderTakeProfit(),0,Red); return(0); } } } } } } return(0); } //+------------------------------------------------------------------+ Note: don’t copy and paste the code above because it warped and will not work for you, use the code provided with lesson in www.forex-tsd.com . Scared? Don’t be scared of the 160 lines you have seen above, we will know everything about this code line by line, I promise it’s an easy task. Test the Expert Advisor: Before studying our expert advisor code we have to be check is it profitable one or not. Note: Our expert advisor will work with EURUSD pairs in 4 Hours timeframe. So compile the expert advisor by pressing F5 and load it in MetaTrader. You can test your expert advisor using two methods: 1- Live trading In live trading testing the results are more accurate but you have to spend days (and maybe months) to know is the expert advisor profitable or not. You have to enable the expert advisor to automate your trades. To enable it click Tools Option menu (or use CTRL+O hotkey), that’s will bring the Options windows (figure 3), click Expert Advisors tab and enable these options: Enable Expert Advisors Allow live trading And click Ok button Figure 3 – Enabling expert advisor auto trade You will see the Smile symbol beside the expert advisor name which means your expert advisor is working and ready to trade for you (Figure 4). Figure 4 – Expert advisor is enabled 2- Strategy Tester: The second method of testing your expert advisor which is less accurate but will not take time is the Strategy tester. We will know everything about Strategy tester later, let’s now bring its window by pressing F6 (Figure 5). When you get the window enter these options: Symbol: EURUSD. Period: H4 (4 Hours). Model: Open price only. Figure 5 – Strategy tester window Now click Start button to start testing the expert advisor. You will see a progress bar and the two tabs (Settings and Journal) became five tabs. We interested in Report tab (Figure 6); click it to see your profit. We have a lot to say and to do in the next lesson; I hope you are ready for the challenge. I welcome very much the questions and the suggestions. See you Coders’ Guru 24-11-2005 MQL4 COURSE By Coders’ guru www.forex-tsd.com -14- Your First Expert Advisor Part 2 -------------------- Welcome to the second part of creating Your First Expert Advisor lesson. In the previous part we have taken the code generated by the new program wizard and added our own code which we are going to crack it today line by line. Did you wear your coding gloves? Let’s crack. Note: I have to repeat that our expert advisor is for educational purpose only and will not (or aimed to) make profits. The code we have: //+------------------------------------------------------------------+ //| My_First_EA.mq4 | //| Coders Guru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.forex-tsd.com" //---- input parameters extern double TakeProfit=250.0; extern double Lots=0.1; extern double TrailingStop=35.0; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } int Crossed (double line1 , double line2) { static int last_direction = 0; static int current_direction = 0; if(line1>line2)current_direction = 1; //up if(line1<line2)current_direction = 2; //down if(current_direction != last_direction) //changed { last_direction = current_direction; return (last_direction); } else { return (0); } } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---- int cnt, ticket, total; double shortEma, longEma; if(Bars<100) { Print("bars less than 100"); return(0); } if(TakeProfit<10) { Print("TakeProfit less than 10"); return(0); // check TakeProfit } shortEma = iMA(NULL,0,8,0,MODE_EMA,PRICE_CLOSE,0); longEma = iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0); int isCrossed = Crossed (shortEma,longEma); total = OrdersTotal(); if(total < 1) { if(isCrossed == 1) { ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point, "My EA",12345,0,Green); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice()); } else Print("Error opening BUY order : ",GetLastError()); return(0); } if(isCrossed == 2) { ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0, Bid-TakeProfit*Point,"My EA",12345,0,Red); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice()); } else Print("Error opening SELL order : ",GetLastError()); return(0); } return(0); } for(cnt=0;cnt<total;cnt++) { OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(isCrossed == 2) { OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(),OrderOpenPrice(),Bid- Point*TrailingStop,OrderTakeProfit(),0,Green); return(0); } } } } else // go to short position { // should it be closed? if(isCrossed == 1) { OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if((OrderOpenPrice()-Ask)>(Point*TrailingStop)) { if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) { OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop, OrderTakeProfit(),0,Red); return(0); } } } } } } return(0); } //+------------------------------------------------------------------+ The idea behind our expert advisor. Before digging into cracking our code we have to explain the idea behind our expert advisor. Any expert advisor has to decide when to enter the market and when to exit. And the idea behind any expert advisor is what the entering and exiting conditions are? Our expert advisor is a simple one and the idea behind it is a simple too, let’s see it. We use two EMA indicators, the first one is the EMA of 8 days (sort EMA) and the second one is the EMA of 13 days (long EMA). Note: using those EMAs or any thought in this lesson is not a recommendation of mine, they are for educational purpose only. Entering (Open): Our expert advisor will enter the market when the short EMA line crosses the long EMA line, the direction of each lines will determine the order type: If the short EMA is above the long EMA will buy (long). If the short EMA is below the long EMA we will sell (short). We will open only one order at the same time. Exiting (Close): Our expert advisor will close the buy order when the short EMA crosses the long EMA and the short EMA is below the long EMA. And will close the sell order when the short EMA crosses the long EMA and the short EMA is above the long EMA. Our order (buy or sell) will automatically be closed too when the Take profit or the Stop loss points are reached. Modifying: Beside entering (opening) and exiting (closing) the market (positions) our expert advisor has the ability to modify existing positions based on the idea of Trailing stop point. We will know how we implemented the idea of Trialing stop later in this lesson. Now let’s resume our code cracking. //---- input parameters extern double TakeProfit=250.0; extern double Lots=0.1; extern double TrailingStop=35.0; In the above lines we have asked the wizard to declare three external variables (which the user can set them from the properties window of our expert advisor). The three variables are double data type. We have initialized them to default values (the user can change these values from the properties window, but it recommended to leave the defaults). I have to pause again to tell you a little story about those variables. Stop loss: It’s a limit point you set to your order when reached the order will be closed, this is useful to minimize your lose when the market going against you. Stop losses points are always set below the current asking price on a buy or above the current bid price on a sell. Trailing Stop It’s a kind of stop loss order that is set at a percentage level below (for a long position) or above (for a short position) the market price. The price is adjusted as the price fluctuates. We will talk about this very important concept later in this lesson. Take profit: It’s similar to stop lose in that it’s a limit point you set to your order when reached the order will be closed There are, however, two differences: • There is no “trailing” point. • The exit point must be set above the current market price, instead of below. Figure 1 – Setting Stop loss and Take profit points int Crossed (double line1 , double line2) { static int last_direction = 0; static int current_direction = 0; if(line1>line2)current_direction = 1; //up if(line1<line2)current_direction = 2; //down if(current_direction != last_direction) //changed { last_direction = current_direction; return (last_direction); } else { return (0); } } As I told you before, the idea behind our expert advisor is monitor the crossing of the short EMA and the long EMA lines. And getting the direction of the crossing (which line is above and which line is below) which will determine the type of the order (buy, sell, buy-close and sell-close). For this goal we have created the Crossed function. The Crossed function takes two double values as parameters and returns an integer. The first parameter is the value of the first line we want to monitor (the short EMA in our case) and the second parameter is the value of the second we want to (the long EMA). The function will monitor the two lines every time we call it by saving the direction of the two lines in static variables to remember their state between the repeated calls. • It will return 0 if there’s no change happened in the last directions saved. • It will return 1 if the direction has changed (the lines crossed each others) and the first line is above the second line. • It will return 2 if the direction has changed (the lines crossed each others) and the first line is below the second line. Note: You can use this function in your coming expert advisor to monitor any two lines and get the crossing direction. Let’s see how did we write it? int Crossed (double line1 , double line2) The above line is the function declaration, it means we want to create Crossed function which takes two double data type parameters and returns an integer. When you call this function you have to pass to it two double parameters and it will return an integer to you. You have to declare the function before using (calling) it. The place of the function doesn't matter, I placed it above start() function, but you can place it anywhere else. static int last_direction = 0; static int current_direction = 0; Here we declared two static integers to hold the current and the last direction of the two lines. We are going to use these variables (they are static variables which means they save their value between the repeated calls) to check if there’s a change in the direction of the lines or not. we have initialized them to 0 because we don’t want them to work in the first call to the function (if they worked in the first call the expert advisor will open an order as soon as we load it in the terminal). if(current_direction != last_direction) //changed In this line we compare the two static variables to check for changes between the last call of our function and the current call. If last_direction not equal current_direction that’s mean there’s a change happened in the direction. last_direction = current_direction; return (last_direction); In this case (last_direction not equal current_direction) we have to reset our last_direction by assigning to it the value of the current_direction. And we will return the value of the last_direction. This value will be 1 if the first line is above the second line and 2 if the first line is below the second line. else { return (0); } Else (last_direction is equal current_direction) there’s no change in the lines direction and we have to return 0. Our program will call this function in its start() function body and use the returned value to determine the appropriate action. In the coming part of this lesson we will know how did we call the function, and we will know a lot about the very important trading functions. To that day I hope you the best luck. I welcome very much the questions and the suggestions. See you Coders’ Guru 01-12-2005 MetaQuotes Language 4 MQL4 quick reference Account Information Array Functions Common functions Conversion functions Custom Indicator functions Date & Time functions File functions Global Variables functions Math & Trig Object functions Pre-defined Variables Standard Constants String functions Technical Indicator calls Trading functions Window functions MQL4 quick reference About MetaQuotes Language 4 Syntax Data types Operations & Expressions Operators Functions Variables Preprocessor About MetaQuotes Language 4 MetaQuotes Language 4 (MQL4) is a new built-in language for programming trading strategies. This language allows to create your own Expert Advisors that render the trade process management automatic and are perfectly suitable for implementing your own trade strategies. Also, with the help of MQL4 you can create your own Custom Indicators, Scripts and Libraries of functions. A large number of functions necessary for the analysis of the current and past quotations, the basic arithmetic and logic operations are included in MQL4 structure. There are also basic indicators built in and commands of order placement and control. The MetaEditor 4 text editor that highlights different constructions of MQL4 language is used for writing the program code. It helps users to orient in the expert system text quite easily. As an information book for MQL4 language we use MetaQuotes Language Dictionary. A brief guide contains functions divided into categories, operations, reserved words, and other language constructions and allows finding the description of every element we use. Programs written in MetaQuotes Language 4 have different features and purposes: • Expert Advisors is a mechanical trade system (MTS) linked up to a certain plot. The Advisor can not only inform you about a possibility to strike bargains, but also can make deals on the trade account automatically and direct them right to the trade server. Like most trade systems, the terminal supports testing strategies on historical data with displaying on the chart the spots where trades come in and out. • Custom Indicators are an analogue of a technical indicator. In other words, Custom Indicators allow to create technical indicators in addition to those already integrated into client terminal. Like built-in indicators, they cannot make deals automatically and are aimed only at implementing analytical functions. • Scripts are programs intended for single execution of some actions. Unlike Expert Advisors, Scripts are not run tick wise and have no access to indicator functions. • Libraries are user functions libraries where frequently used blocks of user programs are stored. Syntax Format Comments Identifiers Reserved words Format Spaces, tabs, line feed/form feed symbols are used as separators. You can use any amount of such symbols instead of one. You should use tab symbols to enhance the readability of the text . Comments Multi line comments start with /* symbols and end with */ symbols. Such comments cannot be nested. Single comments start with // symbols, end with the symbol of a new line and can be nested into multi line comments. Comments are allowed where blank spaces are possible and tolerate any number of spaces. Examples: // single comment /* multi- line // nested single comment comment */ Identifiers Identifiers are used as names of variables, functions, and data types. The length of an identifier cannot exceed 31 characters. Symbols you can use: the numbers 0-9, Latin capital and small letters a-z, A-Z (recognized as different symbols), the symbol of underlining (_). The first symbol cannot be a number. The identifier must not coincide with any reserved word. Examples: NAME1 namel Total_5 Paper Reserved words The identifiers listed below are fixed reserved words. A certain action is assigned to each of them, and they cannot be used for other purposes: Data types Memory classes Operators Other bool extern break false color static case true datetime continue double default int else string for void if return switch while Data types Data types overview Integer constants Literal constants Boolean constants Floating-point number constants String constants Color constants Datetime constants Data types overview The main data types are: • Integer (int) • Boolean (bool) • Literals (char) • String (string) • Floating-point number (double) • Color (color) • Datetime (datetime) We need the Color and Datetime types only to facilitate visualization and entering those parameters that we set from expert advisor property tab or custom indicator "Input parameters" tab. The data of Color and Datetime types are represented as integer values. We use implicit type transformation. The priority of types at a transformation in ascending order is the following: int (bool,color,datetime); double; string; Before operations (except for the assignment ones) are performed, the data have been transferred to the maximum precision type. Before assignment operations are performed, the data have been transferred to the integer type. Integer constants Decimal: numbers from 0 to 9; Zero should not be the first number. Examples: 12, 111, -956 1007 Hexadecimal: numbers from 0 to 9, letters a-f or A-F to represent the values 10-15; they start with 0x or 0X. Examples: 0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7 Integer constants can assume values from -2147483648 to 2147483647. If a constant exceeds this range, the result will not be defined. Literal constants Any single character enclosed in single quotes or a hexadecimal ASCII-code of a character looking like '\x10' is a character constant of integer type. Some characters like a single quote ('), double quote (") a question mark (?), a reverse slash (\) and control characters can be represented as a combination of characters starting with a reverse slash (\) according to the table below: line feed NL (LF) \n horizontal tab HT \t carriage return CR \r reverse slash \ \\ single quote ' \' double quote " \" hexadecimal ASCII-code hh \xhh If a character different from those listed above follows the reverse slash, the result will not be defined. Examples: int a = 'A'; int b = '$'; int c = '©'; // code 0xA9 int d = '\xAE'; // symbol code ® Boolean constants Boolean constants may have the value of true or false, numeric representation of them is 1 or 0 respectively. We can also use synonyms True and TRUE, False and FALSE. Examples: bool a = true; bool b = false; bool c = 1; Floating-point number constants Floating-point constants consist of an integer part, a dot (.) and a fractional part. The integer and the fractional parts are a succession of decimal numbers. An unimportant fractional part with the dot can be absent. Examples: double a = 12.111; double b = -956.1007; double c = 0.0001; double d = 16; Floating-point constants can assume values from 2.2e-308 to 1.8e308. If a constant exceeds this range, the result will not be defined. String constants String constant is a succession of ASCII-code characters enclosed in double quotes: "Character constant". A string constant is an array of characters enclosed in quotes. It is of the string type. Each string constant, even if it is identical to another string constant, is saved in a separate memory space. If you need to insert a double quote (") into the line, you must place a reverse slash (\) before it. You can insert any special character constants into the line if they have a reverse slash (\) before them. The length of a string constant lies between 0 and 255 characters. If the string constant is longer, the superfluous characters on the right are rejected. Examples: "This is a character string" "Copyright symbol \t\xA9" "this line with LF symbol \n" "A" "1234567890" "0" "$" Color constants Color constants can be represented in three ways: by character representation; by integer representation; by name (for concrete Web colors only). Character representation consists of four parts representing numerical rate values of three main color components - red, green, blue. The constant starts with the symbol C and is enclosed in single quotes. Numerical rate values of a color component lie in the range from 0 to 255. Integer-valued representation is written in a form of hexadecimal or a decimal number. A hexadecimal number looks like 0x00BBGGRR where RR is the rate of the red color component, GG - of the green one and BB - of the blue one. Decimal constants are not directly reflected in RGB. They represent the decimal value of the hexadecimal integer representation. Specific colors reflect the so-called Web colors set. Examples: // symbol constants C'128,128,128' // gray C'0x00,0x00,0xFF' // blue // named color Red Yellow Black // integer-valued representation 0xFFFFFF // white 16777215 // white 0x008000 // green 32768 // green Datetime constants Datetime constants can be represented as a character line consisting of 6 parts for value of year, month, date, hour, minutes, and seconds. The constant is enclosed in simple quotes and starts with a D character. Datetime constant can vary from Jan 1, 1970 to Dec 31, 2037. Examples: D'2004.01.01 00:00' // New Year D'1980.07.19 12:30:27' D'19.07.1980 12:30:27' D'19.07.1980 12' //equal to D'1980.07.19 12:00:00' D'01.01.2004' //equal to D'01.01.2004 00:00:00' D'12:30:27' //equal to D'[compilation date] 12:30:27' D'' //equal to D'[compilation date] 00:00:00' Operations & Expressions Expressions Arithmetical operations The operation of assignment Operations of relation Boolean operations Bitwise operations Other operations Precedence rules Expressions An expression consists of one or more operands and operation characters. An expression can be written in several lines. Example: a++; b = 10; x = (y*z)/w; Note: An expression that ends with a semicolon is an operator. Arithmetical operations Sum of values i = j + 2; Difference of values i = j - 3; Changing the operation sign x = - x; Product of values z = 3 * x; Division quotient i = j / 5; Division remainder minutes = time % 60; Adding 1 to the variable value i++; Subtracting 1 from the variable value k--; The operations of adding/subtracting 1 cannot be implemented in expressions. Example: int a=3; a++; // valid expression int b=(a++)*3; // invalid expression The operation of assignment Note: The value of the expression that includes this operation is the value of the left operand following the bind character. Assigning the y value to the x variable y = x; Adding x to the y variable y += x; Subtracting x from the y variable y -= x; Multiplying the y variable by x y *= x; Dividing the y variable by x y /= x; Module x value of y y %= x; Logical shift of y representation to the right by x bit y >>= x; Logical shift of y representation to the left by x bit y <<= x; Bitwise operation AND y &= x; Bitwise operation OR y |= x; Bitwise operation exclusive OR y ^= x; Note: There can be only one operation of assignment in the expression. You can implement bitwise operations with integer numbers only. The logical shift operation uses values of x less than 5 binary digits. The greater digits are rejected, so the shift is for the range of 0-31 bit. By %= operation a result sign is equal to the sign of divided number. Operations of relation The logical value false is represented with an integer zero value, while the logical value true is represented with any value differing from zero. The value of expressions containing operations of relation or logical operations is 0 (false) or 1 (true). True if a equals b a == b; True if a does not equal b a != b; True if a is less than b a < b; True if a is greater than b a > b; True if a is less than or equals b a <= b; True if a is greater than or equals b a >= b; Two unnormalized floating-point numbers cannot be linked by == or != operations. That is why it is necessary to subtract one from another, and the normalized outcome needs to be compared to null. Boolean operations The operand of negation NOT (!) must be of arithmetic type; the result equals 1 if the operand value is 0; the result equals 0 if the operand differs from 0. // True if a is false. if(!a) Print("not 'a'"); The logical operation OR (||) of values k and 1. The value k is checked first, the value 1 is checked only if k value is false. The value of this expression is true if the value of k or 1 is true. Example: if(x<k || x>l) Print("out of range"); The logical operation AND (&&) of values x and y. The value x is checked first; the value y is checked only if k value is true. The value of this expression is true if the values of both x and y are true. Example: if(p!=x && p>y) Print("true"); n++; Bitwise operations One's complement of values of variables. The value of the expression contains 1 in all digits where n contains 0; the value of the expression contains 0 in all digits where n contains 1. b = ~n; Binary-coded representation of x is shifted to the right by y digits. The right shift is logical shift, that is the freed left- side bits will be filled with zeros. Example: x = x >> y; The binary-coded representation of x is shifted to the right by y digits; the free digits on the right will be filled with zeroes. Example: x = x << y; Bitwise operation AND of binary-coded x and y representations. The value of the expression contains 1 (true) in all digits where both x and y are not equal to zero; the value of the expression contains 0 (false) in all other digits. Example: b = ((x & y) != 0); Bitwise operation OR of binary-coded x and y representations. The expression contains 1 in all digits where x and y not equals 0; the value of the expression contains 0 in all other digits. Example: b = x | y; Bitwise operation EXCLUSIVE OR of binary-coded x and y representations. The expression contains 1 in all digits where x and y have different binary values; the value of the expression contains 0 in all other digits. Example: b = x ^ y; Note: Bitwise operations are executed with integers only. Other operations Indexing. At addressing to i element of array, the value of the expression equals the value of the variable numbered as i. Example: array[i] = 3; //Assign the value of 3 to array element with index i. //Mind that the first array element //is described with the expression array [0]. The call of function with x1,x2,...,xn arguments. The expression accepts the value returned by the function. If the returned value is of the void type, you cannot place such function call on the right in the assignment operation. Mind that the expressions x1,x2,...,xn are surely executed in this order. Example: double SL=Ask-25*Point; double TP=Ask+25*Point; int ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,SL,TP, "My comment",123,0,Red); The "comma" operation is executed from left to right. A pair of expressions separated by a comma is calculated from left to right with a subsequent deletion of the left expression value. All side effects of left expression calculation can appear before we calculate the right expression. The result type and value coincide with the type and value of the right expression. Precedence rules Each group of operations in the table has the same priority. The higher the priority is, the higher the position of the group in the table is. The execution order determines the grouping of operations and operands. () Function call From left to right [] Array element selection ! Negation From left to right ~ Bitwise negation - Sign changing operation * Multiplication From left to right / Division % Module division + Addition From left to right - Subtraction << Left shift From left to right >> Right shift < Less than From left to right <= Less than or equals > Greater than >= Greater than or equals == Equals From left to right != Not equal & Bitwise AND operation From left to right ^ Bitwise exclusive OR From left to right | Bitwise OR operation From left to right && Logical AND From left to right || Logical OR From left to right = Assignment From right to left += Assignment addition -= Assignment subtraction *= Assignment multiplication /= Assignment division %= Assignment module >>= Assignment right shift <<= Assignment left shift &= Assignment bitwise AND |= Assignment bitwise OR ^= Assignment exclusive OR , Comma From left to right Use parentheses to change the execution order of the operations. Operators Format and nesting Compound operator Expression operator Break operator Continue operator Return operator Conditional operator if Conditional operator if-else Switch operator Cycle operator while Cycle operator for Format and nesting Format. One operator can occupy one or several lines. Two or more operators can be located in the same line. Nesting. Execution order control operators (if, if-else, switch, while and for) can be nested into each other. Compound operator A compound operator (a block) consists of one or more operators of any type enclosed in braces {}. The closing brace should not be followed by a semicolon (;). Example: if(x==0) { x=1; y=2; z=3; } Expression operator Any expression followed by a semicolon (;) is an operator. Here are some examples of expression operators: Assignment operator. Identifier=expression; Example: x=3; y=x=3; // error You can use an assignment operator in an expression only once. Function call operator Function_name(argument1,..., argumentN); Example: fclose(file); Null operator It consists of a semicolon (;) only. We use it to denote a null body of a control operator. Break operator A break; operator terminates the execution of the nearest nested outward operator switch, while or for. The control is given to the operator that follows the terminated one. One of the purposes of this operator is to finish the looping execution when a certain value is assigned to a variable. Example: // searching first zero element for(i=0;i<array_size;i++) if((array[i]==0) break; Continue operator A continue; operator gives control to the beginning of the nearest outward cycle operator while or for, calling the next iteration. The purpose of this operator is opposite to that of break. Example: // summary of nonzero elements of array int func(int array[]) { int array_size=ArraySize(array); int sum=0; for(int i=0;i<array_size; i++) { if(a[i]==0) continue; sum+=a[i]; } return(sum); } Return operator A return; operator terminates the current function execution and returns the control to the calling program. A return(expression); operator terminates the current function execution and returns the control to the calling program together with the expression value. The operator expression is enclosed in parentheses. The expression should not contain an assignment operator. Example: return(x+y); Conditional operator if if (expression) operator; If the expression is true, the operator will be executed. If the expression is false, the control will be given to the expression following the operator. Example: if(a==x) temp*=3; temp=MathAbs(temp); Conditional operator if-else if (expression) operator1 else operator2 If the expression is true, operator1 is executed and the control is given to the operator that follows operator2 (operator2 is not executed). If the expression is false, operator2 is executed. The "else" part of the "if" operator can be omitted. Thus, a divergence may appear in nested "if" operators with an omitted "else" part. If it happens, "else" addresses to the nearest previous operator "if" in the block that has no "else" part. Example: // The "else" part refers to the second "if" operator: if(x>1) if(y==2) z=5; else z=6; // The "else" part refers to the first "if" operator: if(x>l) { if(y==2) z=5; } else { z=6; } // Nested operators if(x=='a') { y=1; } else if(x=='b') { y=2; z=3; } else if(x=='c') { y = 4; } else { Print("ERROR"); } Switch operator switch (expression) { case constant1: operators; break; case constant2: operators; break; ... default: operators; break; } It compares the expression value with constants in all variants of case and gives control to the operator that resembles the expression value. Each variant of the case can be marked with an integer or character constant or a constant expression. The constant expression must not include variables and function calls. Example: case 3+4: //valid case X+Y: //invalid Operators connected with a default label are executed if none of the constants in case operators equals the expression value. The default variant is not obligatory final. If none of the constants resembles the expression value and the default variant is absent, no actions are executed. The keyword case and the constant are just labels and if operators are executed for some variant of case the program will further execute the operators of all following variants until it hits a break operator. It allows linking one succession of operators with several variants. A constant expression is calculated during compilation. None of two constants in one switch operator can have the same values. Example: switch(x) { case 'A': Print("CASE A\n"); break; case 'B': case 'C': Print("CASE B or C\n"); break; default: Print("NOT A, B or C\n"); break; } Cycle operator while while (expression) operator; If the expression is true, the operator is executed till the expression becomes false. If the expression is false, the control will be given to the next operator. Note: An expression value has been defined before the operator is executed. Therefore, if the expression is false from the very beginning, the operator is not executed at all. Example: while(k<n) { y=y*x; k++; } Cycle operator for for (expression1; expression2; expression3) operator; Expression1 describes the initialization of the cycle. Expression2 is the cycle termination check. If it is true, the loop body operator will be executed, Expression3 is executed. The cycle is repeated until Expression2 becomes false. If it is not false, the cycle is terminated, and the control is given to the next operator. Expression3 is calculated after each iteration. The 'for' operator is equivalent to the following succession of operators: expression1; while (expression2) { operator; expression3; }; Example: for(x=1;x<=7;x++) Print(MathPower(x,2)); Any of the three or all three expressions can be absent in the FOR operator, but you should not omit the semicolons (;) that separate them. If Expression2 is omitted, it is considered constantly true. The FOR (;;) operator is a continuous cycle equivalent to the WHILE(l) operator. Each of the expressions 1 to 3 can consist of several expressions united by a comma operator ','. Example: // for(i=0,j=n-l;i<n;i++,j--) a[i]=a[j]; Functions Function definition Function call Special functions init(), deinit() and start() Function definition A function is defined by return value type declaration, by formal parameters and a compound operator (block) that describes actions the function executes. Example: double // type linfunc (double x, double a, double b) // function name and // parameters list { // nested operators return (a*x + b); // returned value } The "return" operator can return the value of the expression included into this operator. In case of a necessity, the expression value assumes the type of function result. A function that does not return a value must be of "void" type. Example: void errmesg(string s) { Print("error: "+s); } Function call function_name (x1,x2,...,xn) Arguments (actual parameters) are transferred according to their value. Each expression x1,...,xn is calculated, and the value is passed to the function. The order of expressions calculation and the order of values loading are guaranteed. During the execution, the system checks the number and type of arguments given to the function. Such way of addressing to the function is called a value call. There is also another way: call by link. A function call is an expression that assumes the value returned by the function. This function type must correspond with the type of the returned value. The function can be declared or described in any part of the program: int somefunc() { double a=linfunc(0.3, 10.5, 8); } double linfunc(double x, double a, double b) { return (a*x + b); } Special functions init(), deinit() and start() Any program begins its work with the "init()" function. "Init()" function attached to charts is launched also after client terminal has started and in case of changing financial symbol and/or charts periodicity. Every program finishes its work with the "deinit()" function. "deinit()" function is launched also by client terminal shutdown, chart window closing, changing financial symbol and/or charts periodicity. When new quotations are received, the "start()" function of attached expert advisors and custom indicator programs is executed. If, when receiving new quotations, the "start()" function triggered on the previous quotations was performed, the next calling "start()" function is executed only after "return()" instruction. All new quotations received during the program execution are ignored by the program. Detaching of the program from charts, changing financial symbol and/or charts periodicity, charts closing and also client terminal exiting interrupts execution of program. Execution of scripts does not depend on quotations coming. Variables Definitions Defining local variables Static variables Defining global variables Defining extern variables Initializing variables External function definition Definitions Definitions are used to define variables and to declare types of variables and functions defined somewhere else. A definition is not an operator. Variables must be declared before being used. Only constants can be used to initialize variables. The basic types are: • string - a string of characters; • int - an integer; • double - a floating-point number (double precision); • bool - a boolean number "true" or "false". Example: string MessageBox; int Orders; double SymbolPrice; bool bLog; The additional types are: • datetime is date and time, unsigned integer, containing seconds since 0 o'clock on January, 1, 1970. • color - integer reflecting a collection of three color components. The additional data types make sense only at the declaration of input data for more convenient their representation in a property sheet. Example: extern datetime tBegin_Data = D'2004.01.01 00:00'; extern color cModify_Color = C'0x44,0xB9,0xE6'; Arrays Array is the indexed sequence of the identical-type data. Example: int a[50]; //A one-dimensional array of 50 integers. double m[7][50]; //Two-dimensional array of seven arrays, //each of them consisting of 50 integers. Only an integer can be an array index. No more than four-dimensional arrays can be declared. Defining local variables The variable declared inside any function is local. The scope of a local variable is limited to limits of the function inside which it is declared. The local variable can be initialized by outcome of any expression. Every call of function execute the initialization of local variables. Local variables are stored in memory area of corresponding function. Formal parameters Examples: void func(int x, double y, bool z) { ... } Formal parameters are local. Scope is the block of the function. Formal parameters must have names differing from those of external variables and local variables defined within one function. In the block of the function to the formal parameters some values can be assigned. Formal parameters can be initialized by constants. In this case, the initializing value is considered as a default value. The parameters following the initialized parameter should be initialized, as well. By calling this function the initialized parameters can be omitted, instead of them defaults will be substituted. Example: func(123, 0.5); Parameters are passed by value. These are modifications of a corresponding local variable inside the called function will not be reflected in any way in the calling function. It is possible to pass arrays as parameters. However, for an array passed as parameter, it is impossible to change the array elements. There is a possibility to pass parameters by reference. In this case, modification of such parameters will be reflected on corresponded variables in the called function. To point, that the parameter is passed by reference, after a data type, it is necessary to put the modifier &. Example: void func(int& x, double& y, double& z[]) { ... } Arrays also can be passed by reference, all modifications will be reflected in the initial array. The parameters that passed by reference, cannot be initialized by default values. Static variables The memory class "static" defines a static variable. The specifier "static" is declared before a data type. Example: { static int flag } Static variables are constant ones since their values are not lost when the function is exited. Any variables in a block, except the formal parameters of the function, can be defined as static. The static variable can be initialized by corresponded type constant, as against a simple local variable which can be initialized by any expression. If there is no explicit initialization, the static variable is initialized with zero. Static variables are initialized only once before calling "init()" function. That is at exit from the function inside which the static variable is declared, the value of this variable being not lost. Defining global variables They are defined on the same level as functions, i.e. they are not local in any block. Example: int Global_flag; int start() { ... } Scope of global variables is the whole program. Global variables are accessible from all functions defined in the program. They are initialized with zero if no other initial value is explicitly defined. The global variable can be initialized only by corresponded type constant. Initialization of global variables is made only once before execution of "init()" function. Note: it is not necessary to confuse the variables declared at a global level, to global variables of Client Terminal, access to which is carried out by GlobalVariable...() function. Defining extern variables The memory class "extern" defines an extern variable. The specifier "extern" is declared before a data type. Example: extern double InputParameter1 = 1.0; int init() { ... } Extern variables define input data of the program, they are accessible from a property program sheet. It is not meaningful to define extern variables in scripts. Arrays cannot represent itself as extern variables. Initializing variables Any variable can be initialized during its definition. Any permanently located variable is initialized with zero (0) if no other initial value is explicitly defined. Global and static variables can be initialized only by constant of corresponded type. Local variables can be initialized by any expression, and not just a constant. Initialization of global and static variables is made only once. Initialization of local variables is made each time by call of corresponded functions. Basic types Examples: int mt = 1; // integer initialization // initialization floating-point number (double precision) double p = MarketInfo(Symbol(),MODE_POINT); // string initialization string s = "hello"; Arrays Example: int mta[6] = {1,4,9,16,25,36}; The list of array elements must be enclosed by curly braces. If the array size is defined, the values being not explicitly defined equal 0. External function definition The type of external functions defined in another component of a program must be explicitly defined. The absence of such a definition may result in errors during the compilation, assembling or execution of your program. While describing an external object, use the key word #import with the reference to the module. Examples: #import "user32.dll" int MessageBoxA(int hWnd ,string szText, string szCaption,int nType); int SendMessageA(int hWnd,int Msg,int wParam,int lParam); #import "lib.ex4" double round(double value); #import Preprocessor Declaring of constant Controlling compilation Including files Importing functions and other modules Declaring of constant If the first character in a program line is #, it means that this line is a compiler command. Such a compiler command ends with a carriage-return character. #define identifier_value The identifier of a constant obeys the same rules as variable names. The value can be of any type. Example: #define ABC 100 #define PI 0.314 #define COMPANY_NAME "MetaQuotes Software Corp." The compiler will replace each occurrence of an identifier in your source code with the corresponding value. Controlling compilation #property identifier_value The list of predefined constant identifiers. Example: #property link "http://www.metaquotes.net" #property copyright "MetaQuotes Software Corp." #property stacksize 1024 Constant Type Description link string a link to the company website copyright string the company name stacksize int stack size indicator_chart_window void show the indicator in the chart window indicator_separate_window void show the indicator in a separate window indicator_buffers int the number of buffers for calculation, up to 8 indicator_minimum int the bottom border for the chart indicator_maximum int the top border for the chart indicator_colorN color the color for displaying line N, where N lies between 1 and 8 indicator_levelN double predefined level N for separate window custom indicator, where N lies between 1 and 8 show_confirm void before script run message box with confirmation appears show_inputs void before script run its property sheet appears; disables show_confirm property The compiler will write the declared values to the settings of the executable module. Including files Note: The #include command line can be placed anywhere in the program, but usually all inclusions are placed at the beginning of the source code. #include <file_name> Example: #include <win32.h> The preprocessor replaces this line with the content of the file win32.h. Angle brackets mean that the file win32.h will be taken from the default directory (usually, terminal_directory\experts\include). The current directory is not searched. #include "file_name" Example: #include "mylib.h" The compiler replaces this line with the content of the file mylib.h. Since this name is enclosed in quotes, the search is performed in the current directory (where the main file of the source code is located). If the file is not found in the current directory, the error will be messaged. Importing functions and other modules #import "file_name" func1(); func2(); #import Example: #import "user32.dll" int MessageBoxA(int hWnd,string lpText,string lpCaption, int uType); int MessageBoxExA(int hWnd,string lpText,string lpCaption, int uType,int wLanguageId); #import "melib.ex4" #import "gdi32.dll" int GetDC(int hWnd); int ReleaseDC(int hWnd,int hDC); #import Functions are imported from MQL4 compiled modules (*.ex4 files) and from operating system modules (*.dll files). In the latter case, the imported functions are also declared. A new #import command (it can be without parameters) finishes the description of imported functions. Account Information AccountBalance() AccountCredit() AccountCompany() AccountCurrency() AccountEquity() AccountFreeMargin() AccountLeverage() AccountMargin() AccountName() AccountNumber() AccountProfit() double AccountBalance() Returns balance value of the current account. Sample Print("Account balance = ",AccountBalance()); double AccountCredit() Returns credit value of the current account. Sample Print("Account number ", AccountCredit()); string AccountCompany() Returns the current account company name. Sample Print("Account company name ", AccountCompany()); string AccountCurrency() Returns currency name of the current account. Sample Print("account currency is ", AccountCurrency()); double AccountEquity() Returns equity value of the current account. Sample Print("Account equity = ",AccountEquity()); double AccountFreeMargin() Returns free margin value of the current account. Sample Print("Account free margin = ",AccountFreeMargin()); int AccountLeverage() Returns leverage of the current account. Sample Print("Account #",AccountNumber(), " leverage is ", AccountLeverage()); double AccountMargin() Returns margin value of the current account. Sample Print("Account margin ", AccountMargin()); string AccountName() Returns the current account name. Sample Print("Account name ", AccountName()); int AccountNumber() Returns the number of the current account. Sample Print("account number ", AccountNumber()); double AccountProfit() Returns profit value of the current account . Sample Print("Account profit ", AccountProfit()); Array Functions ArrayBsearch() ArrayCopy() ArrayCopyRates() ArrayCopySeries() ArrayDimension() ArrayGetAsSeries() ArrayInitialize() ArrayIsSeries() ArrayMaximum() ArrayMinimum() ArrayRange() ArrayResize() ArraySetAsSeries() ArraySize() ArraySort() int ArrayBsearch( double array[], double value, int count=WHOLE_ARRAY, int start=0, int direction=MODE_ASCEND) Returns the index of the first occurrence of a value in the first dimension of array if possible, or the nearest one, if the occurrence is not found. The function cannot be used with string arrays and serial numeric arrays. Note: Binary search processes only sorted arrays. To sort numeric arrays use ArraySort() functions. Parameters array[] - The numeric array to search for. value - The value to search for. count - Count of elements to search for. By default, it searches in the whole array. start - Starting index to search for. By default, the search starts on the first element. direction - Search direction. It can be any of the following values: MODE_ASCEND searching in forward direction, MODE_DESCEND searching in the backward direction. Sample datetime daytimes[]; int shift=10,dayshift; // All the Time[] timeseries are sorted in descendant mode ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1); if(Time[shift]>=daytimes[0]) dayshift=0; else { dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND); if(Period()<PERIOD_D1) dayshift++; } Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ", TimeToStr(daytimes[dayshift])); int ArrayCopy( object& dest[], object source[], int start_dest=0, int start_source=0, int count=WHOLE_ARRAY) Copies an array to another one. Arrays must be of the same type, but arrays with type double[], int[], datetime[], color[], and bool[] can be copied as arrays with same type. Returns the amount of copied elements. Parameters dest[] - Destination array. source[] - Source array. start_dest - Starting index for the destination array. By default, start index is 0. start_source - Starting index for the source array. By default, start index is 0. count - The count of elements that should be copied. By default, it is WHOLE_ARRAY constant. Sample double array1[][6]; double array2[10][6]; // fill array with some data ArrayCopyRates(array1); ArrayCopy(array2, array1,0,Bars-9,10); // now array2 has first 10 bars in the history int ArrayCopyRates(double& dest_array[], string symbol=NULL, int timeframe=0) Copies rates to the two-dimensional array from chart RateInfo array, where second dimension has 6 elements: 0 - time, 1 - open, 2 - low, 3 - high, 4 - close, 5 - volume. Note: Usually retrieved array used to pass large blocks of data to the DLL functions. Parameters dest_array[] - Reference to the two-dimensional destination numeric array. symbol - symbol name, by default, current chart symbol name is used. timeframe - Time frame, by default, the current chart time frame is used. It can be any of Time frame enumeration values. Sample double array1[][6]; ArrayCopyRates(array1,"EURUSD", PERIOD_H1); Print("Current bar ",TimeToStr(array1[0][0]),"Open", array1[0][1]); int ArrayCopySeries( double& array[], int series_index, string symbol=NULL, int timeframe=0) Copies a series array to another one and returns the count of copied elements. Note: If series_index is MODE_TIME, the first parameter must be a datetime array. Parameters array[] - Reference to the destination one-dimensional numeric array. series_index - Series array identifier. It can be any of Series array identifiers enumeration values. symbol - Symbol name, by default, the current chart symbol name is used. timeframe - Time frame, by default, the current chart time frame is used. It can be any of Time frame enumeration values. Sample datetime daytimes[]; int shift=10,dayshift; // All the Time[] timeseries are sorted in descendant mode ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1); if(Time[shift]>=daytimes[0]) dayshift=0; else { dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND); if(Period()<PERIOD_D1) dayshift++; } Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ", TimeToStr(daytimes[dayshift])); int ArrayDimension(int array[]) Returns array rank (dimensions count). Parameters array[] - array to retrieve dimensions count. Sample int num_array[10][5]; int dim_size; dim_size=ArrayDimension(num_array); // dim_size is 2 bool ArrayGetAsSeries(object array[]) Returns true if array is organized as a series array (array elements indexed from last to first) otherwise return false. Parameters array[] - Array to check. Sample if(ArrayGetAsSeries(array1)==true) Print("array1 is indexed as a series array"); else Print("array1 is indexed normally (from left to right)"); int ArrayInitialize(double& array[], double value) Sets all elements of numeric array to the same value. Returns the count of initialized element. Note: It is useless to initialize index buffers in the custom indicator init() function. Parameters array[] - Numeric array to be initialized. value - New value to be set. Sample //---- setting all elements of array to 2.1 double myarray[10]; ArrayInitialize(myarray,2.1); bool ArrayIsSeries(object array[]) Returns true if the array checked is a series array (time,open,close,high,low, or volume). Parameters array[] - Array to check. Sample if(ArrayIsSeries(array1)==false) ArrayInitialize(array1,0); else { Print("Series array cannot be initialized!"); return(-1); } int ArrayMaximum(double array[], int count=WHOLE_ARRAY, int start=0) Searches for elements with maximum value and returns its position. Parameters array[] - The numeric array to search for. count - Scans for the count of elements in the array. start - Start searching on the start index. Sample double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9}; int maxValueIdx=ArrayMaximum(num_array); Print("Max value = ", num_array[maxValueIdx]); int ArrayMinimum(double array[], int count=WHOLE_ARRAY, int start=0) Searches for element with minimum value and returns its position. Parameters array[] - The numeric array to search for. count - Scans for the count of elements in the array. start - Start searching on the start index. Sample double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9}; double minValueidx=ArrayMinimum(num_array); Print("Min value = ", num_array[minValueIdx]); int ArrayRange(object array[], int range_index) Returns the count of elements in the indicated dimension of the array. Since indexes are zero-based, the size of dimension is 1 greater than the largest index. Parameters array[] - Array to check range_index - Dimension index. Sample int dim_size; double num_array[10,10,10]; dim_size=ArrayRange(num_array, 1); int ArrayResize(object& array[], int new_size) Sets new size to the first dimension. If success returns count of all elements contained in the array after resizing, otherwise, returns zero and array is not resized. Parameters array[] - Array to resize. new_size - New size for the first dimension. Sample double array1[][4]; int element_count=ArrayResize(array, 20); // element count is 80 elements bool ArraySetAsSeries(double& array[], bool set) Sets indexing order of the array like a series arrays, i.e. last element has zero index. Returns previous state. Parameters array[] - The numeric array to set. set - The Series flag to set (true) or drop (false). Sample double macd_buffer[300]; double signal_buffer[300]; int i,limit=ArraySize(macd_buffer); ArraySetAsSeries(macd_buffer,true); for(i=0; i<limit; i++) macd_buffer[i]=iMA(NULL,0,12,0,MODE_EMA,PRICE_CLOSE,i)- iMA(NULL,0,26,0,MODE_EMA,PRICE_CLOSE,i); for(i=0; i<limit; i++) signal_buffer[i]=iMAOnArray(macd_buffer,limit,9,0,MODE_SMA,i); int ArraySize(object array[]) Returns the count of elements contained in the array. Parameters array[] - Array of any type. Sample int count=ArraySize(array1); for(int i=0; i<count; i++) { // do some calculations. } int ArraySort( double& array[], int count=WHOLE_ARRAY, int start=0, int sort_dir=MODE_ASCEND) Sorts numeric arrays by first dimension. Series arrays cannot be sorted by ArraySort(). Parameters array[] - The numeric array to sort. count - Count of elements to sort. start - Starting index. sort_dir - Array sorting direction. It can be any of the following values: MODE_ASCEND - sort ascending, MODE_DESCEND - sort descending. Sample double num_array[5]={4,1,6,3,9}; // now array contains values 4,1,6,3,9 ArraySort(num_array); // now array is sorted 1,3,4,6,9 ArraySort(num_array,MODE_DESCEND); // now array is sorted 9,6,4,3,1 Common functions Alert() ClientTerminalName() CompanyName() Comment() GetLastError() GetTickCount() HideTestIndicators() IsConnected() IsDemo() IsDllsAllowed() IsLibrariesAllowed() IsStopped() IsTesting() IsTradeAllowed() MarketInfo() MessageBox() Period() PlaySound() Print() RefreshRates() SendMail() ServerAddress() Sleep() SpeechText() Symbol() UninitializeReason() void Alert(... ) Displays a dialog box containing the user-defined data. Parameters can be of any type. Arrays cannot be passed to the Alert function. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. See also: Comment() and Print() functions. Parameters ... - Any values, separated by commas. Sample if(Close[0]>SignalLevel) Alert("Close price coming ", Close[0],"!!!"); string ClientTerminalName() Returns Client Terminal Name. Sample Print("Terminal name is ",ClientTerminalName()); string CompanyName() Returns Company name Sample Print("Company name is ",CompanyName()); void Comment(... ) Prints some message to the left top corner of the chart. Parameters can be of any type. Arrays cannot be passed to the Comment() function. Arrays should be output elementwise. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. See also: Alert() and Print() functions. Parameters ... - Any values, separated by commas. Sample double free=AccountFreeMargin(); Comment("Account free margin is ",DoubleToStr(free,2),"\n","Current time is ",TimeToStr(CurTime())); int GetLastError() Returns last occurred error after an operation and sets internal last error value to zero. Sample int err; int handle=FileOpen("somefile.dat", FILE_READ|FILE_BIN); if(handle<1) { err=GetLastError(); Print("error(",err,"): ",ErrorDescription(err)); return(0); } int GetTickCount() The GetTickCount() function retrieves the number of milliseconds that have elapsed since the system was started. It is limited to the resolution of the system timer. Sample int start=GetTickCount(); // do some hard calculation... Print("Calculation time is ", GetTickCount()-start, " milliseconds."); void HideTestIndicators(bool hide) The function sets a flag hiding indicators called by the Expert Advisor. After the chart has been tested and opened the flagged indicators will not be drawn on the testing chart. Every indicator called will first be flagged with the current hiding flag. Parameters hide - TRUE - if indicators must be hidden, otherwise, FALSE. Sample HideTestIndicators(true); bool IsConnected() Returns true if client terminal has opened connection to the server, otherwise returns false. Sample if(!IsConnected()) { Print("Connection is broken!"); return(0); } // Expert body that need opened connection // ... bool IsDemo() Returns true if expert runs on demo account, otherwise returns false. Sample if(IsDemo()) Print("I am working on demo account"); else Print("I am working on real account"); bool IsDllsAllowed() Returns true if DLL function call is allowed for the expert, otherwise returns false. See also IsLibrariesAllowed(), IsTradeAllowed(). Sample #import "user32.dll" int MessageBoxA(int hWnd ,string szText, string szCaption,int nType); ... ... if(IsDllsAllowed()==false) { Print("DLL call is not allowed. Experts cannot run."); return(0); } // expert body that calls external DLL functions MessageBoxA(0,"an message","Message",MB_OK); bool IsLibrariesAllowed() Returns true if expert can call library function, otherwise returns false. See also IsDllsAllowed(), IsTradeAllowed(). Sample #import "somelibrary.ex4" int somefunc(); ... ... if(IsLibrariesAllowed()==false) { Print("Library call is not allowed. Experts cannot run."); return(0); } // expert body that calls external DLL functions somefunc(); bool IsStopped() Returns true if expert in the stopping state, otherwise returns false. This function can be used in the cycles to determine expert unloading. Sample while(expr!=false) { if(IsStopped()==true) return(0); // long time procesing cycle // ... } bool IsTesting() Returns true if expert runs in the testing mode, otherwise returns false. Sample if(IsTesting()) Print("I am testing now"); bool IsTradeAllowed() Returns true if trade is allowed for the expert, otherwise returns false. See also IsDllsAllowed(), IsLibrariesAllowed(). Sample if(IsTradeAllowed()) Print("Trade allowed"); double MarketInfo(string symbol, int type) Returns value from Market watch window. Parameters symbol - Instrument symbol. type - Returning data type index. It can be any of Market information identifiers value. Sample double var; var=MarketInfo("EURUSD",MODE_BID); int MessageBox(string text=NULL, string caption=NULL, int flags=EMPTY) The MessageBox function creates, displays, and operates a message box. The message box contains an application-defined message and title, plus any combination of predefined icons and push buttons. If the function succeeds, the return value is one of the MessageBox return code values. Parameters text - Optional text that contains the message to be displayed. caption - Optional text that contains the dialog box title.If this parameter is NULL, the title will be name of expert. flags - Specifies the contents and behavior of the dialog box.This optional parameter can be a combination of flags from the following groups of flags. Sample #include <WinUser32.mqh> if(ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045)==false) { int ret=MessageBox("ObjectCreate() fails with code "+GetLastError()+"\nContinue?", "Question", MB_YESNO|MB_ICONQUESTION); if(ret==IDNO) return(false); } // continue int Period() Returns the number of minutes defining the used period (chart timeframe). Sample Print("Period is ", Period()); void PlaySound(string filename) Function plays sound file. File must be located at the terminal_dir\sounds directory or its subdirectory. Parameters filename - Sound file name. Sample if(IsDemo()) PlaySound("alert.wav"); void Print(... ) Prints some message to the experts log. Parameters can be of any type. Arrays cannot be passed to the Print() function. Arrays should be printed elementwise. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. See also: Alert() and Comment() functions. Parameters ... - Any values, separated by commas. Sample Print("Account free margin is ", AccountFreeMargin()); Print("Current time is ", TimeToStr(CurTime())); double pi=3.141592653589793; Print("PI number is ", DoubleToStr(pi,8)); // Output: PI number is 3.14159265 // Array printing for(int i=0;i<10;i++) Print(Close[i]); bool RefreshRates() Refreshing data in the built-in variables and series arrays. This function is used when expert advisor calculates for a long time and needs refreshing data. Returns true if data are refreshed, otherwise false. Sample int ticket; while(true) { ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE); if(ticket<=0) { int error=GetLastError(); if(error==134) break; // not enough money if(error==135) RefreshRates(); // prices changed break; } else { OrderPrint(); break; } //---- 10 seconds wait Sleep(10000); } void SendMail(string subject, string some_text) Sends mail to address set in the Tools->Options->EMail tab if enabled. Note: Posting e-mail can be denied or address can be empty. Parameters subject - Subject text. some_text - Mail body. Sample double lastclose=Close[0]; if(lastclose<my_signal) SendMail("from your expert", "Price dropped down to "+DoubleToStr(lastclose)); string ServerAddress() Returns connected server address in form of a text string. Sample Print("Server address is ", ServerAddress()); void Sleep(int milliseconds) The Sleep function suspends the execution of the current expert for a specified interval. Parameters milliseconds - Sleeping interval in milliseconds. Sample Sleep(5); void SpeechText(string text, int lang_mode=SPEECH_ENGLISH) Computer speaks some text. Parameters text - Speaking text. lang_mode - SPEECH_ENGLISH (by default) or SPEECH_NATIVE values. Sample double lastclose=Close[0]; SpeechText("Price dropped down to "+DoubleToStr(lastclose)); string Symbol() Returns a text string with the name of the current financial instrument. Sample int total=OrdersTotal(); for(int pos=0;pos<total;pos++) { // check selection result becouse order may be closed or deleted at this time! if(OrderSelect(pos, SELECT_BY_POS)==false) continue; if(OrderType()>OP_SELL || OrderSymbol()!=Symbol()) continue; // do some orders processing... } int UninitializeReason() Returns the code of the uninitialization reason for the experts, custom indicators, and scripts. Return values can be one of Uninitialize reason codes. Sample // this is example int deinit() { switch(UninitializeReason()) { case REASON_CHARTCLOSE: case REASON_REMOVE: CleanUp(); break; // clean up and free all expert's resources. case REASON_RECOMPILE: case REASON_CHARTCHANGE: case REASON_PARAMETERS: case REASON_ACCOUNT: StoreData(); break; // prepare to restart } //... } Conversion functions CharToStr() DoubleToStr() NormalizeDouble() StrToDouble() StrToInteger() StrToTime() TimeToStr() string CharToStr(int char_code) Returns string with one symbol that have specified code Parameters char_code - ASCII char code. Sample string str="WORL" + CharToStr(44); // 44 is code for 'D' // resulting string will be WORLD string DoubleToStr(double value, int digits) Returns text string with the specified numerical value transformed into the specified precision format. Parameters value - Numerical value. digits - Precision format, number of digits after decimal point (0-8). Sample string value=DoubleToStr(1.28473418, 5); // value is 1.28473 double NormalizeDouble(double value, int digits) Rounds floating point number to specified decimal places. Parameters value - Floating point value. digits - Precision format, number of digits after decimal point (0-8). Sample double var1=0.123456789; Print(NormalizeDouble(var1,5)); // output: 0.12346 double StrToDouble(string value) Converts string representation of number to type double. Parameters value - String containing value in fixed number format. Sample double var=StrToDouble("103.2812"); int StrToInteger(string value) Converts string representation of number to type integer. Parameters value - String containing integer number. Sample int var1=StrToInteger("1024"); datetime StrToTime(string value) Converts string in the format "yyyy.mm.dd hh:mi" to type datetime. Parameters value - String value of date/time format such as "yyyy.mm.dd hh:mi". Sample datetime var1; var1=StrToTime("2003.8.12 17:35"); var1=StrToTime("17:35"); // returns with current date var1=StrToTime("2003.8.12"); // returns with midnight time "00:00" string TimeToStr(datetime value, int mode=TIME_DATE|TIME_MINUTES) Returns time as string in the format "yyyy.mm.dd hh:mi". Parameters value - Positive number of seconds from 00:00 January 1, 1970. mode - Optional data output mode can be one or combination of: TIME_DATE get result in form "yyyy.mm.dd", TIME_MINUTES get result in form "hh:mi", TIME_SECONDS get result in form "hh:mi:ss". Sample strign var1=TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS); Custom Indicator functions IndicatorBuffers() IndicatorCounted() IndicatorDigits() IndicatorShortName() SetIndexArrow() SetIndexBuffer() SetIndexDrawBegin() SetIndexEmptyValue() SetIndexLabel() SetIndexShift() SetIndexStyle() SetLevelStyle() SetLevelValue() void IndicatorBuffers(int count) Allocates memory for buffers used for custom indicator calculations. Cannot be greater than 8 and less than indicator_buffers property. If custom indicator requires additional buffers for counting then use this function for pointing common buffers count. Parameters count - Buffers count to allocate. Should be up to 8 buffers. Sample #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- indicator parameters extern int FastEMA=12; extern int SlowEMA=26; extern int SignalSMA=9; //---- indicator buffers double ind_buffer1[]; double ind_buffer2[]; double ind_buffer3[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- 2 additional buffers are used for counting. IndicatorBuffers(3); //---- drawing settings SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3); SetIndexDrawBegin(0,SignalSMA); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2); //---- 3 indicator buffers mapping SetIndexBuffer(0,ind_buffer1); SetIndexBuffer(1,ind_buffer2); SetIndexBuffer(2,ind_buffer3); //---- name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } int IndicatorCounted() Returns bars count that does not changed after last indicator launch. In most cases same count of index values do not need for recalculation. Used for optimizing calculations. Sample int start() { int limit; int counted_bars=IndicatorCounted(); //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- main loop for(int i=0; i<limit; i++) { //---- ma_shift set to 0 because SetIndexShift called abowe ExtBlueBuffer[i]=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i); ExtRedBuffer[i]=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i); ExtLimeBuffer[i]=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i); } //---- done return(0); } void IndicatorDigits(int digits) Sets default precision format for indicators visualization. Parameters digits - Precision format, number of digits after decimal point. Sample #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- indicator parameters extern int FastEMA=12; extern int SlowEMA=26; extern int SignalSMA=9; //---- indicator buffers double ind_buffer1[]; double ind_buffer2[]; double ind_buffer3[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- 2 additional buffers are used for counting. IndicatorBuffers(3); //---- drawing settings SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3); SetIndexDrawBegin(0,SignalSMA); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2); //---- 3 indicator buffers mapping SetIndexBuffer(0,ind_buffer1); SetIndexBuffer(1,ind_buffer2); SetIndexBuffer(2,ind_buffer3); //---- name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } void IndicatorShortName(string name) Sets indicator short name for showing on the chart subwindow. Parameters name - New short name. Sample #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- indicator parameters extern int FastEMA=12; extern int SlowEMA=26; extern int SignalSMA=9; //---- indicator buffers double ind_buffer1[]; double ind_buffer2[]; double ind_buffer3[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- 2 additional buffers are used for counting. IndicatorBuffers(3); //---- drawing settings SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3); SetIndexDrawBegin(0,SignalSMA); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2); //---- 3 indicator buffers mapping SetIndexBuffer(0,ind_buffer1); SetIndexBuffer(1,ind_buffer2); SetIndexBuffer(2,ind_buffer3); //---- name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } void SetIndexArrow(int index, int code) Sets arrow symbol for indicators that draws some lines as arrow. Parameters index - Line index. Should be from 0 to 7. code - Symbol code from Wingdings font or Array constants. Sample SetIndexArrow(0, 217); bool SetIndexBuffer(int index, double array[]) Sets buffer for calculating line. The indicated array bound with previously allocated custom indicator buffer. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). Parameters index - Line index. Should be from 0 to 7. array[] - Array that stores calculated indicator values. Sample double ExtBufferSilver[]; int init() { SetIndexBuffer(0, ExtBufferSilver); // set buffer for first line // ... } void SetIndexDrawBegin(int index, int begin) Sets first bar from what index will be drawn. Index values before draw begin are not significant and does not drawn and not show in the DataWindow. Parameters index - Line index. Should be from 0 to 7. begin - First drawing bar position number. Sample #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- indicator parameters extern int FastEMA=12; extern int SlowEMA=26; extern int SignalSMA=9; //---- indicator buffers double ind_buffer1[]; double ind_buffer2[]; double ind_buffer3[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- 2 additional buffers are used for counting. IndicatorBuffers(3); //---- drawing settings SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3); SetIndexDrawBegin(0,SignalSMA); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2); //---- 3 indicator buffers mapping SetIndexBuffer(0,ind_buffer1); SetIndexBuffer(1,ind_buffer2); SetIndexBuffer(2,ind_buffer3); //---- name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } void SetIndexEmptyValue(int index, double value) Sets drawing line empty value. By default, empty value line is EMPTY_VALUE. Empty values are not drawn and not show in the DataWindow. Parameters index - Line index. Should be from 0 to 7. value - New empty value. Sample SetIndexEmptyValue(6,0.0001); void SetIndexLabel(int index, string text) Sets drawing line description for showing in the DataWindow. Parameters index - Line index. Should be from 0 to 7. text - Label text. NULL means that index value does not show in the DataWindow. Sample //+------------------------------------------------------------------+ //| Ichimoku Kinko Hyo initialization function | //+------------------------------------------------------------------+ int init() { //---- SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,Tenkan_Buffer); SetIndexDrawBegin(0,Tenkan-1); SetIndexLabel(0,"Tenkan Sen"); //---- SetIndexStyle(1,DRAW_LINE); SetIndexBuffer(1,Kijun_Buffer); SetIndexDrawBegin(1,Kijun-1); SetIndexLabel(1,"Kijun Sen"); //---- a_begin=Kijun; if(a_begin<Tenkan) a_begin=Tenkan; SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_DOT); SetIndexBuffer(2,SpanA_Buffer); SetIndexDrawBegin(2,Kijun+a_begin-1); SetIndexShift(2,Kijun); //---- Up Kumo bounding line does not show in the DataWindow SetIndexLabel(2,NULL); SetIndexStyle(5,DRAW_LINE,STYLE_DOT); SetIndexBuffer(5,SpanA2_Buffer); SetIndexDrawBegin(5,Kijun+a_begin-1); SetIndexShift(5,Kijun); SetIndexLabel(5,"Senkou Span A"); //---- SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_DOT); SetIndexBuffer(3,SpanB_Buffer); SetIndexDrawBegin(3,Kijun+Senkou-1); SetIndexShift(3,Kijun); //---- Down Kumo bounding line does not show in the DataWindow SetIndexLabel(3,NULL); //---- SetIndexStyle(6,DRAW_LINE,STYLE_DOT); SetIndexBuffer(6,SpanB2_Buffer); SetIndexDrawBegin(6,Kijun+Senkou-1); SetIndexShift(6,Kijun); SetIndexLabel(6,"Senkou Span B"); //---- SetIndexStyle(4,DRAW_LINE); SetIndexBuffer(4,Chinkou_Buffer); SetIndexShift(4,-Kijun); SetIndexLabel(4,"Chinkou Span"); //---- return(0); } void SetIndexShift(int index, int shift) Sets offset for drawing line. Line will be counted on the current bar, but will be drawn shifted. Parameters index - Line index. Should be from 0 to 7. shift - Shitf value in bars. Sample //+------------------------------------------------------------------+ //| Alligator initialization function | //+------------------------------------------------------------------+ int init() { //---- line shifts when drawing SetIndexShift(0,JawsShift); SetIndexShift(1,TeethShift); SetIndexShift(2,LipsShift); //---- first positions skipped when drawing SetIndexDrawBegin(0,JawsShift+JawsPeriod); SetIndexDrawBegin(1,TeethShift+TeethPeriod); SetIndexDrawBegin(2,LipsShift+LipsPeriod); //---- 3 indicator buffers mapping SetIndexBuffer(0,ExtBlueBuffer); SetIndexBuffer(1,ExtRedBuffer); SetIndexBuffer(2,ExtLimeBuffer); //---- drawing settings SetIndexStyle(0,DRAW_LINE); SetIndexStyle(1,DRAW_LINE); SetIndexStyle(2,DRAW_LINE); //---- index labels SetIndexLabel(0,"Gator Jaws"); SetIndexLabel(1,"Gator Teeth"); SetIndexLabel(2,"Gator Lips"); //---- initialization done return(0); } void SetIndexStyle( int index, int type, int style=EMPTY, int width=EMPTY, color clr=CLR_NONE) Sets new type, style, width and color for a given indicator line. Parameters index - Line index. Should be from 0 to 7. type - Shape style.Can be one of Drawing shape style enumeration. style - Drawing style. Except STYLE_SOLID style all other styles valid when width is 1 pixel.Can be one of Shape style enumeration. EMPTY value indicates that style does not changed. width - Line width. valid values - 1,2,3,4,5. EMPTY value indicates that width does not changed. clr - Line color. Sample SetIndexStyle(3, DRAW_LINE, EMPTY, 2, Red); void SetLevelStyle(int draw_style, int line_width, color clr=CLR_NONE) Function sets new style, width and color of indicator levels. Parameters draw_style - Drawing style. Except for STYLE_SOLID, all other styles are valid if the width is 1 pixel.Can be one of Shape style constants.EMPTY value indicates that style will not be changed. line_width - Line width. Valid values are 1,2,3,4,5. EMPTY value indicates that width will not be changed. clr - Line color. Sample //---- show levels as thick red lines SetLevelStyle(STYLE_SOLID,2,Red) int SetLevelValue(int level, double value) Function sets a new value for the given indicator level. Parameters level - Level index (0-31). value - Value for the given indicator level. Sample SetLevelValue(1,3.14); Date & Time functions CurTime() Day() DayOfWeek() DayOfYear() Hour() LocalTime() Minute() Month() Seconds() TimeDay() TimeDayOfWeek() TimeDayOfYear() TimeHour() TimeMinute() TimeMonth() TimeSeconds() TimeYear() Year() datetime CurTime() Returns the last known server time, number of seconds elapsed from 00:00 January 1, 1970. Sample if(CurTime()-OrderOpenTime()<360) return(0); int Day() Returns the current day of the month. Sample if(Day()<5) return(0); int DayOfWeek() Returns the current zero based day of the week (0-Sunday,1,2,3,4,5,6). Sample // do not work on holidays. if(DayOfWeek()==0 || DayOfWeek()==6) return(0); int DayOfYear() Returns the current day of the year (1-1 january,..,365(6) - 31 december). Sample if(DayOfYear()==245) return(true); int Hour() Returns current hour (0,1,2,..23) Sample bool is_siesta=false; if(Hour()>=12 || Hour()<17) is_siesta=true; datetime LocalTime() Returns local computer time, number of seconds elapsed from 00:00 January 1, 1970. Sample if(LocalTime()-OrderOpenTime()<360) return(0); int Minute() Returns current minute (0,1,2,..59). Sample if(Minute()<=15) return("first quarter"); int Month() Returns current month as number (1-January,2,3,4,5,6,7,8,9,10,11,12). Sample if(Month()<=5) return("first half of year"); int Seconds() Returns current second (0,1,2,..59). Sample if(Seconds()<=15) return(0); int TimeDay(datetime date) Returns day of month (1 - 31) for specified date. Parameters date - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample int day=TimeDay(D'2003.12.31'); // day is 31 int TimeDayOfWeek(datetime date) Returns zero based day of week (0-Sunday,1,2,3,4,5,6) for specified date. Parameters date - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample int weekday=TimeDayOfWeek(D'2004.11.2'); // day is 2 - tuesday int TimeDayOfYear(datetime date) Returns day (1-1 january,..,365(6) - 31 december) of year for specified date. Parameters date - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample int day=TimeDayOfYear(CurTime()); int TimeHour(datetime time) Returns hour for specified time. Parameters time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample int h=TimeHour(CurTime()); int TimeMinute(datetime time) Returns minute for specified time. Parameters time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample int m=TimeMinute(CurTime()); int TimeMonth(datetime time) Returns month for specified time. Parameters time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample int m=TimeMonth(CurTime()); int TimeSeconds(datetime time) Returns seconds after minute (0 – 59) for specified time. Parameters time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample int m=TimeSeconds(CurTime()); int TimeYear(datetime time) Returns year for specified date. Return values can be in range 1970-2037. Parameters time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample int y=TimeYear(CurTime()); int Year() Returns current year. Sample // return if date before 1 May 2002 if(Year()==2002 && Month()<5) return(0); File functions FileClose() FileDelete() FileFlush() FileIsEnding() FileIsLineEnding() FileOpen() FileOpenHistory() FileReadArray() FileReadDouble() FileReadInteger() FileReadNumber() FileReadString() FileSeek() FileSize() FileTell() FileWrite() FileWriteArray() FileWriteDouble() FileWriteInteger() FileWriteString() void FileClose(int handle) Closes file previously opened by FileOpen() functions. Parameters handle - File handle, returned by FileOpen() functions Sample int handle=FileOpen("filename", FILE_CSV|FILE_READ); if(handle>0) { // working with file ... FileClose(handle); } void FileClose(int handle) Closes file previously opened by FileOpen() functions. Parameters handle - File handle, returned by FileOpen() functions Sample int handle=FileOpen("filename", FILE_CSV|FILE_READ); if(handle>0) { // working with file ... FileClose(handle); } void FileFlush(int handle) Flushes all data stored in the file buffer to disk. Parameters handle - File handle, returned by FileOpen() functions. Sample int bars_count=Bars; int handle=FileOpen("mydat.csv",FILE_CSV|FILE_WRITE); if(handle>0) { FileWrite(handle, "#","OPEN","CLOSE","HIGH","LOW"); for(int i=0;i<bars_count;i++) FileWrite(handle, i+1,Open[i],Close[i],High[i], Low[i]); FileFlush(handle); ... for(int i=0;i<bars_count;i++) FileWrite(handle, i+1,Open[i],Close[i],High[i], Low[i]); FileClose(handle); } bool FileIsEnding(int handle) Returns logical true if file pointer is at the end of the file, otherwise returns false. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() functions. Sample if(FileIsEnding(h1)) { FileClose(h1); return(false); } bool FileIsLineEnding(int handle) For CSV file returns logical true if file pointer is at the end of the line, otherwise returns false. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. Sample if(FileIsLineEnding(h1)) { FileClose(h1); return(false); } int FileOpen(string filename, int mode, int delimiter=';') Opens file for input and/or output. Returns a file handle for the opened file. If the function fails, the return value less than 1. To get the detailed error information, call GetLastError() function. Note: Files can be opened only from terminal_dir\experts\files directory and its subdirectories. Parameters filename - File name, file may be with any extensions. mode - Open mode. can be one or combination of values: FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE. delimiter - Delimiter character for csv files. By default passed ';' symbol. Sample int handle; handle=FileOpen("my_data.csv",FILE_CSV|FILE_READ,';'); if(handle<1) { Print("File my_data.dat not found, the last error is ", GetLastError()); return(false); } int FileOpenHistory(string filename, int mode, int delimiter=';') Opens file in the current history directory for input and/or output. Returns a file handle for the opened file. If the function fails, the return value less than 1. To get the detailed error information, call GetLastError(). Parameters filename - File name, file may be with any extensions. mode - Open mode. can be one or combination of values: FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE. delimiter - Delimiter character for csv files. By default passed ';' symbol. Sample int handle=FileOpenHistory("USDX240.HST",FILE_BIN|FILE_WRITE); if(handle<1) { Print("Cannot create file USDX240.HST"); return(false); } // work with file // ... FileClose(handle); int FileReadArray(int handle, object& array[], int start, int count) Reads the indicated count of elements from the binary file to array. Returns actual read elements count. To get the detailed error information, call GetLastError() function. Note: Before reading the data, array must be resized to a sufficient size. Parameters handle - File handle, returned by FileOpen() function. array[] - Array where data will be stored. start - Storing start position into array. count - Count of elements to read. Sample int handle; double varray[10]; handle=FileOpen("filename.dat", FILE_BIN|FILE_READ); if(handle>0) { FileReadArray(handle, varray, 0, 10); FileClose(handle); } int FileReadArray(int handle, object& array[], int start, int count) Reads the indicated count of elements from the binary file to array. Returns actual read elements count. To get the detailed error information, call GetLastError() function. Note: Before reading the data, array must be resized to a sufficient size. Parameters handle - File handle, returned by FileOpen() function. array[] - Array where data will be stored. start - Storing start position into array. count - Count of elements to read. Sample int handle; double varray[10]; handle=FileOpen("filename.dat", FILE_BIN|FILE_READ); if(handle>0) { FileReadArray(handle, varray, 0, 10); FileClose(handle); } int FileReadInteger(int handle, int size=LONG_VALUE) Read the integer from binary files from the current file position. Integer format size can be 1, 2 or 4 bytes length. If the format size is not specified system attempts to read 4 bytes length value. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. size - Format size. Can be CHAR_VALUE(1 byte), SHORT_VALUE(2 bytes) or LONG_VALUE(4 bytes). Sample int handle; int value; handle=FileOpen("mydata.dat", FILE_BIN|FILE_READ); if(handle>0) { value=FileReadInteger(h1,2); FileClose(handle); } double FileReadNumber(int handle) Read the number from the current file position to the delimiter. Only for CSV files. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. Sample int handle; int value; handle=FileOpen("filename.csv", FILE_CSV, ';'); if(handle>0) { value=FileReadNumber(handle); FileClose(handle); } string FileReadString(int handle, int length=0) Read the string from the current file position. Applied to both CSV and binary files. For text files string will be read to the delimiter and for binary file string will be read for the count of characters indicated. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. length - Reading characters count. Sample int handle; string str; handle=FileOpen("filename.csv", FILE_CSV|FILE_READ); if(handle>0) { str=FileReadString(handle); FileClose(handle); } bool FileSeek(int handle, int offset, int origin) Moves the file pointer to a specified location. The FileSeek() function moves the file pointer associated with handle to a new location that is offset bytes from origin. The next operation on the file occurs at the new location. If successful, function returns TRUE. Otherwise, it returns FALSE. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() functions. offset - Offset in bytes from origin. origin - Initial position. Value can be one of this constants: SEEK_CUR - from current position, SEEK_SET - from begin, SEEK_END - from end of file. Sample int handle=FileOpen("filename.csv", FILE_CSV|FILE_READ, ';'); if(handle>0) { FileSeek(handle, 10, SEEK_SET); FileReadInteger(handle); FileClose(handle); handle=0; } int FileSize(int handle) Returns file size in bytes. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. Sample int handle; int size; handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ); if(handle>0) { size=FileSize(handle); Print("my_table.dat size is ", size, " bytes"); FileClose(handle); } int FileSize(int handle) Returns file size in bytes. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. Sample int handle; int size; handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ); if(handle>0) { size=FileSize(handle); Print("my_table.dat size is ", size, " bytes"); FileClose(handle); } int FileWrite(int handle, ... ) Writes to the CSV file some values, delimiter inserted automatically. Returns the number of characters written, or a negative value if an error occurs. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. ... - User data to write, separated with commas. Note: int and double types automatically converted to string,but color, datetime and bool types does not automatically converted and will be writen to file in it's as integers. Sample int handle; datetime orderOpen=OrderOpenTime(); handle=FileOpen("filename", FILE_CSV|FILE_WRITE, ';'); if(handle>0) { FileWrite(handle, Close[0], Open[0], High[0], Low[0], TimeToStr(orderOpen)); FileClose(handle); } int FileWriteArray(int handle, object array[], int start, int count) Writes array to the binary file. Arrays of type int, bool, datetime and color will be written as 4 bytes integers. Arrays of type double will be written as 8 bytes floating point numbers. Arrays of string will be written as one string where elements will be divided by Carriage return and Line feed symbols (0D 0A). Returns the number of elements wrote, or a negative value if an error occurs. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. array[] - Array to write. start - Starting index into array to write. count - Count of elements to write. Sample int handle; double BarOpenValues[10]; // copy first ten bars to the array for(int i=0;i<10; i++) BarOpenValues[i]=Open[i]; // writing array to the file handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE); if(handle>0) { FileWriteArray(handle, BarOpenValues, 3, 7); // writing last 7 elements FileClose(handle); } int FileWriteDouble(int handle, double value, int size=DOUBLE_VALUE) Writes double value to the binary file. If size is FLOAT_VALUE, value will be written as 4 bytes floating point format, else will be written in 8 bytes floating point format. Returns actual written bytes count. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. value - Value to write. size - Optional format flag. It can be any of the following values: DOUBLE_VALUE (8 bytes, default) FLOAT_VALUE (4 bytes). Sample int handle; double var1=0.345; handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE); if(handle<1) { Print("can't open file error-",GetLastError()); return(0); } FileWriteDouble(h1, var1, DOUBLE_VALUE); //... FileClose(handle); int FileWriteInteger(int handle, int value, int size=LONG_VALUE) Writes integer value to the binary file. If size is SHORT_VALUE, value will be written as 2 bytes integer, if size is CHAR_VALUE, value will be written as 1 bytes integer and if size is LONG_VALUE, value will be written as 4 bytes integer. Returns actual written bytes count. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. value - Value to write. size - Optional format flag. It can be any of the following values: CHAR_VALUE (1 byte), SHORT_VALUE (2 bytes), LONG_VALUE (4 bytes, default). Sample int handle; int value=10; handle=FileOpen("filename.dat", FILE_BIN|FILE_WRITE); if(handle<1) { Print("can't open file error-",GetLastError()); return(0); } FileWriteInteger(handle, value, SHORT_VALUE); //... FileClose(handle); int FileWriteString(int handle, string value, int length) Writes string to the binary file from current file position. Returns actual written bytes count. To get the detailed error information, call GetLastError() function. Parameters handle - File handle, returned by FileOpen() function. value - Text to write. length - Counts of characters to write. Sample int handle; string str="some string"; handle=FileOpen("filename.bin", FILE_BIN|FILE_WRITE); if(handle<1) { Print("can't open file error-",GetLastError()); return(0); } FileWriteString(h1, str, 8); FileClose(handle); Global Variables functions GlobalVariableCheck() GlobalVariableDel() GlobalVariableGet() GlobalVariableSet() GlobalVariableSetOnCondition() GlobalVariablesDeleteAll() bool GlobalVariableCheck(string name) Return logical true if global variable exists, otherwise returns false. To get the detailed error information, call GetLastError() function. Parameters name - Global variable name. Sample // check variable before use if(!GlobalVariableCheck("g1")) GlobalVariableSet("g1",1); bool GlobalVariableDel(string name) Deletes global variable. If the function succeeds, the return value will be true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). Parameters name - Global variable name. Sample // deleting global variable with name "gvar_1" GlobalVariableDel("gvar_1"); double GlobalVariableGet(string name) Returns global variable value. To check function failure, check error information by calling GetLastError(). Parameters name - Global variable name. Sample double v1=GlobalVariableGet("g1"); //---- check function call result if(GetLastError()!=0) return(false); //---- continue processing datetime GlobalVariableSet(string name, double value) Sets global variable value. If it does not exist, the system creates a new variable. If the function succeeds, the return value is last access time. If the function fails, the return value is 0. To get the detailed error information, call GetLastError(). Parameters name - Global variable name. value - Numeric value to set. Sample //---- try to set new value if(GlobalVariableSet("BarsTotal",Bars)==0) return(false); //---- continue processing bool GlobalVariableSetOnCondition(string name, double value, double check_value) Sets the new value of the global variable if the current value equals to the third parameter check_value. If there is no variable at all, the function will return false and set the value of ERR_GLOBAL_VARIABLE_NOT_FOUND constant to LastError. When successfully executed, the function returns true, otherwise it does false. To receive the information about the error, call GetLastError() function. The function can be used as a semaphore for the access to common resources. Parameters name - Global variable name. value - Numeric value to set. check_value - Value to compare with the current global variable value. Sample int init() { //---- create global variable GlobalVariableSet("DATAFILE_SEM",0); //... } int start() { //---- try to lock common resource while(!IsStopped()) { //---- locking if(GlobalVariableSetOnCondition("DATAFILE_SEM",1,0)==true) break; //---- may be variable deleted? if(GetLastError()==ERR_GLOBAL_VARIABLE_NOT_FOUND) return(0); //---- sleeping Sleep(500); } //---- resource locked // ... do some work //---- unlock resource GlobalVariableSet("DATAFILE_SEM",0); } void GlobalVariablesDeleteAll() Deletes all global variables. This function never fails. Sample GlobalVariablesDeleteAll(); Math & Trig MathAbs() MathArccos() MathArcsin() MathArctan() MathCeil() MathCos() MathExp() MathFloor() MathLog() MathMax() MathMin() MathMod() MathPow() MathRand() MathRound() MathSin() MathSqrt() MathSrand() MathTan() double MathAbs(double value) Returns the absolute value (modulus) of the specified numeric value. Parameters value - Numeric value. Sample double dx=-3.141593, dy; // calc MathAbs dy=MathAbs(dx); Print("The absolute value of ",dx," is ",dy); // Output: The absolute value of -3.141593 is 3.141593 double MathArccos(double x) The MathArccos function returns the arccosine of x in the range 0 to π radians. If x is less than -1 or greater than 1, MathArccos returns an indefinite (same as a quiet NaN). Parameters x - Value between -1 and 1 arc cosine of which should be calculated. Sample double x=0.32696, y; y=asin(x); Print("Arcsine of ",x," = ",y); y=acos(x); Print("Arccosine of ",x," = ",y); //Output: Arcsine of 0.326960=0.333085 //Output: Arccosine of 0.326960=1.237711 double MathArcsin(double x) The MathArcsin function returns the arcsine of x in the range -π/2 to π/2 radians. If x is less than -1 or greater than 1, arcsine returns an indefinite (same as a quiet NaN). Parameters x - Value the arcsine of which should be calculated Sample double x=0.32696, y; y=MathArcsin(x); Print("Arcsine of ",x," = ",y); y=acos(x); Print("Arccosine of ",x," = ",y); //Output: Arcsine of 0.326960=0.333085 //Output: Arccosine of 0.326960=1.237711 double MathArctan(double x) The MathArctan returns the arctangent of x. If x is 0, MathArctan returns 0. MathArctan returns a value in the range -π/2 to π/2 radians. Parameters x - A number representing a tangent. Sample double x=-862.42, y; y=MathArctan(x); Print("Arctangent of ",x," is ",y); //Output: Arctangent of -862.42 is -1.5696 double MathCeil(double x) The MathCeil function returns a numeric value representing the smallest integer that is greater than or equal to x. Parameters x - Numeric value. Sample double y; y=MathCeil(2.8); Print("The ceil of 2.8 is ",y); y=MathCeil(-2.8); Print("The ceil of -2.8 is ",y); /*Output: The ceil of 2.8 is 3 The ceil of -2.8 is -2*/ double MathCos(double value) Returns the cosine of the specified angle. Parameters value - An angle, measured in radians. Sample double pi=3.1415926535; double x, y; x=pi/2; y=MathSin(x); Print("MathSin(",x,") = ",y); y=MathCos(x); Print("MathCos(",x,") = ",y); //Output: MathSin(1.5708)=1 // MathCos(1.5708)=0 double MathExp(double d) Returns value the number e raised to the power d. On overflow, the function returns INF (infinite) and on underflow, MathExp returns 0. Parameters d - A number specifying a power. Sample double x=2.302585093,y; y=MathExp(x); Print("MathExp(",x,") = ",y); //Output: MathExp(2.3026)=10 double MathFloor(double x) The MathFloor function returns a numeric value representing the largest integer that is less than or equal to x. Parameters x - Numeric value. Sample double y; y=MathFloor(2.8); Print("The floor of 2.8 is ",y); y=MathFloor(-2.8); Print("The floor of -2.8 is ",y); /*Output: The floor of 2.8 is 2 The floor of -2.8 is -3*/ double MathLog(double x) The MathLog functions return the logarithm of x if successful. If x is negative, these functions return an indefinite (same as a quiet NaN). If x is 0, they return INF (infinite). Parameters x - Value whose logarithm is to be found. Sample double x=9000.0,y; y=MathLog(x); Print("MathLog(",x,") = ", y); //Output: MathLog(9000)=9.10498 double MathMax(double value1, double value2) Returns maximum value of two numeric values. Parameters value1 - First numeric value. value2 - Second numeric value. Sample double result=MathMax(1.08,Bid); double MathMin(double value1, double value2) Returns minimum value of two numeric values. Parameters value1 - First numeric value. value2 - Second numeric value. Sample double result=MathMin(1.08,Ask); double MathMod(double value, double value2) Divides two numbers and returns only the remainder. Parameters value - Dividend value. value2 - Divider value. Sample double x=-10.0,y=3.0,z; z=MathMod(x,y); Print("The remainder of ",x," / ",y," is ",z); //Output: The remainder of -10 / 3 is -1 double MathPow(double base, double exponent) Returns the value of a base expression taken to a specified power. Parameters base - Base value. exponent - Exponent value. Sample double x=2.0,y=3.0,z; z=MathPow(x,y); Printf(x," to the power of ",y," is ", z); //Output: 2 to the power of 3 is 8 int MathRand() The MathRand function returns a pseudorandom integer in the range 0 to 0x7fff (32767). Use the MathSrand function to seed the pseudorandom-number generator before calling rand. Sample MathSrand(LocalTime()); // Display 10 numbers. for(int i=0;i<10;i++ ) Print("random value ", MathRand()); double MathRound(double value) Returns value rounded to the nearest integer of the specified numeric value. Parameters value - Numeric value to round. Sample double y=MathRound(2.8); Print("The round of 2.8 is ",y); y=MathRound(2.4); Print("The round of -2.4 is ",y); //Output: The round of 2.8 is 3 // The round of -2.4 is -2 double MathSin(double value) Returns the sine of the specified angle. Parameters value - An angle, measured in radians. Sample double pi=3.1415926535; double x, y; x=pi/2; y=MathSin(x); Print("MathSin(",x,") = ",y); y=MathCos(x); Print("MathCos(",x,") = ",y); //Output: MathSin(1.5708)=1 // MathCos(1.5708)=0 double MathSqrt(double x) The MathSqrt function returns the square-root of x. If x is negative, MathSqrt returns an indefinite (same as a quiet NaN). Parameters x - Positive numeric value. Sample double question=45.35, answer; answer=MathSqrt(question); if(question<0) Print("Error: MathSqrt returns ",answer," answer"); else Print("The square root of ",question," is ", answer); //Output: The square root of 45.35 is 6.73 void MathSrand(int seed) The MathSrand() function sets the starting point for generating a series of pseudorandom integers. To reinitialize the generator, use 1 as the seed argument. Any other value for seed sets the generator to a random starting point. MathRand retrieves the pseudorandom numbers that are generated. Calling MathRand before any call to MathSrand generates the same sequence as calling MathSrand with seed passed as 1. Parameters seed - Seed for random-number generation. Sample MathSrand(LocalTime()); // Display 10 numbers. for(int i=0;i<10;i++ ) Print("random value ", MathRand()); double MathTan(double x) MathTan returns the tangent of x. If x is greater than or equal to 263, or less than or equal to -263, a loss of significance in the result occurs, in which case the function returns an indefinite (same as a quiet NaN). Parameters x - Angle in radians. Sample double pi=3.1415926535; double x,y; x=MathTan(pi/4); Print("MathTan(",pi/4," = ",x); //Output: MathTan(0.7856)=1 Object functions ObjectCreate() ObjectDelete() ObjectDescription() ObjectFind() ObjectGet() ObjectGetFiboDescription() ObjectGetShiftByValue() ObjectGetValueByShift() ObjectGetVisibility() ObjectMove() ObjectName() ObjectsDeleteAll() ObjectSet() ObjectSetFiboDescription() ObjectSetText() ObjectSetVisibility() ObjectsRedraw ObjectsTotal() ObjectType() bool ObjectCreate( string name, int type, int window, datetime time1, double price1, datetime time2=0, double price2=0, datetime time3=0, double price3=0) Create object with specified name, type and initial coordinates in the specified window. Count of coordinates related from object type (1-3). If the function succeeds, the return value will be true. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). For objects with type OBJ_LABEL first coordinate ignored. To set coordinate for label use ObjectSet() function to set OBJPROP_XDISTANCE and OBJPROP_YDISTANCE properties. Note: Coordinates must be passed with both part - time and price. For example: Object OBJ_VLINE required 1 coordinate part time. But function wants also the seconds part of coordinate price. Parameters name - Unique object name. type - Object type. It can be any of the Object type enumeration values. window - Window index where object will be added. Window index must be greater or equal to 0 and less than WindowsTotal(). time1 - Time part of first point. price1 - Price part of first point. time2 - Time part of second point. price2 - Price part of second point. time3 - Time part of third point. price3 - Price part of third point. Sample // new text object if(!ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045)) { Print("error: can't create text_object! code #",GetLastError()); return(0); } // new label object if(!ObjectCreate("label_object", OBJ_LABEL, 0, 0, 0)) { Print("error: can't create label_object! code #",GetLastError()); return(0); } ObjectSet("label_object", OBJPROP_XDISTANCE, 200); ObjectSet("label_object", OBJPROP_YDISTANCE, 100); bool ObjectDelete(string name) Deletes object with specified name. If the function succeeds, the return value will be true. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). Parameters name - Deleting object name. Sample ObjectDelete("text_object"); string ObjectDescription(string name) Return object description. To get error information, call GetLastError() function. Parameters name - Object name. Sample // writing chart's object list to the file int handle, total; string obj_name,fname; // file name fname="objlist_"+Symbol(); handle=FileOpen(fname,FILE_CSV|FILE_WRITE); if(handle!=false) { total=ObjectsTotal(); for(int i=-;i<total;i++) { obj_name=ObjectName(i); FileWrite(handle,"Object "+obj_name+" description= "+ObjectDescription(obj_name)); } FileClose(handle); } int ObjectFind(string name) Return object owner's window index. If the function fails, the return value will be -1. To get the detailed error information, call GetLastError() function. Parameters name - Object name to check. Sample if(ObjectFind("line_object2")!=win_idx) return(0); double ObjectGet(string name, int index) Returns objects property value by index. To check errors, call GetLastError() function. Parameters name - Object name. index - Object property index. It can be any of the Object properties enumeration values. Sample color oldColor=ObjectGet("hline12", OBJPROP_COLOR); string ObjectGetFiboDescription(string name, int index) Function returns description of Fibonacci level. The amount of Fibonacci levels depends on the object type. The maximum amount of Fibonacci levels never exceeds 32. To get the detailed error information, call GetLastError() function. Parameters name - Object name. index - Index of the Fibonacci level. Sample #include <stdlib.mqh> ... string text; for(int i=0;i<32;i++) { text=ObjectGetFiboDescription(MyObjectName,i); //---- check. may be objects's level count less than 32 if(GetLastError()!=ERR_NO_ERROR) break; Print(MyObjectName,"level: ",i," description: ",text); } int ObjectGetShiftByValue(string name, double value) Calculates and returns bar index for the indicated price. Calculated by first and second coordinate. Applied to trendlines. To get the detailed error information, call GetLastError() function. Parameters name - Object name. value - Price value. Sample int shift=ObjectGetShiftByValue("MyTrendLine#123", 1.34); double ObjectGetValueByShift(string name, int shift) Calculates and returns price value for the indicated bar. Calculated by first and second coordinate. Applied to trendlines. To get the detailed error information, call GetLastError() function. Parameters name - Object name shift - Bar index. Sample double price=ObjectGetValueByShift("MyTrendLine#123", 11); int ObjectGetVisibility(string name) Function returns flags of the object visibility on the chart. Value can be single or combined (bitwise addition) of object visibility constants. Parameters name - Object name. Sample // is object visible on the chart? if((ObjectGetVisibility()&OBJ_PERIOD_M5)!=0 && Period()==PERIOD_M5) { // working with object } bool ObjectMove(string name, int point, datetime time1, double price1) Moves objects point on the chart. Objects can have from one to three points related to its type. If the function succeeds, the return value will be true. If the function fails, the return value will be false. To get the detailed error information, call GetLastError(). Parameters name - Object name. point - Coordinate index. time1 - New time value. price1 - New price value. Sample ObjectMove("MyTrend", 1, D'2005.02.25 12:30', 1.2345); string ObjectName(int index) Returns object name by index. Parameters index - Object index on the chart. Object index must be greater or equal to 0 and less than ObjectsTotal(). Sample int obj_total=ObjectsTotal(); string name; for(int i=0;i<obj_total;i++) { name=ObjectName(i); Print(i,"Object name is " + name); } int ObjectsDeleteAll(int window, int type=EMPTY) Removes all objects with specified type and on the specified subwindow of the chart. Returns removed objects count. Parameters window - Window index from objects will be deleted. Window index must be greater or equal to 0 and less than WindowsTotal(). type - Optional object type to delete.It can be any of the Object type enumeration values or EMPTY constant to delete all objects with any types. Sample ObjectsDeleteAll(2, OBJ_HLINE); // removes all horizontal line objects from window 3 (index 2). bool ObjectSet(string name, int index, double value) Changes named objects property with new value. If the function succeeds, the return value will be true. If the function fails, the return value will be false. To get the detailed error information, call GetLastError(). Parameters name - Object name. index - Object value index. It can be any of Object properties enumeration values. value - New value for property. Sample // moving first coord to last bar time ObjectSet("MyTrend", OBJPROP_TIME1, Time[0]); // setting second fibo level ObjectSet("MyFibo", OBJPROP_FIRSTLEVEL+1, 1.234); // setting object visibility. object will be shown only on 15 minute and 1 hour charts ObjectSet("MyObject", OBJPROP_TIMEFRAMES, OBJ_PERIOD_M15 | OBJ_PERIOD_H1); bool ObjectSetFiboDescription(string name, int index, string text) Function assigns a new description to a Fibonacci level. The amount of Fibonacci levels depends on the object type. The maximum amount of Fibonacci levels never exceeds 32. To get the detailed error information, call GetLastError() function. Parameters name - Object name. index - Index of the Fibonacci level (0-31). text - New description to be assigned to the Fibonacci level. Sample ObjectSetFiboDescription("MyFiboObject,2,"Second line"); bool ObjectSetText( string name, string text, int font_size, string font=NULL, color text_color=CLR_NONE) Sets object description. If the function succeeds, the return value will be true. If the function fails, the return value will be false. To get the detailed error information, call GetLastError() function. Parameters name - Object name. text - Some text. font_size - Font size in points. font - Font name. text_color - Text color. Sample ObjectSetText("text_object", "Hello world!", 10, "Times New Roman", Green); int ObjectSetVisibility(string name, int flag) Function sets new value to the object visibility property. Function returns previous value. Parameters name - Object name. flag - New value of the object visibility property. Value can be single or combined (bitwise addition) of object visibility constants. Sample // The object will be shown on 1-hour charts only. ObjectSetVisibility("MyObj1",OBJ_PERIOD_H1); void ObjectsRedraw() Redraws all objects on the char. Sample ObjectsRedraw(); int ObjectsTotal() Returns total count of objects on the chart. Sample int obj_total=ObjectsTotal(); string name; for(int i=0;i<obj_total;i++) { name=ObjectName(i); Print(i,"Object name is for object #",i," is " + name); } int ObjectType(string name) Returns Object type enumeration value. Parameters name - Object name. Sample if(ObjectType("line_object2")!=OBJ_HLINE) return(0); Pre-defined Variables Ask Bars Bid Close Digits High Low Open Point Time Volume double Ask Ask price (the Buyer's price). if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25) { OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point, "My order #2",3,D'2005.10.10 12:30',Red); return; } int Bars Number of bars on the chart. int counter=1; for(int i=1;i<=Bars;i++) { Print(Close[i-1]); } double Bid Bid price (the Seller's price). if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) { OrderSend("EURUSD",OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point, "My order #2",3,D'2005.10.10 12:30',Red); return(0); } double Close[] Returns the closing price of the bar being referenced. int handle, bars=Bars; handle=FileOpen("file.csv",FILE_CSV|FILE_WRITE,';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i<bars; i++) FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]); FileClose(handle); } int Digits Number of digits after decimal point for the current symbol. Print(DoubleToStr(Close[i-1], Digits)); double High[] Returns the highest price of the bar referenced. int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i<bars; i++) FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]); FileClose(handle); } double Low[] Returns the lowest price of the bar referenced. int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ";"); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i<bars; i++) FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]); FileClose(handle); } double Open[] Returns the opening price of the bar referenced. int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i<bars; i++) FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]); FileClose(handle); } double Point Point value for the current chart. OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,Red); datetime Time[] Open time of the bars. Datetime is the number of seconds elapsed from 00:00 January 1, 1970. int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i<bars; i++) FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]); FileClose(handle); } double Volume[] Returns the ticks count for the referenced bar. int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // erite data for(int i=0; i<bars; i++) FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]); FileClose(handle); } Standard Constants Applied price enumeration Drawing shape style enumeration Error codes Ichimoku Kinko Hyo modes enumeration Indicators line identifiers Market information identifiers MessageBox return codes MessageBox behavior flags Moving Average method enumeration Object properties enumeration Object type enumeration Object visibility enumeration Predefined Arrow codes enumeration Series array identifier Special constants Time frame enumeration Trade operation enumeration Uninitialize reason codes Wingdings symbols Web colors table Applied price enumeration Applied price constants. It can be any of the following values: Constant Value Description PRICE_CLOSE 0 Close price. PRICE_OPEN 1 Open price. PRICE_HIGH 2 High price. PRICE_LOW 3 Low price. PRICE_MEDIAN 4 Median price, (high+low)/2. PRICE_TYPICAL 5 Typical price, (high+low+close)/3. PRICE_WEIGHTED 6 Weighted close price, (high+low+close+close)/4. Drawing shape style enumeration Drawing shape style enumeration for SetIndexStyle() function. It can be any of the following values: Constant Value Description DRAW_LINE 0 Drawing line. DRAW_SECTION 1 Drawing sections. DRAW_HISTOGRAM 2 Drawing histogram. DRAW_ARROW 3 Drawing arrows (symbols). DRAW_NONE 12 No drawing. Drawing style. Valid when width=1. It can be any of the following values: Constant Value Description STYLE_SOLID 0 The pen is solid. STYLE_DASH 1 The pen is dashed. STYLE_DOT 2 The pen is dotted. STYLE_DASHDOT 3 The pen has alternating dashes and dots. STYLE_DASHDOTDOT 4 The pen has alternating dashes and double dots. Error codes The GetLastError() function return codes. Error code constants defined at stderror.mqh file. To print text messages use ErrorDescription() function defined at stdlib.mqh file. #include <stdlib.mqh> void SendMyMessage(string text) { int check; SendMail("some subject", text); check=GetLastError(); if(check!=ERR_NO_MQLERROR) Print("Cannot send message, error: ",ErrorDescription(check)); } Error codes returned from trade server. Constant Value Description ERR_NO_ERROR 0 No error returned. ERR_NO_RESULT 1 No error returned, but the result is unknown. ERR_COMMON_ERROR 2 Common error. ERR_INVALID_TRADE_PARAMETERS 3 Invalid trade parameters. ERR_SERVER_BUSY 4 Trade server is busy. ERR_OLD_VERSION 5 Old version of the client terminal. ERR_NO_CONNECTION 6 No connection with trade server. ERR_NOT_ENOUGH_RIGHTS 7 Not enough rights. ERR_TOO_FREQUENT_REQUESTS 8 Too frequent requests. ERR_MALFUNCTIONAL_TRADE 9 Malfunctional trade operation. ERR_ACCOUNT_DISABLED 64 Account disabled. ERR_INVALID_ACCOUNT 65 Invalid account. ERR_TRADE_TIMEOUT 128 Trade timeout. ERR_INVALID_PRICE 129 Invalid price. ERR_INVALID_STOPS 130 Invalid stops. ERR_INVALID_TRADE_VOLUME 131 Invalid trade volume. ERR_MARKET_CLOSED 132 Market is closed. ERR_TRADE_DISABLED 133 Trade is disabled. ERR_NOT_ENOUGH_MONEY 134 Not enough money. ERR_PRICE_CHANGED 135 Price changed. ERR_OFF_QUOTES 136 Off quotes. ERR_BROKER_BUSY 137 Broker is busy. ERR_REQUOTE 138 Requote. ERR_ORDER_LOCKED 139 Order is locked. ERR_LONG_POSITIONS_ONLY_ALLOWED 140 Long positions only allowed. ERR_TOO_MANY_REQUESTS 141 Too many requests. ERR_TRADE_MODIFY_DENIED 145 Modification denied because order too close to market. ERR_TRADE_CONTEXT_BUSY 146 Trade context is busy. MQL4 run time error codes Constant Value Description ERR_NO_MQLERROR 4000 No error. ERR_WRONG_FUNCTION_POINTER 4001 Wrong function pointer. ERR_ARRAY_INDEX_OUT_OF_RANGE 4002 Array index is out of range. ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK 4003 No memory for function call stack. ERR_RECURSIVE_STACK_OVERFLOW 4004 Recursive stack overflow. ERR_NOT_ENOUGH_STACK_FOR_PARAMETER 4005 Not enough stack for parameter. ERR_NO_MEMORY_FOR_PARAMETER_STRING 4006 No memory for parameter string. ERR_NO_MEMORY_FOR_TEMP_STRING 4007 No memory for temp string. ERR_NOT_INITIALIZED_STRING 4008 Not initialized string. ERR_NOT_INITIALIZED_ARRAYSTRING 4009 Not initialized string in array. ERR_NO_MEMORY_FOR_ARRAYSTRING 4010 No memory for array string. ERR_TOO_LONG_STRING 4011 Too long string. ERR_REMAINDER_FROM_ZERO_DIVIDE 4012 Remainder from zero divide. ERR_ZERO_DIVIDE 4013 Zero divide. ERR_UNKNOWN_COMMAND 4014 Unknown command. ERR_WRONG_JUMP 4015 Wrong jump (never generated error). ERR_NOT_INITIALIZED_ARRAY 4016 Not initialized array. ERR_DLL_CALLS_NOT_ALLOWED 4017 DLL calls are not allowed. ERR_CANNOT_LOAD_LIBRARY 4018 Cannot load library. ERR_CANNOT_CALL_FUNCTION 4019 Cannot call function. ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED 4020 Expert function calls are not allowed. ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING 4021 Not enough memory for temp string returned from function. ERR_SYSTEM_BUSY 4022 System is busy (never generated error). ERR_INVALID_FUNCTION_PARAMETERS_COUNT 4050 Invalid function parameters count. ERR_INVALID_FUNCTION_PARAMETER_VALUE 4051 Invalid function parameter value. ERR_STRING_FUNCTION_INTERNAL_ERROR 4052 String function internal error. ERR_SOME_ARRAY_ERROR 4053 Some array error. ERR_INCORRECT_SERIES_ARRAY_USING 4054 Incorrect series array using. ERR_CUSTOM_INDICATOR_ERROR 4055 Custom indicator error. ERR_INCOMPATIBLE_ARRAYS 4056 Arrays are incompatible. ERR_GLOBAL_VARIABLES_PROCESSING_ERROR 4057 Global variables processing error. ERR_GLOBAL_VARIABLE_NOT_FOUND 4058 Global variable not found. ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE 4059 Function is not allowed in testing mode. ERR_FUNCTION_NOT_CONFIRMED 4060 Function is not confirmed. ERR_SEND_MAIL_ERROR 4061 Send mail error. ERR_STRING_PARAMETER_EXPECTED 4062 String parameter expected. ERR_INTEGER_PARAMETER_EXPECTED 4063 Integer parameter expected. ERR_DOUBLE_PARAMETER_EXPECTED 4064 Double parameter expected. ERR_ARRAY_AS_PARAMETER_EXPECTED 4065 Array as parameter expected. ERR_HISTORY_WILL_UPDATED 4066 Requested history data in updating state. ERR_END_OF_FILE 4099 End of file. ERR_SOME_FILE_ERROR 4100 Some file error. ERR_WRONG_FILE_NAME 4101 Wrong file name. ERR_TOO_MANY_OPENED_FILES 4102 Too many opened files. ERR_CANNOT_OPEN_FILE 4103 Cannot open file. Ichimoku Kinko Hyo modes enumeration Ichimoku Kinko Hyo source of data. Used in iIchimoku() indicators. It can be one of the following values: Constant Value Description MODE_TENKANSEN 1 Tenkan-sen. MODE_KIJUNSEN 2 Kijun-sen. MODE_SENKOUSPANA 3 Senkou Span A. MODE_SENKOUSPANB 4 Senkou Span B. MODE_CHINKOUSPAN 5 Chinkou Span. Indicators line identifiers Indicator line identifiers used in iMACD(), iRVI() and iStochastic() indicators. It can be one of the following values: Constant Value Description MODE_MAIN 0 Base indicator line. MODE_SIGNAL 1 Signal line. Indicator line identifiers used in iADX() indicator. Constant Value Description MODE_MAIN 0 Base indicator line. MODE_PLUSDI 1 +DI indicator line. MODE_MINUSDI 2 -DI indicator line. Indicator line identifiers used in iBands(), iEnvelopes(), iEnvelopesOnArray(), iFractals() and iGator() indicators. Constant Value Description MODE_UPPER 1 Upper line. MODE_LOWER 2 Lower line. Market information identifiers Market information identifiers, used with MarketInfo() function. It can be any of the following values: Constant Value Description MODE_LOW 1 Low day price. MODE_HIGH 2 High day price. MODE_TIME 5 The last incoming quotation time. MODE_BID 9 Last incoming bid price. MODE_ASK 10 Last incoming ask price. MODE_POINT 11 Point size. MODE_DIGITS 12 Digits after decimal point. MODE_SPREAD 13 Spread value in points. MODE_STOPLEVEL 14 Stop level in points. MODE_LOTSIZE 15 Lot size in the base currency. MODE_TICKVALUE 16 Tick value. MODE_TICKSIZE 17 Tick size. MODE_SWAPLONG 18 Swap of the long position. MODE_SWAPSHORT 19 Swap of the short position. MODE_STARTING 20 Market starting date (usually used for future markets). MODE_EXPIRATION 21 Market expiration date (usually used for future markets). MODE_TRADEALLOWED 22 Trade is allowed for the symbol. MODE_MINLOT 22 The minimum lot size in points. MODE_LOTSTEP 22 Step for changing lots in points. MessageBox return codes The MessageBox() function return codes. If a message box has a Cancel button, the function returns the IDCANCEL value if either the ESC key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing ESC has no effect. Note: MessageBox return codes defined in the WinUser32.mqh file Constant Value Description IDOK 1 OK button was selected. IDCANCEL 2 Cancel button was selected. IDABORT 3 Abort button was selected. IDRETRY 4 Retry button was selected. IDIGNORE 5 Ignore button was selected. IDYES 6 Yes button was selected. IDNO 7 No button was selected. IDTRYAGAIN 10 Try Again button was selected. IDCONTINUE 11 Continue button was selected. MessageBox behavior flags The MessageBox function flags specify the contents and behavior of the dialog box. This value can be a combination of flags from the following groups of flags. Note: MessageBox return codes defined in the WinUser32.mqh file To indicate the buttons displayed in the message box, specify one of the following values. Constant Value Description MB_OK 0x00000000 The message box contains one push button: OK. This is the default. MB_OKCANCEL 0x00000001 The message box contains two push buttons: OK and Cancel. MB_ABORTRETRYIGNORE 0x00000002 The message box contains three push buttons: Abort, Retry, and Ignore. MB_YESNOCANCEL 0x00000003 The message box contains three push buttons: Yes, No, and Cancel. MB_YESNO 0x00000004 The message box contains two push buttons: Yes and No. MB_RETRYCANCEL 0x00000005 The message box contains two push buttons: Retry and Cancel. MB_CANCELTRYCONTINUE 0x00000006 Windows 2000: The message box contains three push buttons: Cancel, Try Again, Continue. Use this message box type instead of MB_ABORTRETRYIGNORE. To display an icon in the message box, specify one of the following values. Constant Value Description MB_ICONSTOP, MB_ICONERROR, MB_ICONHAND 0x00000010 A stop-sign icon appears in the message box. MB_ICONQUESTION 0x00000020 A question-mark icon appears in the message box. MB_ICONEXCLAMATION, MB_ICONWARNING 0x00000030 An exclamation-point icon appears in the message box. MB_ICONINFORMATION, MB_ICONASTERISK 0x00000040 An icon consisting of a lowercase letter i in a circle appears in the message box. To indicate the default button, specify one of the following values. Constant Value Description MB_DEFBUTTON1 0x00000000 The first button is the default button. MB_DEFBUTTON1 is the default unless MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 is specified. MB_DEFBUTTON2 0x00000100 The second button is the default button. MB_DEFBUTTON3 0x00000200 The third button is the default button. MB_DEFBUTTON4 0x00000300 The fourth button is the default button. Moving Average method enumeration Moving Average calculation method. used with iAlligator(), iEnvelopes(), iEnvelopesOnArray, iForce(), iGator(), iMA(), iMAOnArray(), iStdDev(), iStdDevOnArray(), iStochastic() indicators. It can be any of the following values: Constant Value Description MODE_SMA 0 Simple moving average, MODE_EMA 1 Exponential moving average, MODE_SMMA 2 Smoothed moving average, MODE_LWMA 3 Linear weighted moving average. Object properties enumeration Object value index used with ObjectGet() and ObjectSet() functions. It can be any of the following values: Constant Value Description OBJPROP_TIME1 0 Datetime value to set/get first coordinate time part. OBJPROP_PRICE1 1 Double value to set/get first coordinate price part. OBJPROP_TIME2 2 Datetime value to set/get second coordinate time part. OBJPROP_PRICE2 3 Double value to set/get second coordinate price part. OBJPROP_TIME3 4 Datetime value to set/get third coordinate time part. OBJPROP_PRICE3 5 Double value to set/get third coordinate price part. OBJPROP_COLOR 6 Color value to set/get object color. OBJPROP_STYLE 7 Value is one of STYLE_SOLID, STYLE_DASH, STYLE_DOT, STYLE_DASHDOT, STYLE_DASHDOTDOT constants to set/get object line style. OBJPROP_WIDTH 8 Integer value to set/get object line width. Can be from 1 to 5. OBJPROP_BACK 9 Boolean value to set/get background drawing flag for object. OBJPROP_RAY 10 Boolean value to set/get ray flag of object. OBJPROP_ELLIPSE 11 Boolean value to set/get ellipse flag for fibo arcs. OBJPROP_SCALE 12 Double value to set/get scale object property. OBJPROP_ANGLE 13 Double value to set/get angle object property in degrees. OBJPROP_ARROWCODE 14 Integer value or arrow enumeration to set/get arrow code object property. OBJPROP_TIMEFRAMES 15 Value can be one or combination (bitwise addition) of object visibility constants to set/get timeframe object property. OBJPROP_DEVIATION 16 Double value to set/get deviation property for Standard deviation objects. OBJPROP_FONTSIZE 100 Integer value to set/get font size for text objects. OBJPROP_CORNER 101 Integer value to set/get anchor corner property for label objects. Must be from 0-3. OBJPROP_XDISTANCE 102 Integer value to set/get anchor X distance object property in pixels. OBJPROP_YDISTANCE 103 Integer value is to set/get anchor Y distance object property in pixels. OBJPROP_FIBOLEVELS 200 Integer value to set/get Fibonacci object level count. Can be from 0 to 32. OBJPROP_FIRSTLEVEL+n 210 Fibonacci object level index, where n is level index to set/get. Can be from 0 to 31. Object type enumeration Object type identifier constants used with ObjectCreate(), ObjectsDeleteAll() and ObjectType() functions. It can be any of the following values: Objects can have 1-3 coordinates related to type. Constant Value Description OBJ_VLINE 0 Vertical line. Uses time part of first coordinate. OBJ_HLINE 1 Horizontal line. Uses price part of first coordinate. OBJ_TREND 2 Trend line. Uses 2 coordinates. OBJ_TRENDBYANGLE 3 Trend by angle. Uses 1 coordinate. To set angle of line use ObjectSet() function. OBJ_REGRESSION 4 Regression. Uses time parts of first two coordinates. OBJ_CHANNEL 5 Channel. Uses 3 coordinates. OBJ_STDDEVCHANNEL 6 Standard deviation channel. Uses time parts of first two coordinates. OBJ_GANNLINE 7 Gann line. Uses 2 coordinate, but price part of second coordinate ignored. OBJ_GANNFAN 8 Gann fan. Uses 2 coordinate, but price part of second coordinate ignored. OBJ_GANNGRID 9 Gann grid. Uses 2 coordinate, but price part of second coordinate ignored. OBJ_FIBO 10 Fibonacci retracement. Uses 2 coordinates. OBJ_FIBOTIMES 11 Fibonacci time zones. Uses 2 coordinates. OBJ_FIBOFAN 12 Fibonacci fan. Uses 2 coordinates. OBJ_FIBOARC 13 Fibonacci arcs. Uses 2 coordinates. OBJ_EXPANSION 14 Fibonacci expansions. Uses 3 coordinates. OBJ_FIBOCHANNEL 15 Fibonacci channel. Uses 3 coordinates. OBJ_RECTANGLE 16 Rectangle. Uses 2 coordinates. OBJ_TRIANGLE 17 Triangle. Uses 3 coordinates. OBJ_ELLIPSE 18 Ellipse. Uses 2 coordinates. OBJ_PITCHFORK 19 Andrews pitchfork. Uses 3 coordinates. OBJ_CYCLES 20 Cycles. Uses 2 coordinates. OBJ_TEXT 21 Text. Uses 1 coordinate. OBJ_ARROW 22 Arrows. Uses 1 coordinate. OBJ_LABEL 23 Text label. Uses 1 coordinate in pixels. Object visibility enumeration Time frames where object may be shown. Used in ObjectSet() function to set OBJPROP_TIMEFRAMES property. Constant Value Description OBJ_PERIOD_M1 0x0001 Object shown is only on 1-minute charts. OBJ_PERIOD_M5 0x0002 Object shown is only on 5-minute charts. OBJ_PERIOD_M15 0x0004 Object shown is only on 15-minute charts. OBJ_PERIOD_M30 0x0008 Object shown is only on 30-minute charts. OBJ_PERIOD_H1 0x0010 Object shown is only on 1-hour charts. OBJ_PERIOD_H4 0x0020 Object shown is only on 4-hour charts. OBJ_PERIOD_D1 0x0040 Object shown is only on daily charts. OBJ_PERIOD_W1 0x0080 Object shown is only on weekly charts. OBJ_PERIOD_MN1 0x0100 Object shown is only on monthly charts. OBJ_ALL_PERIODS 0x01FF Object shown is on all timeframes. NULL 0 Object shown is on all timeframes. EMPTY -1 Hidden object on all timeframes. Predefined Arrow codes enumeration Predefined Arrow codes enumeration. Arrows code constants. It can be one of the following values: Constant Value Description SYMBOL_THUMBSUP 67 Thumb up symbol (`). SYMBOL_THUMBSDOWN 68 Thumb down symbol (·). SYMBOL_ARROWUP 241 Arrow up symbol (^). SYMBOL_ARROWDOWN 242 Arrow down symbol (-). SYMBOL_STOPSIGN 251 Stop sign symbol (×). SYMBOL_CHECKSIGN 252 Check sign symbol (-). Special Arrow codes that exactly points to price and time. It can be one of the following values: Constant Value Description 1 Upwards arrow with tip rightwards (↱). 2 Downwards arrow with tip rightwards (↳). 3 Left pointing triangle (◄). 4 En Dash symbol (–). SYMBOL_LEFTPRICE 5 Left sided price label. SYMBOL_RIGHTPRICE 6 Right sided price label. Series array identifier Series array identifier used with ArrayCopySeries(), Highest() and Lowest() functions. It can be any of the following values: Constant Value Description MODE_OPEN 0 Open price. MODE_LOW 1 Low price. MODE_HIGH 2 High price. MODE_CLOSE 3 Close price. MODE_VOLUME 4 Volume, used in Lowest() and Highest() functions. MODE_TIME 5 Bar open time, used in ArrayCopySeries() function. Special constants Special constants used to indicate parameters and variables states. It can be one of the following values: Constant value Description NULL 0 Indicates empty state of the string. EMPTY -1 Indicates empty state of the parameter. EMPTY_VALUE 0x7FFFFFFF Default custom indicator empty value. CLR_NONE 0xFFFFFFFF Indicates empty state of colors. WHOLE_ARRAY 0 Used with array functions. Indicates that all array elements will be processed. Time frame enumeration Time frame on the chart. It can be any of the following values: Constant Value Description PERIOD_M1 1 1 minute. PERIOD_M5 5 5 minutes. PERIOD_M15 15 15 minutes. PERIOD_M30 30 30 minutes. PERIOD_H1 60 1 hour. PERIOD_H4 240 4 hour. PERIOD_D1 1440 Daily. PERIOD_W1 10080 Weekly. PERIOD_MN1 43200 Monthly. 0 (zero) 0 Time frame used on the chart. Trade operation enumeration Operation type for the OrderSend() function. It can be any of the following values: Constant Value Description OP_BUY 0 Buying position. OP_SELL 1 Selling position. OP_BUYLIMIT 2 Buy limit pending position. OP_SELLLIMIT 3 Sell limit pending position. OP_BUYSTOP 4 Buy stop pending position. OP_SELLSTOP 5 Sell stop pending position. Uninitialize reason codes Uninitialize reason codes returned by UninitializeReason() function. It can be any one of the following values: Constant Value Description REASON_REMOVE 1 Expert removed from chart. REASON_RECOMPILE 2 Expert recompiled. REASON_CHARTCHANGE 3 symbol or timeframe changed on the chart. REASON_CHARTCLOSE 4 Chart closed. REASON_PARAMETERS 5 Inputs parameters was changed by user. REASON_ACCOUNT 6 Other account activated. Wingdings symbols Wingdings font symbols used with Arrow objects. 32 . 33 > 34 - 35 36 ~ 37 ¡ 38 39 W 40 ³ 41 ¯ 42 ¯ 43 - 44 - 45 46 47 ´ 48 . 49 ± 50 ¯ 51 ¯ 52 ± 53 : 54 l 55 ´ 56 ¯ 57 ¯ 58 ± 59 ¯ 60 U 61 · 62 > 63 64 · 65 ` 66 ` 67 · 68 ¯ 69 70 - 71 · 72 ¨ 73 © 74 © 75 ® 76 e 77 ª 78 ¦ 79 ¯ 80 ¬ 81 ^ 82 e 83 + 84 ± 85 V 86 1 87 + 88 4 89 L 90 w 91 6 92 + 93 ° 94 · 95 T 96 C 97 ¹ 98 H 99 - 10 0 " 10 1 × 10 2 ¹ 10 3 ´ 10 4 ) 10 5 m 10 6 & 10 7 ¤ 10 8 O 10 9 Þ 11 0 E 11 1 O 11 2 Q 11 3 Ò 11 4 · 11 5 4 11 6 4 11 7 + 11 8 º 11 9 E 12 0 E 12 1 = 12 2 · 12 3 = 12 4 " 12 5 " 12 6 D 12 7 © 12 8 C 12 9 C 13 0 C 13 1 C 13 2 … 13 3 © 13 4 C 13 5 ® 13 6 ‰ 13 7 1 13 8 O 13 9 O 14 0 O 14 1 O 14 2 O 14 3 O 14 4 ‘ 14 5 ’ 14 6 “ 14 7 ” 14 8 G 14 9 – 15 0 — 15 1 s 15 2 c 15 3 ¬ 15 4 < 15 5 - 15 6 w 15 7 · 15 8 º 15 9 · 16 0 O 16 1 O 16 2 O 16 3 O 16 4 © 16 5 O 16 6 · 16 7 E 16 8 - 16 9 + 17 0 * 17 1 * 17 2 - 17 3 4 17 4 ^ 17 5 = 17 6 = 17 7 · 17 8 ¯ 17 9 · 18 0 O 18 1 ´ 18 2 18 3 18 4 18 5 18 6 18 7 18 8 18 9 · 19 0 · 19 1 · 19 2 19 3 19 4 ¬ 19 5 + 19 6 ´ 19 7 ó 19 8 ^ 19 9 ÷ 20 0 ´ 20 1 ¯ 20 2 = 20 3 Q 20 4 Ø 20 5 T 20 6 R 20 7 _ 20 8 l 20 9 _ 21 0 Ø 21 1 7 21 2 ^ 21 3 E 21 4 ¬ 21 5 × 21 6 * 21 7 · 21 8 C 21 9 C 22 0 O 22 1 O 22 2 ÷ 22 3 ¬ 22 4 ^ 22 5 + 22 6 N 22 7 7 22 8 × 22 9 × 23 0 + 23 1 ¬ 23 2 + 23 3 + 23 4 R 23 5 7 23 6 v 23 7 N 23 8 ¯ 23 9 = 24 0 ^ 24 1 - 24 2 ¯ 24 3 ^ 24 4 ' 24 5 ¯ 24 6 u 24 7 ^ 24 8 · 24 9 - 25 0 × 25 1 - 25 2 E 25 3 E 25 4 ¼ 25 5 Web colors table Black DarkGreen DarkSlateGray Olive Green Teal Navy Purple Maroon Indigo MidnightBlue DarkBlue DarkOliveGreen SaddleBrown ForestGreen OliveDrab SeaGreen DarkGoldenrod DarkSlateBlue Sienna MediumBlue Brown DarkTurquoise DimGray LightSeaGreen DarkViolet FireBrick MediumVioletRed MediumSeaGreen Chocolate Crimson SteelBlue Goldenrod MediumSpringGreen LawnGreen CadetBlue DarkOrchid YellowGreen LimeGreen OrangeRed DarkOrange Orange Gold Yellow Chartreuse Lime SpringGreen Aqua DeepSkyBlue Blue Magenta Red Gray SlateGray Peru BlueViolet LightSlateGray DeepPink MediumTurquoise DodgerBlue Turquoise RoyalBlue SlateBlue DarkKhaki IndianRed MediumOrchid GreenYellow MediumAquamarine DarkSeaGreen Tomato RosyBrown Orchid MediumPurple PaleVioletRed Coral CornflowerBlue DarkGray SandyBrown MediumSlateBlue Tan DarkSalmon BurlyWood HotPink Salmon Violet LightCoral SkyBlue LightSalmon Plum Khaki LightGreen Aquamarine Silver LightSkyBlue LightSteelBlue LightBlue PaleGreen Thistle PowderBlue PaleGoldenrod PaleTurquoise LightGray Wheat NavajoWhite Moccasin LightPink Gainsboro PeachPuff Pink Bisque LightGoldenRod BlanchedAlmond LemonChiffon Beige AntiqueWhite PapayaWhip Cornsilk LightYellow LightCyan Linen Lavender MistyRose OldLace WhiteSmoke Seashell Ivory Honeydew AliceBlue LavenderBlush MintCream Snow White String functions StringConcatenate() StringFind() StringGetChar() StringLen() StringSetChar() StringSubstr() StringTrimLeft() StringTrimRight() string StringConcatenate(... ) Writes data to the string and returns it. Parameters can be of any type. Arrays cannot be passed to the StringConcatenate() function. Arrays should be printed elementwise. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. StringConcatenate() function work faster than concatenating strings by + operator. See also: Print(), Alert() and Comment() functions. Parameters ... - Any values, separated by commas. Sample string text; text=StringConcatenate("Account free margin is ", AccountFreeMargin(), "Current time is ", TimeToStr(CurTime())); // slow text="Account free margin is " + AccountFreeMargin() + "Current time is " + TimeToStr(CurTime()) Print(text); int StringFind(string text, string matched_text, int start=0) Scans this string for the first match of a substring. Parameters text - String to search for. matched_text - String to search for. start - Starting index in the string. Sample string text="The quick brown dog jumps over the lazy fox"; int index=StringFind(text, "dog jumps", 0); if(index!=16) Print("oops!"); int StringGetChar(string text, int pos) Returns character (code) from specified position in the string. Parameters text - String where character will be retrieved. pos - Char zero based position in the string. Sample int char_code=StringGetChar("abcdefgh", 3); // char code 'c' is 99 int StringLen(string text) Returns character count of a string. Parameters text - String to calculate length. Sample string str="some text"; if(StringLen(str)<5) return(0); string StringSetChar(string text, int pos, int value) Returns string copy with changed character at the indicated position with new value. Parameters text - String where character will be changed. pos - Zero based character position in the string. Can be from 0 to StringLen()-1. value - New char ASCII code. Sample string str="abcdefgh"; string str1=StringSetChar(str, 3, 'D'); // str1 is "abcDefgh" string StringSubstr(string text, int start, int count=EMPTY) Extracts a substring from text string, starting at position (zero-based). The function returns a copy of the extracted substring if possible, otherwise returns empty string. Parameters text - String from substring will be extracted. start - Substring starting index count - Character count. Sample string text="The quick brown dog jumps over the lazy fox"; string substr=StringSubstr(text, 4, 5); // subtracted string is "quick" word string StringTrimLeft(string text) Call the function to trim leading white space characters from the string. StringTrimLeft removes new line, space, and tab characters. The function returns a copy of the trimmed string if possible, otherwise returns empty string. Returns new string with changes. Parameters text - String to trim left. Sample string str1=" Hello world "; string str2=StringTrimLeft(str); // after trimming the str2 variable will be "Hello World " string StringTrimRight(string text) Call the function to trim leading white space characters from the string. StringTrimRight removes new line, space, and tab characters. The function returns a copy of the trimmed string if possible, otherwise return empty string. Parameters text - String to trim right. Sample string str1=" Hello world "; string str2=StringTrimRight(str); // after trimming the str2 variable will be " Hello World" Technical Indicator calls Accelerator Oscillator - iAC() Accumulation/Distribution - iAD() Alligator - iAlligator() Average Directional Movement Index - iADX() Average True Range - iATR() Awesome Oscillator - iAO() Bears Power - iBearsPower() Bollinger Bands - iBands() Bollinger Bands on buffer - iBandsOnArray() Bulls Power - iBullsPower() Commodity Channel Index - iCCI() Commodity Channel Index on buffer - iCCIOnArray() Custom Indicator - iCustom() DeMarker - iDeMarker() Envelopes - iEnvelopes() Envelopes on buffer - iEnvelopesOnArray() Force Index - iForce() Fractals - iFractals() Gator Oscillator - iGator() Ichimoku Kinko Hyo - iIchimoku() Market Facilitation Index (Bill Williams) - iBWMFI() Momentum - iMomentum() Momentum on buffer - iMomentumOnArray() Money Flow Index - iMFI() Moving Average - iMA() Moving Average on buffer - iMAOnArray() Moving Average of Oscillator - iOsMA() Moving Averages Convergence/Divergence - iMACD() On Balance Volume - iOBV() Parabolic SAR - iSAR() Relative Strength Index - iRSI() Relative Strength Index on buffer - iRSIOnArray() Relative Vigor Index - iRVI() Standard Deviation - iStdDev() Standard Deviation on buffer - iStdDevOnArray() Stochastic Oscillator - iStochastic() William's Percent Range - iWPR() iBars() iBarShift() iClose() iHigh() iLow() iOpen() iTime() iVolume() Highest() Lowest() double iAC(string symbol, int timeframe, int shift) Calculates the Bill Williams' Accelerator/Decelerator oscillator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double result=iAC(NULL, 0, 1); double iAD(string symbol, int timeframe, int shift) Calculates the Accumulation/Distribution indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double result=iAD(NULL, 0, 1); double iAlligator( string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price, int mode, int shift) Calculates the Bill Williams' Alligator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. jaw_period - Jaw period. jaw_shift - Jaw line shift. teeth_period - Teeth period. teeth_shift - Teeth line shift. lips_period - Lips period. lips_shift - Lips line shift. ma_method - MA method. It can be any of Moving Average method enumeration value. applied_price - Applied price. It can be any of Applied price enumeration values. mode - Source of data. It can be any of the following values: MODE_GATORJAW - Gator Jaw (blue) balance line, MODE_GATORTEETH - Gator Teeth (red) balance line, MODE_GATORLIPS - Gator Lips (green) balance line. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double jaw_val=iAlligator(NULl, 0, 13, 8, 8, 5, 5, 3, MODE_SMMA, PRICE_MEDIAN, MODE_GATORJAW, 1); double iADX( string symbol, int timeframe, int period, int applied_price, int mode, int shift) Calculates the Movement directional index and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. applied_price - Applied price. It can be any of Applied price enumeration values. mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iADX(NULL,0,14,PRICE_HIGH,MODE_MAIN,0)>iADX(NULL,0,14,PRICE_HIGH,MODE_PLUSDI,0)) return(0); double iATR(string symbol, int timeframe, int period, int shift) Calculates the Indicator of the average true range and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iATR(NULL,0,12,0)>iATR(NULL,0,20,0)) return(0); double iAO(string symbol, int timeframe, int shift) Calculates the Bill Williams' Awesome oscillator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iAO(NULL, 0, 2); double iBearsPower( string symbol, int timeframe, int period, int applied_price, int shift) Calculates the Bears Power indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iBearsPower(NULL, 0, 13,PRICE_CLOSE,0); double iBands( string symbol, int timeframe, int period, int deviation, int bands_shift, int applied_price, int mode, int shift) Calculates the Bollinger bands indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. deviation - Deviation. bands_shift - Bands shift. applied_price - Applied price. It can be any of Applied price enumeration values. mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iBands(NULL,0,20,2,0,PRICE_LOW,MODE_LOWER,0)>Low[0]) return(0); double iBandsOnArray( double array[], int total, int period, double deviation, int bands_shift, int mode, int shift) Calculates the Bollinger bands indicator and returns its value. Parameters array[] - Array with data. total - The number of items to be counted. period - Number of periods for calculation. deviation - Deviation. bands_shift - Bands shift. mode - Series array identifier. It can be any of the Series array identifier enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iBands(ExtBuffer,total,2,0,MODE_LOWER,0)>Low[0]) return(0); double iBullsPower( string symbol, int timeframe, int period, int applied_price, int shift) Calculates the Bulls Power indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iBullsPower(NULL, 0, 13,PRICE_CLOSE,0); double iCCI(string symbol, int timeframe, int period, int applied_price, int shift) Calculates the Commodity channel index and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iCCI(NULL,0,12,0)>iCCI(NULL,0,20,0)) return(0); double iCCIOnArray(double array[], int total, int period, int shift) Calculates the Commodity channel index and returns its value. Parameters array[] - Array with data. total - The number of items to be counted. period - Number of periods for calculation. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iCCIOnArray(ExtBuffer,total,12,0)>iCCI(NULL,0,20,PRICE_OPEN, 0)) return(0); double iCustom(string symbol, int timeframe, string name, ... , int mode, int shift) Calculates the Custom indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. name - Custom indicator compiled program name. ... - Parameters set (if needed). mode - Line index. Can be from 0 to 7. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iCustom(NULL, 0, "SampleInd",13,1,0); double iDeMarker(string symbol, int timeframe, int period, int shift) Calculates the DeMarker indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iDeMarker(NULL, 0, 13, 1); double iEnvelopes( string symbol, int timeframe, int ma_period, int ma_method, int ma_shift, int applied_price, double deviation, int mode, int shift) Calculates the Envelopes indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. ma_period - Number of periods for calculation. ma_method - MA method. It can be any of Moving Average method enumeration value. ma_shift - MA shift. Indicator line offset relate to the chart by timeframe. applied_price - Applied price. It can be any of Applied price enumeration values. deviation - Deviation. mode - Indicator line array index. It can be any of Indicators line identifiers enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iEnvelopes(NULL, 0, 13,MODE_SMA,10,PRICE_CLOSE,0.2,MODE_UPPER,0); double iEnvelopesOnArray( double array[], int total, int ma_period, int ma_method, int ma_shift, double deviation, int mode, int shift) Calculates the Envelopes indicator counted on buffer and returns its value. Parameters array[] - Array with data. total - The number of items to be counted. ma_period - Number of periods for calculation. ma_method - MA method. It can be any of Moving Average method enumeration value. ma_shift - MA shift. Indicator line offset relate to the chart by timeframe. deviation - Deviation. mode - Indicator line array index. It can be any of Indicators line identifiers enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iEnvelopesOnArray(ExtBuffer, 0, 13, MODE_SMA, 0.2, MODE_UPPER,0 ); double iForce( string symbol, int timeframe, int period, int ma_method, int applied_price, int shift) Calculates the Force index and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. ma_method - MA method. It can be any of Moving Average method enumeration value. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iForce(NULL, 0, 13,MODE_SMA,PRICE_CLOSE,0); double iFractals(string symbol, int timeframe, int mode, int shift) Calculates the Fractals and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iFractals(NULL, 0, MODE_UPPER,0); double iGator( string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price, int mode, int shift) Calculates the Gator Oscillator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. jaw_period - Jaw period. jaw_shift - Jaw line shift. teeth_period - Teeth period. teeth_shift - Teeth line shift. lips_period - Lips period. lips_shift - Lips line shift. ma_method - MA method. It can be any of Moving Average method enumeration value. applied_price - Applied price. It can be any of Applied price enumeration values. mode - Indicator line array index. It can be any of Indicators line identifiers enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double jaw_val=iGator(NULL, 0, 13, 8, 8, 5, 5, 3, MODE_SMMA, PRICE_MEDIAN, MODE_UPPER, 1); double iIchimoku( string symbol, int timeframe, int tenkan_sen, int kijun_sen, int senkou_span_b, int mode, int shift) Calculates the Ichimoku Kinko Hyo and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. tenkan_sen - Tenkan Sen. kijun_sen - Kijun Sen. senkou_span_b - Senkou SpanB. mode - Source of data. It can be one of the Ichimoku Kinko Hyo mode enumeration. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double tenkan_sen=iIchimoku(NULL, 0, 9, 26, 52, MODE_TENKANSEN, 1); double iBWMFI(string symbol, int timeframe, int shift) Calculates the Bill Williams Market Facilitation index and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iBWMFI(NULL, 0, 0); double iMomentum( string symbol, int timeframe, int period, int applied_price, int shift) Calculates the Momentum indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator.NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iMomentum(NULL,0,12,PRICE_CLOSE,0)>iMomentum(NULL,0,20,PRICE_CLOSE,0)) return(0); double iMomentumOnArray(double array[], int total, int period, int shift) Calculates the Momentum indicator counted on buffer and returns its value. Parameters array[] - Array with data. total - The number of items to be counted. period - Number of periods for calculation. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iMomentumOnArray(mybuffer,100,12,0)>iMomentumOnArray(mubuffer,100,20,0)) return(0); double iMFI(string symbol, int timeframe, int period, int shift) Calculates the Money flow index and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iMFI(NULL,0,14,0)>iMFI(NULL,0,14,1)) return(0); double iMA( string symbol, int timeframe, int period, int ma_shift, int ma_method, int applied_price, int shift) Calculates the Moving average indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. ma_shift - MA shift. Indicators line offset relate to the chart by timeframe. ma_method - MA method. It can be any of the Moving Average method enumeration value. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample AlligatorJawsBuffer[i]=iMA(NULL,0,13,8,MODE_SMMA,PRICE_MEDIAN,i); double iMAOnArray( double array[], int total, int period, int ma_shift, int ma_method, int shift) Calculates the Moving average counted on buffer and returns its value. Parameters array[] - Array with data. total - The number of items to be counted. 0 means whole array. period - Number of periods for calculation. ma_shift - MA shift ma_method - MA method. It can be any of the Moving Average method enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double macurrent=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,0); double macurrentslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,0); double maprev=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,1); double maprevslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,1); //---- if(maprev<maprevslow && macurrent>=macurrentslow) Alert("crossing up"); double iOsMA( string symbol, int timeframe, int fast_ema_period, int slow_ema_period, int signal_period, int applied_price, int shift) Calculates the Moving Average of Oscillator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. fast_ema_period - Number of periods for fast moving average calculation. slow_ema_period - Nmber of periods for slow moving average calculation. signal_period - Number of periods for signal moving average calculation. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iOsMA(NULL,0,12,26,9,PRICE_OPEN,1)>iOsMA(NULL,0,12,26,9,PRICE_OPEN,0)) return(0); double iMACD( string symbol, int timeframe, int fast_ema_period, int slow_ema_period, int signal_period, int applied_price, int mode, int shift) Calculates the Moving averages convergence/divergence and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. fast_ema_period - Number of periods for fast moving average calculation. slow_ema_period - Number of periods for slow moving average calculation. signal_period - Number of periods for signal moving average calculation. applied_price - Applied price. It can be any of Applied price enumeration values. mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0)>iMACD(NULL,0,12,26,9,PRICE_CLOSE,M ODE_SIGNAL,0)) return(0); double iOBV(string symbol, int timeframe, int applied_price, int shift) Calculates the On Balance Volume indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iOBV(NULL, 0, PRICE_CLOSE, 1); double iSAR(string symbol, int timeframe, double step, double maximum, int shift) Calculates the Parabolic Sell and Reverse system and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. step - Increment, usually 0.02. maximum - Maximum value, usually 0.2. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iSAR(NULL,0,0.02,0.2,0)>Close[0]) return(0); double iRSI(string symbol, void timeframe, int period, int applied_price, int shift) Calculates the Relative strength index and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iRSI(NULL,0,14,PRICE_CLOSE,0)>iRSI(NULL,0,14,PRICE_CLOSE,1)) return(0); double iRSIOnArray(double array[], int total, int period, int shift) Calculates the Relative strength index counted on buffer and returns its value. Parameters array[] - Array with data. total - The number of items to be counted. period - Number of periods for calculation. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iRSIOnBuffer(ExtBuffer,1000,14,0)>iRSI(NULL,0,14,PRICE_CLOSE,1)) return(0); double iRVI(string symbol, int timeframe, int period, int mode, int shift) Calculates the Relative Vigor index and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. mode - Indicator line array index. It can be any of Indicators line identifiers enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iRVI(NULL, 0, 10,MODE_MAIN,0); double iStdDev( string symbol, int timeframe, int ma_period, int ma_method, int ma_shift, int applied_price, int shift) Calculates the Standard Deviation indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. ma_period - MA period. ma_method - MA method. It can be any of Moving Average method enumeration value. ma_shift - MA shift. applied_price - Applied price. It can be any of Applied price enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iStdDev(NULL,0,10,MODE_EMA,0,PRICE_CLOSE,0); double iStdDevOnArray( double array[], int total, int ma_period, int ma_method, int ma_shift, int shift) Calculates the Standard Deviation counted on buffer and returns its value. Parameters array[] - Array with data. total - The number of items to be counted. ma_period - MA period. ma_method - MA method. It can be any of Moving Average method enumeration value. ma_shift - iMA shift. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample double val=iStdDevOnArray(ExtBuffer,100,10,MODE_EMA,0,0); double iStochastic( string symbol, int timeframe, int %Kperiod, int %Dperiod, int slowing, int method, int price_field, int mode, int shift) Calculates the Stochastic oscillator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. %Kperiod - %K line period. %Dperiod - %D line period. slowing - Slowing value. method - MA method. It can be any ofMoving Average method enumeration value. price_field - Price field parameter. Can be one of this values: 0 - Low/High or 1 - Close/Close. mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,0)>iStochastic(NULL,0,5,3,3,MODE_S MA,0,MODE_SIGNAL,0)) return(0); double iWPR(string symbol, int timeframe, int period, int shift) Calculates the Larry William's percent range indicator and returns its value. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. period - Number of periods for calculation. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample if(iWPR(NULL,0,14,0)>iWPR(NULL,0,14,1)) return(0); int iBars(string symbol, int timeframe) Returns the number of bars on the specified chart. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. Sample Print("Bar count on the 'EUROUSD' symbol with PERIOD_H1 is",iBars("EUROUSD",PERIOD_H1)); int iBarShift(string symbol, int timeframe, datetime time, bool exact=false) Search for bar by open time. The function returns bar shift with the open time specified. If the bar having the specified open time is absent the function will return, depending on the exact parameter, -1 or the nearest bar shift. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. time - value to find (bar's open time). exact - Return mode when bar not found. false - iBarShift returns nearest. true - iBarShift returns -1. Sample datetime some_time=D'2004.03.21 12:00'; int shift=iBarShift("EUROUSD",PERIOD_M1,some_time); Print("shift of bar with open time ",TimeToStr(some_time)," is ",shift); double iClose(string symbol, int timeframe, int shift) Returns Close value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function returns 0. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i)); double iHigh(string symbol, int timeframe, int shift) Returns High value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function returns 0. Parameters symbol - Symbol on that data need to calculate indicator. NULL means current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i)); double iLow(string symbol, int timeframe, int shift) Returns Low value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function returns 0. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i)); double iOpen(string symbol, int timeframe, int shift) Returns Open value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function returns 0. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i)); datetime iTime(string symbol, int timeframe, int shift) Returns Time value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function returns 0. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i)); double iVolume(string symbol, int timeframe, int shift) Returns Volume value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function returns 0. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. shift - Shift relative to the current bar (number of periods back), where the data should be taken from. Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i)); int Highest(string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0) Returns the shift of the maximum value over a specific number of periods depending on type. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. type - Series array identifier. It can be any of the Series array identifier enumeration values. count - Number of periods (in direction from the start bar to the back one) on which the calculation is carried out. start - Shift showing the bar, relative to the current bar, that the data should be taken from. Sample double val; // calculating the highest value in the range from 5 element to 25 element // indicator charts symbol and indicator charts time frame val=High[Highest(NULL,0,MODE_HIGH,20,4)]; int Lowest(string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0) Returns the shift of the least value over a specific number of periods depending on type. Parameters symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Time frame. It can be any of Time frame enumeration values. type - Series array identifier. It can be any of Series array identifier enumeration values. count - Number of periods (in direction from the start bar to the back one) on which the calculation is carried out. start - Shift showing the bar, relative to the current bar, that the data should be taken from. Sample double val=Low[Lowest(NULL,0,MODE_LOW,10,10)]; Trading functions HistoryTotal() OrderClose() OrderCloseBy() OrderClosePrice() OrderCloseTime() OrderComment() OrderCommission() OrderDelete() OrderExpiration() OrderLots() OrderMagicNumber() OrderModify() OrderOpenPrice() OrderOpenTime() OrderPrint() OrderProfit() OrderSelect() OrderSend() OrderStopLoss() OrdersTotal() OrderSwap() OrderSymbol() OrderTakeProfit() OrderTicket() OrderType() int HistoryTotal() Returns the number of closed orders in the account history loaded into the terminal. To get the detailed error information, call GetLastError() function. Sample // retrieving info from trade history int i,hstTotal=HistoryTotal(); for(i=0;i<hstTotal;i++) { //---- check selection result if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Access to history failed with error (",GetLastError(),")"); break; } // some work with order } bool OrderClose( int ticket, double lots, double price, int slippage, color Color=CLR_NONE) Closes opened order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). Parameters ticket - Unique number of the order ticket. lots - Number of lots. price - Preferred closing price. slippage - Value of the maximum price slippage in points. Color - Color of the closing arrow on the chart.If the parameter is absent or has CLR_NONE value closing arrow will not be drawn on the chart. Sample if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) { OrderClose(order_id,1,Ask,3,Red); return(0); } bool OrderCloseBy(int ticket, int opposite, color Color=CLR_NONE) Closes opened order by another opposite opened order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). Parameters ticket - Unique number of the order ticket. opposite - Unique number of the opposite order ticket. Color - Color of the closing arrow on the chart.If the parameter is absent or has CLR_NONE value closing arrow will not be drawn on the chart. Sample if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) { OrderCloseBy(order_id,opposite_id); return(0); } double OrderClosePrice() Returns close price for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(ticket,SELECT_BY_POS)==true) Print("Close price for the order ",ticket," = ",OrderClosePrice()); else Print("OrderSelect failed error code is",GetLastError()); datetime OrderCloseTime() Returns close time for the currently selected order. If order close time is not 0 then the order selected and has been closed and retrieved from the account history. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(10,SELECT_BY_POS,MODE_HISTORY)==true) { datetime ctm=OrderOpenTime(); if(ctm>0) Print("Open time for the order 10 ", ctm); ctm=OrderCloseTime(); if(ctm>0) Print("Close time for the order 10 ", ctm); } else Print("OrderSelect failed error code is",GetLastError()); string OrderComment() Returns comment for the selected order. Note: Order must be selected by OrderSelect() function. Sample string comment; if(OrderSelect(10,SELECT_BY_TICKET)==false) { Print("OrderSelect failed error code is",GetLastError()); return(0); } comment = OrderComment(); // ... double OrderCommission() Returns calculated commission for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(10,SELECT_BY_POS)==true) Print("Commission for the order 10 ",OrderCommission()); else Print("OrderSelect failed error code is",GetLastError()); bool OrderDelete(int ticket) Deletes previously opened pending order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). Parameters ticket - Unique number of the order ticket. Sample if(Ask>var1) { OrderDelete(order_ticket); return(0); } datetime OrderExpiration() Returns expiration date for the selected pending order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(10, SELECT_BY_TICKET)==true) Print("Order expiration for the order #10 is ",OrderExpiration()); else Print("OrderSelect failed error code is",GetLastError()); double OrderLots() Returns lots value for the selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(10,SELECT_BY_POS)==true) Print("lots for the order 10 ",OrderLots()); else Print("OrderSelect failed error code is",GetLastError()); int OrderMagicNumber() Returns magic number for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(10,SELECT_BY_POS)==true) Print("Magic number for the order 10 ", OrderMagicNumber()); else Print("OrderSelect failed error code is",GetLastError()); bool OrderModify( int ticket, double price, double stoploss, double takeprofit, datetime expiration, color arrow_color=CLR_NONE) Modification of characteristics for the previously opened position or a pending order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). Parameters ticket - Unique number of the order ticket. price - New price (for pending orders only). stoploss - New stoploss level. takeprofit - New profit-taking level. expiration - Order expiration server date/time (for pending orders only). arrow_color - Arrow color of the pictogram on the chart.If the parameter is absent or has CLR_NONE value arrow will not be drawn on the chart. Sample if(TrailingStop>0) { SelectOrder(12345,SELECT_BY_TICKET); if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(),Ask-10*Point,Ask- 35*Point,OrderTakeProfit(),0,Blue); return(0); } } } double OrderOpenPrice() Returns open price for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(10, SELECT_BY_POS)==true) Print("open price for the order 10 ",OrderOpenPrice()); else Print("OrderSelect failed error code is",GetLastError()); datetime OrderOpenTime() Returns open time for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(10, SELECT_BY_POS)==true) Print("open time for the order 10 ",OrderOpenTime()); else Print("OrderSelect failed error code is",GetLastError()); void OrderPrint() Prints selected order data to the log for the selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(10, SELECT_BY_TICKET)==true) OrderPrint(); else Print("OrderSelect failed error code is",GetLastError()); double OrderProfit() Returns profit for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(10, SELECT_BY_POS)==true) Print("Profit for the order 10 ",OrderProfit()); else Print("OrderSelect failed error code is",GetLastError()); bool OrderSelect(int index, int select, int pool=MODE_TRADES) Selects order by index or ticket to further processing. If the function fails, the return value will be false. To get the extended error information, call GetLastError(). Parameters index - Order index or order ticket depending from second parameter. select - Selecting flags. It can be any of the following values: SELECT_BY_POS - index in the order pool, SELECT_BY_TICKET - index is order ticket. pool - Optional order pool index. Used when select parameter is SELECT_BY_POS.It can be any of the following values: MODE_TRADES (default)- order selected from trading pool(opened and pending orders), MODE_HISTORY - order selected from history pool (closed and canceled order). Sample if(OrderSelect(12470, SELECT_BY_TICKET)==true) { Print("order #12470 open price is ", OrderOpenPrice()); Print("order #12470 close price is ", OrderClosePrice()); } else Print("OrderSelect failed error code is",GetLastError()); int OrderSend( string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE) Main function used to open a position or set a pending order. Returns ticket of the placed order or -1 if failed. To check error code use GetLastError() function. Parameters symbol - Symbol for trading. cmd - Operation type. It can be any of the Trade operation enumeration. volume - Number of lots. price - Preferred price of the trade. slippage - Maximum price slippage for buy or sell orders. stoploss - Stop loss level. takeprofit - Take profit level. comment - Order comment text. Last part of the comment may be changed by server. magic - Order magic number. May be used as user defined identifier. expiration - Order expiration time (for pending orders only). arrow_color - Color of the opening arrow on the chart. If parameter is absent or has CLR_NONE value opening arrow is not drawn on the chart. Sample int ticket; if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25) { ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,Ask-25*Point,Ask+25*Point,"My order #2",16384,0,Green); if(ticket<0) { Print("OrderSend failed with error #",GetLastError()); return(0); } } double OrderStopLoss() Returns stop loss value for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(ticket,SELECT_BY_POS)==true) Print("Stop loss value for the order 10 ", OrderStopLoss()); else Print("OrderSelect failed error code is",GetLastError()); int OrdersTotal() Returns market and pending orders count. Sample int handle=FileOpen("OrdersReport.csv",FILE_WRITE|FILE_CSV,"\t"); if(handle<0) return(0); // write header FileWrite(handle,"#","open price","open time","symbol","lots"); int total=OrdersTotal(); // write open orders for(int pos=0;pos<total;pos++) { if(OrderSelect(pos,SELECT_BY_POS)==false) continue; FileWrite(handle,OrderTicket(),OrderOpenPrice(),OrderOpenTime(),OrderSymbol(),Or derLots()); } FileClose(handle); double OrderSwap() Returns swap value for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(order_id, SELECT_BY_TICKET)==true) Print("Swap for the order #", order_id, " ",OrderSwap()); else Print("OrderSelect failed error code is",GetLastError()); string OrderSymbol() Returns the order symbol value for selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(12, SELECT_BY_POS)==true) Print("symbol of order #", OrderTicket(), " is ", OrderSymbol()); else Print("OrderSelect failed error code is",GetLastError()); double OrderTakeProfit() Returns take profit value for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(12, SELECT_BY_POS)==true) Print("Order #",OrderTicket()," profit: ", OrderTakeProfit()); else Print("OrderSelect() 忮痦箅 铠栳牦 - ",GetLastError()); int OrderTicket() Returns ticket number for the currently selected order. Note: Order must be selected by OrderSelect() function. Sample if(OrderSelect(12, SELECT_BY_POS)==true) order=OrderTicket(); else Print("OrderSelect failed error code is",GetLastError()); int OrderType() Returns order operation type for the currently selected order. It can be any of the following values: OP_BUY - buying position, OP_SELL - selling position, OP_BUYLIMIT - buy limit pending position, OP_BUYSTOP - buy stop pending position, OP_SELLLIMIT - sell limit pending position, OP_SELLSTOP - sell stop pending position. Note: Order must be selected by OrderSelect() function. Sample int order_type; if(OrderSelect(12, SELECT_BY_POS)==true) { order_type=OrderType(); // ... } else Print("OrderSelect() returned error - ",GetLastError()); Window functions BarsPerWindow() FirstVisibleBar() PriceOnDropped() TimeOnDropped() WindowFind() WindowHandle() WindowIsVisible WindowOnDropped() WindowsTotal() WindowXOnDropped() WindowYOnDropped() int BarsPerWindow() Function returns the amount of bars visible on the chart. Sample // work with visible bars. int bars_count=BarsPerWindow(); int bar=FirstVisibleBar(); for(int i=0; i<bars_count; i++,bar--) { // ... } int FirstVisibleBar() Function returns index of the first visible bar. Sample // work with visible bars. int bars_count=BarsPerWindow(); int bar=FirstVisibleBar(); for(int i=0; i<bars_count; i++,bar--) { // ... } int FirstVisibleBar() Function returns index of the first visible bar. Sample // work with visible bars. int bars_count=BarsPerWindow(); int bar=FirstVisibleBar(); for(int i=0; i<bars_count; i++,bar--) { // ... } datetime TimeOnDropped() Returns time part of dropped point where expert or script was dropped. This value is valid when expert or script dropped by mouse. Note: For custom indicators this value is undefined. Sample double drop_price=PriceOnDropped(); datetime drop_time=TimeOnDropped(); //---- may be undefined (zero) if(drop_time>0) { ObjectCreate("Dropped price line", OBJ_HLINE, 0, drop_price); ObjectCreate("Dropped time line", OBJ_VLINE, 0, drop_time); } int WindowFind(string name) If indicator with name found returns the window index containing specified indicator, otherwise returns -1. Note: WindowFind() returns -1 if ñustom indicator searches itself when init() function works. Parameters name - Indicator short name. Sample int win_idx=WindowFind("MACD(12,26,9)"); int WindowHandle(string symbol, int timeframe) If chart of symbol and timeframe is currently opened returns the window handle, otherwise returns 0. Parameters symbol - symbol name. timeframe - Time frame. It can be any of Time frame enumeration values. Sample int win_handle=WindowHandle("USDX",PERIOD_H1); if(win_handle!=0) Print("Window with USDX,H1 detected. Rates array will be copied immediately."); bool WindowIsVisible(int index) Returns true if the chart subwindow is visible, otherwise returns false. Parameters index - Chart subwindow index. Sample int maywin=WindowFind("MyMACD"); if(maywin>-1 && WindowIsVisible(maywin)==true) Print("window of MyMACD is visible"); else Print("window of MyMACD not found or is not visible"); int WindowOnDropped() Returns window index where expert, custom indicator or script was dropped. This value is valid when expert, custom indicator or script dropped by mouse. Note: For custom indicators this index is undefined when init() function works and returning index is window index where custom indicator works (may be different from dropping window index, because custom indicator can create its own new window). See also WindowXOnDropped(), WindowYOnDropped() Sample if(WindowOnDropped()!=0) { Print("Indicator 'MyIndicator' must be applied to main chart window!"); return(false); } int WindowsTotal() Returns count of indicator windows on the chart (including main chart). Sample Print("Windows count = ", WindowsTotal()); int WindowXOnDropped() Returns x-axis coordinate in pixels were expert or script dropped to the chart. See also WindowYOnDropped(), WindowOnDropped() Sample Print("Expert dropped point x=",WindowXOnDropped()," y=",WindowYOnDropped()); int WindowYOnDropped() Returns y-axis coordinate in pixels were expert or script dropped to the chart. See also WindowYOnDropped(), WindowOnDropped() Sample Print("Expert dropped point x=",WindowXOnDropped()," y=",WindowYOnDropped()); Include Files //+------------------------------------------------------------------+ //| stderror.mqh | //| Copyright © 2004-2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ //---- errors returned from trade server #define ERR_NO_ERROR 0 #define ERR_NO_RESULT 1 #define ERR_COMMON_ERROR 2 #define ERR_INVALID_TRADE_PARAMETERS 3 #define ERR_SERVER_BUSY 4 #define ERR_OLD_VERSION 5 #define ERR_NO_CONNECTION 6 #define ERR_NOT_ENOUGH_RIGHTS 7 #define ERR_TOO_FREQUENT_REQUESTS 8 #define ERR_MALFUNCTIONAL_TRADE 9 #define ERR_ACCOUNT_DISABLED 64 #define ERR_INVALID_ACCOUNT 65 #define ERR_TRADE_TIMEOUT 128 #define ERR_INVALID_PRICE 129 #define ERR_INVALID_STOPS 130 #define ERR_INVALID_TRADE_VOLUME 131 #define ERR_MARKET_CLOSED 132 #define ERR_TRADE_DISABLED 133 #define ERR_NOT_ENOUGH_MONEY 134 #define ERR_PRICE_CHANGED 135 #define ERR_OFF_QUOTES 136 #define ERR_BROKER_BUSY 137 #define ERR_REQUOTE 138 #define ERR_ORDER_LOCKED 139 #define ERR_LONG_POSITIONS_ONLY_ALLOWED 140 #define ERR_TOO_MANY_REQUESTS 141 #define ERR_TRADE_MODIFY_DENIED 145 #define ERR_TRADE_CONTEXT_BUSY 146 //---- mql4 run time errors #define ERR_NO_MQLERROR 4000 #define ERR_WRONG_FUNCTION_POINTER 4001 #define ERR_ARRAY_INDEX_OUT_OF_RANGE 4002 #define ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK 4003 #define ERR_RECURSIVE_STACK_OVERFLOW 4004 #define ERR_NOT_ENOUGH_STACK_FOR_PARAMETER 4005 #define ERR_NO_MEMORY_FOR_PARAMETER_STRING 4006 #define ERR_NO_MEMORY_FOR_TEMP_STRING 4007 #define ERR_NOT_INITIALIZED_STRING 4008 #define ERR_NOT_INITIALIZED_ARRAYSTRING 4009 #define ERR_NO_MEMORY_FOR_ARRAYSTRING 4010 #define ERR_TOO_LONG_STRING 4011 #define ERR_REMAINDER_FROM_ZERO_DIVIDE 4012 #define ERR_ZERO_DIVIDE 4013 #define ERR_UNKNOWN_COMMAND 4014 #define ERR_WRONG_JUMP 4015 #define ERR_NOT_INITIALIZED_ARRAY 4016 #define ERR_DLL_CALLS_NOT_ALLOWED 4017 #define ERR_CANNOT_LOAD_LIBRARY 4018 #define ERR_CANNOT_CALL_FUNCTION 4019 #define ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED 4020 #define ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING 4021 #define ERR_SYSTEM_BUSY 4022 #define ERR_INVALID_FUNCTION_PARAMETERS_COUNT 4050 #define ERR_INVALID_FUNCTION_PARAMETER_VALUE 4051 #define ERR_STRING_FUNCTION_INTERNAL_ERROR 4052 #define ERR_SOME_ARRAY_ERROR 4053 #define ERR_INCORRECT_SERIES_ARRAY_USING 4054 #define ERR_CUSTOM_INDICATOR_ERROR 4055 #define ERR_INCOMPATIBLE_ARRAYS 4056 #define ERR_GLOBAL_VARIABLES_PROCESSING_ERROR 4057 #define ERR_GLOBAL_VARIABLE_NOT_FOUND 4058 #define ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE 4059 #define ERR_FUNCTION_NOT_CONFIRMED 4060 #define ERR_SEND_MAIL_ERROR 4061 #define ERR_STRING_PARAMETER_EXPECTED 4062 #define ERR_INTEGER_PARAMETER_EXPECTED 4063 #define ERR_DOUBLE_PARAMETER_EXPECTED 4064 #define ERR_ARRAY_AS_PARAMETER_EXPECTED 4065 #define ERR_HISTORY_WILL_UPDATED 4066 #define ERR_END_OF_FILE 4099 #define ERR_SOME_FILE_ERROR 4100 #define ERR_WRONG_FILE_NAME 4101 #define ERR_TOO_MANY_OPENED_FILES 4102 #define ERR_CANNOT_OPEN_FILE 4103 #define ERR_INCOMPATIBLE_ACCESS_TO_FILE 4104 #define ERR_NO_ORDER_SELECTED 4105 #define ERR_UNKNOWN_SYMBOL 4106 #define ERR_INVALID_PRICE_PARAM 4107 #define ERR_INVALID_TICKET 4108 #define ERR_TRADE_NOT_ALLOWED 4109 #define ERR_LONGS__NOT_ALLOWED 4110 #define ERR_SHORTS_NOT_ALLOWED 4111 #define ERR_OBJECT_ALREADY_EXISTS 4200 #define ERR_UNKNOWN_OBJECT_PROPERTY 4201 #define ERR_OBJECT_DOES_NOT_EXIST 4202 #define ERR_UNKNOWN_OBJECT_TYPE 4203 #define ERR_NO_OBJECT_NAME 4204 #define ERR_OBJECT_COORDINATES_ERROR 4205 #define ERR_NO_SPECIFIED_SUBWINDOW 4206 //+------------------------------------------------------------------+ //| stdlib.mqh | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #import "stdlib.ex4" string ErrorDescription(int error_code); int RGB(int red_value,int green_value,int blue_value); bool CompareDoubles(double number1,double number2); string DoubleToStrMorePrecision(double number,int precision); string IntegerToHexString(int integer_number); //+------------------------------------------------------------------+ //| WinUser32.mqh | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #define copyright "Copyright © 2004, MetaQuotes Software Corp." #define link "http://www.metaquotes.net/" #import "user32.dll" //---- messages int SendMessageA(int hWnd,int Msg,int wParam,int lParam); int SendNotifyMessageA(int hWnd,int Msg,int wParam,int lParam); int PostMessageA(int hWnd,int Msg,int wParam,int lParam); void keybd_event(int bVk,int bScan,int dwFlags,int dwExtraInfo); void mouse_event(int dwFlags,int dx,int dy,int dwData,int dwExtraInfo); //---- windows int FindWindowA(string lpClassName ,string lpWindowName); int SetWindowTextA(int hWnd,string lpString); int GetWindowTextA(int hWnd,string lpString,int nMaxCount); int GetWindowTextLengthA(int hWnd); int GetWindow(int hWnd,int uCmd); int UpdateWindow(int hWnd); int EnableWindow(int hWnd,int bEnable); int DestroyWindow(int hWnd); int ShowWindow(int hWnd,int nCmdShow); int SetActiveWindow(int hWnd); int AnimateWindow(int hWnd,int dwTime,int dwFlags); int FlashWindow(int hWnd,int dwFlags /*bInvert*/); int CloseWindow(int hWnd); int MoveWindow(int hWnd,int X,int Y,int nWidth,int nHeight,int bRepaint); int SetWindowPos(int hWnd,int hWndInsertAfter ,int X,int Y,int cx,int cy,int uFlags); int IsWindowVisible(int hWnd); int IsIconic(int hWnd); int IsZoomed(int hWnd); int SetFocus(int hWnd); int GetFocus(); int GetActiveWindow(); int IsWindowEnabled(int hWnd); //---- miscelaneouse int MessageBoxA(int hWnd ,string lpText,string lpCaption,int uType); int MessageBoxExA(int hWnd ,string lpText,string lpCaption,int uType,int wLanguageId); int MessageBeep(int uType); int GetSystemMetrics(int nIndex); int ExitWindowsEx(int uFlags,int dwReserved); int SwapMouseButton(int fSwap); #import //---- Window Messages #define WM_NULL 0x0000 #define WM_CREATE 0x0001 #define WM_DESTROY 0x0002 #define WM_MOVE 0x0003 #define WM_SIZE 0x0005 #define WM_ACTIVATE 0x0006 #define WM_SETFOCUS 0x0007 #define WM_KILLFOCUS 0x0008 #define WM_ENABLE 0x000A #define WM_SETREDRAW 0x000B #define WM_SETTEXT 0x000C #define WM_GETTEXT 0x000D #define WM_GETTEXTLENGTH 0x000E #define WM_PAINT 0x000F #define WM_CLOSE 0x0010 #define WM_QUERYENDSESSION 0x0011 #define WM_QUIT 0x0012 #define WM_QUERYOPEN 0x0013 #define WM_ERASEBKGND 0x0014 #define WM_SYSCOLORCHANGE 0x0015 #define WM_ENDSESSION 0x0016 #define WM_SHOWWINDOW 0x0018 #define WM_WININICHANGE 0x001A #define WM_SETTINGCHANGE 0x001A // WM_WININICHANGE #define WM_DEVMODECHANGE 0x001B #define WM_ACTIVATEAPP 0x001C #define WM_FONTCHANGE 0x001D #define WM_TIMECHANGE 0x001E #define WM_CANCELMODE 0x001F #define WM_SETCURSOR 0x0020 #define WM_MOUSEACTIVATE 0x0021 #define WM_CHILDACTIVATE 0x0022 #define WM_QUEUESYNC 0x0023 #define WM_GETMINMAXINFO 0x0024 #define WM_PAINTICON 0x0026 #define WM_ICONERASEBKGND 0x0027 #define WM_NEXTDLGCTL 0x0028 #define WM_SPOOLERSTATUS 0x002A #define WM_DRAWITEM 0x002B #define WM_MEASUREITEM 0x002C #define WM_DELETEITEM 0x002D #define WM_VKEYTOITEM 0x002E #define WM_CHARTOITEM 0x002F #define WM_SETFONT 0x0030 #define WM_GETFONT 0x0031 #define WM_SETHOTKEY 0x0032 #define WM_GETHOTKEY 0x0033 #define WM_QUERYDRAGICON 0x0037 #define WM_COMPAREITEM 0x0039 #define WM_GETOBJECT 0x003D #define WM_COMPACTING 0x0041 #define WM_WINDOWPOSCHANGING 0x0046 #define WM_WINDOWPOSCHANGED 0x0047 #define WM_COPYDATA 0x004A #define WM_CANCELJOURNAL 0x004B #define WM_NOTIFY 0x004E #define WM_INPUTLANGCHANGEREQUEST 0x0050 #define WM_INPUTLANGCHANGE 0x0051 #define WM_TCARD 0x0052 #define WM_HELP 0x0053 #define WM_USERCHANGED 0x0054 #define WM_NOTIFYFORMAT 0x0055 #define WM_CONTEXTMENU 0x007B #define WM_STYLECHANGING 0x007C #define WM_STYLECHANGED 0x007D #define WM_DISPLAYCHANGE 0x007E #define WM_GETICON 0x007F #define WM_SETICON 0x0080 #define WM_NCCREATE 0x0081 #define WM_NCDESTROY 0x0082 #define WM_NCCALCSIZE 0x0083 #define WM_NCHITTEST 0x0084 #define WM_NCPAINT 0x0085 #define WM_NCACTIVATE 0x0086 #define WM_GETDLGCODE 0x0087 #define WM_SYNCPAINT 0x0088 #define WM_NCMOUSEMOVE 0x00A0 #define WM_NCLBUTTONDOWN 0x00A1 #define WM_NCLBUTTONUP 0x00A2 #define WM_NCLBUTTONDBLCLK 0x00A3 #define WM_NCRBUTTONDOWN 0x00A4 #define WM_NCRBUTTONUP 0x00A5 #define WM_NCRBUTTONDBLCLK 0x00A6 #define WM_NCMBUTTONDOWN 0x00A7 #define WM_NCMBUTTONUP 0x00A8 #define WM_NCMBUTTONDBLCLK 0x00A9 #define WM_KEYFIRST 0x0100 #define WM_KEYDOWN 0x0100 #define WM_KEYUP 0x0101 #define WM_CHAR 0x0102 #define WM_DEADCHAR 0x0103 #define WM_SYSKEYDOWN 0x0104 #define WM_SYSKEYUP 0x0105 #define WM_SYSCHAR 0x0106 #define WM_SYSDEADCHAR 0x0107 #define WM_KEYLAST 0x0108 #define WM_INITDIALOG 0x0110 #define WM_COMMAND 0x0111 #define WM_SYSCOMMAND 0x0112 #define WM_TIMER 0x0113 #define WM_HSCROLL 0x0114 #define WM_VSCROLL 0x0115 #define WM_INITMENU 0x0116 #define WM_INITMENUPOPUP 0x0117 #define WM_MENUSELECT 0x011F #define WM_MENUCHAR 0x0120 #define WM_ENTERIDLE 0x0121 #define WM_MENURBUTTONUP 0x0122 #define WM_MENUDRAG 0x0123 #define WM_MENUGETOBJECT 0x0124 #define WM_UNINITMENUPOPUP 0x0125 #define WM_MENUCOMMAND 0x0126 #define WM_CTLCOLORMSGBOX 0x0132 #define WM_CTLCOLOREDIT 0x0133 #define WM_CTLCOLORLISTBOX 0x0134 #define WM_CTLCOLORBTN 0x0135 #define WM_CTLCOLORDLG 0x0136 #define WM_CTLCOLORSCROLLBAR 0x0137 #define WM_CTLCOLORSTATIC 0x0138 #define WM_MOUSEFIRST 0x0200 #define WM_MOUSEMOVE 0x0200 #define WM_LBUTTONDOWN 0x0201 #define WM_LBUTTONUP 0x0202 #define WM_LBUTTONDBLCLK 0x0203 #define WM_RBUTTONDOWN 0x0204 #define WM_RBUTTONUP 0x0205 #define WM_RBUTTONDBLCLK 0x0206 #define WM_MBUTTONDOWN 0x0207 #define WM_MBUTTONUP 0x0208 #define WM_MBUTTONDBLCLK 0x0209 #define WM_PARENTNOTIFY 0x0210 #define WM_ENTERMENULOOP 0x0211 #define WM_EXITMENULOOP 0x0212 #define WM_NEXTMENU 0x0213 #define WM_SIZING 0x0214 #define WM_CAPTURECHANGED 0x0215 #define WM_MOVING 0x0216 #define WM_DEVICECHANGE 0x0219 #define WM_MDICREATE 0x0220 #define WM_MDIDESTROY 0x0221 #define WM_MDIACTIVATE 0x0222 #define WM_MDIRESTORE 0x0223 #define WM_MDINEXT 0x0224 #define WM_MDIMAXIMIZE 0x0225 #define WM_MDITILE 0x0226 #define WM_MDICASCADE 0x0227 #define WM_MDIICONARRANGE 0x0228 #define WM_MDIGETACTIVE 0x0229 #define WM_MDISETMENU 0x0230 #define WM_ENTERSIZEMOVE 0x0231 #define WM_EXITSIZEMOVE 0x0232 #define WM_DROPFILES 0x0233 #define WM_MDIREFRESHMENU 0x0234 #define WM_MOUSEHOVER 0x02A1 #define WM_MOUSELEAVE 0x02A3 #define WM_CUT 0x0300 #define WM_COPY 0x0301 #define WM_PASTE 0x0302 #define WM_CLEAR 0x0303 #define WM_UNDO 0x0304 #define WM_RENDERFORMAT 0x0305 #define WM_RENDERALLFORMATS 0x0306 #define WM_DESTROYCLIPBOARD 0x0307 #define WM_DRAWCLIPBOARD 0x0308 #define WM_PAINTCLIPBOARD 0x0309 #define WM_VSCROLLCLIPBOARD 0x030A #define WM_SIZECLIPBOARD 0x030B #define WM_ASKCBFORMATNAME 0x030C #define WM_CHANGECBCHAIN 0x030D #define WM_HSCROLLCLIPBOARD 0x030E #define WM_QUERYNEWPALETTE 0x030F #define WM_PALETTEISCHANGING 0x0310 #define WM_PALETTECHANGED 0x0311 #define WM_HOTKEY 0x0312 #define WM_PRINT 0x0317 #define WM_PRINTCLIENT 0x0318 #define WM_HANDHELDFIRST 0x0358 #define WM_HANDHELDLAST 0x035F #define WM_AFXFIRST 0x0360 #define WM_AFXLAST 0x037F #define WM_PENWINFIRST 0x0380 #define WM_PENWINLAST 0x038F #define WM_APP 0x8000 //---- keybd_event routines #define KEYEVENTF_EXTENDEDKEY 0x0001 #define KEYEVENTF_KEYUP 0x0002 //---- mouse_event routines #define MOUSEEVENTF_MOVE 0x0001 // mouse move #define MOUSEEVENTF_LEFTDOWN 0x0002 // left button down #define MOUSEEVENTF_LEFTUP 0x0004 // left button up #define MOUSEEVENTF_RIGHTDOWN 0x0008 // right button down #define MOUSEEVENTF_RIGHTUP 0x0010 // right button up #define MOUSEEVENTF_MIDDLEDOWN 0x0020 // middle button down #define MOUSEEVENTF_MIDDLEUP 0x0040 // middle button up #define MOUSEEVENTF_WHEEL 0x0800 // wheel button rolled #define MOUSEEVENTF_ABSOLUTE 0x8000 // absolute move //---- GetSystemMetrics() codes #define SM_CXSCREEN 0 #define SM_CYSCREEN 1 #define SM_CXVSCROLL 2 #define SM_CYHSCROLL 3 #define SM_CYCAPTION 4 #define SM_CXBORDER 5 #define SM_CYBORDER 6 #define SM_CXDLGFRAME 7 #define SM_CYDLGFRAME 8 #define SM_CYVTHUMB 9 #define SM_CXHTHUMB 10 #define SM_CXICON 11 #define SM_CYICON 12 #define SM_CXCURSOR 13 #define SM_CYCURSOR 14 #define SM_CYMENU 15 #define SM_CXFULLSCREEN 16 #define SM_CYFULLSCREEN 17 #define SM_CYKANJIWINDOW 18 #define SM_MOUSEPRESENT 19 #define SM_CYVSCROLL 20 #define SM_CXHSCROLL 21 #define SM_DEBUG 22 #define SM_SWAPBUTTON 23 #define SM_RESERVED1 24 #define SM_RESERVED2 25 #define SM_RESERVED3 26 #define SM_RESERVED4 27 #define SM_CXMIN 28 #define SM_CYMIN 29 #define SM_CXSIZE 30 #define SM_CYSIZE 31 #define SM_CXFRAME 32 #define SM_CYFRAME 33 #define SM_CXMINTRACK 34 #define SM_CYMINTRACK 35 #define SM_CXDOUBLECLK 36 #define SM_CYDOUBLECLK 37 #define SM_CXICONSPACING 38 #define SM_CYICONSPACING 39 #define SM_MENUDROPALIGNMENT 40 #define SM_PENWINDOWS 41 #define SM_DBCSENABLED 42 #define SM_CMOUSEBUTTONS 43 #define SM_SECURE 44 #define SM_CXEDGE 45 #define SM_CYEDGE 46 #define SM_CXMINSPACING 47 #define SM_CYMINSPACING 48 #define SM_CXSMICON 49 #define SM_CYSMICON 50 #define SM_CYSMCAPTION 51 #define SM_CXSMSIZE 52 #define SM_CYSMSIZE 53 #define SM_CXMENUSIZE 54 #define SM_CYMENUSIZE 55 #define SM_ARRANGE 56 #define SM_CXMINIMIZED 57 #define SM_CYMINIMIZED 58 #define SM_CXMAXTRACK 59 #define SM_CYMAXTRACK 60 #define SM_CXMAXIMIZED 61 #define SM_CYMAXIMIZED 62 #define SM_NETWORK 63 #define SM_CLEANBOOT 67 #define SM_CXDRAG 68 #define SM_CYDRAG 69 #define SM_SHOWSOUNDS 70 #define SM_CXMENUCHECK 71 // Use instead of GetMenuCheckMarkDimensions()! #define SM_CYMENUCHECK 72 #define SM_SLOWMACHINE 73 #define SM_MIDEASTENABLED 74 #define SM_MOUSEWHEELPRESENT 75 #define SM_XVIRTUALSCREEN 76 #define SM_YVIRTUALSCREEN 77 #define SM_CXVIRTUALSCREEN 78 #define SM_CYVIRTUALSCREEN 79 #define SM_CMONITORS 80 #define SM_SAMEDISPLAYFORMAT 81 //---- GetWindow() Constants #define GW_HWNDFIRST 0 #define GW_HWNDLAST 1 #define GW_HWNDNEXT 2 #define GW_HWNDPREV 3 #define GW_OWNER 4 #define GW_CHILD 5 //---- AnimateWindow() Commands #define AW_HOR_POSITIVE 0x00000001 #define AW_HOR_NEGATIVE 0x00000002 #define AW_VER_POSITIVE 0x00000004 #define AW_VER_NEGATIVE 0x00000008 #define AW_CENTER 0x00000010 #define AW_HIDE 0x00010000 #define AW_ACTIVATE 0x00020000 #define AW_SLIDE 0x00040000 #define AW_BLEND 0x00080000 //---- MessageBox() Flags #define MB_OK 0x00000000 #define MB_OKCANCEL 0x00000001 #define MB_ABORTRETRYIGNORE 0x00000002 #define MB_YESNOCANCEL 0x00000003 #define MB_YESNO 0x00000004 #define MB_RETRYCANCEL 0x00000005 #define MB_ICONHAND 0x00000010 #define MB_ICONQUESTION 0x00000020 #define MB_ICONEXCLAMATION 0x00000030 #define MB_ICONASTERISK 0x00000040 #define MB_USERICON 0x00000080 #define MB_ICONWARNING MB_ICONEXCLAMATION #define MB_ICONERROR MB_ICONHAND #define MB_ICONINFORMATION MB_ICONASTERISK #define MB_ICONSTOP MB_ICONHAND #define MB_DEFBUTTON1 0x00000000 #define MB_DEFBUTTON2 0x00000100 #define MB_DEFBUTTON3 0x00000200 #define MB_DEFBUTTON4 0x00000300 #define MB_APPLMODAL 0x00000000 #define MB_SYSTEMMODAL 0x00001000 #define MB_TASKMODAL 0x00002000 #define MB_HELP 0x00004000 // Help Button #define MB_NOFOCUS 0x00008000 #define MB_SETFOREGROUND 0x00010000 #define MB_DEFAULT_DESKTOP_ONLY 0x00020000 #define MB_TOPMOST 0x00040000 #define MB_RIGHT 0x00080000 #define MB_RTLREADING 0x00100000 //---- Dialog Box Command IDs #define IDOK 1 #define IDCANCEL 2 #define IDABORT 3 #define IDRETRY 4 #define IDIGNORE 5 #define IDYES 6 #define IDNO 7 #define IDCLOSE 8 #define IDHELP 9 //+------------------------------------------------------------------+ Scripts //+------------------------------------------------------------------+ //| Period_Converter.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net" #property show_inputs #include <WinUser32.mqh> extern int ExtPeriodMultiplier=3; // new period multiplier factor int ExtHandle=-1; //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { int i, start_pos, i_time, time0, last_fpos, periodseconds; double d_open, d_low, d_high, d_close, d_volume, last_volume; int hwnd=0,cnt=0; //---- History header int version=400; string c_copyright; string c_symbol=Symbol(); int i_period=Period()*ExtPeriodMultiplier; int i_digits=Digits; int i_unused[13]; //---- ExtHandle=FileOpenHistory(c_symbol+i_period+".hst", FILE_BIN|FILE_WRITE); if(ExtHandle < 0) return(-1); //---- write history file header c_copyright="(C)opyright 2003, MetaQuotes Software Corp."; FileWriteInteger(ExtHandle, version, LONG_VALUE); FileWriteString(ExtHandle, c_copyright, 64); FileWriteString(ExtHandle, c_symbol, 12); FileWriteInteger(ExtHandle, i_period, LONG_VALUE); FileWriteInteger(ExtHandle, i_digits, LONG_VALUE); FileWriteInteger(ExtHandle, 0, LONG_VALUE); //timesign FileWriteInteger(ExtHandle, 0, LONG_VALUE); //last_sync FileWriteArray(ExtHandle, i_unused, 0, 13); //---- write history file periodseconds=i_period*60; start_pos=Bars-1; d_open=Open[start_pos]; d_low=Low[start_pos]; d_high=High[start_pos]; d_volume=Volume[start_pos]; //---- normalize open time i_time=Time[start_pos]/periodseconds; i_time*=periodseconds; for(i=start_pos-1;i>=0; i--) { time0=Time[i]; if(time0>=i_time+periodseconds || i==0) { if(i==0 && time0<i_time+periodseconds) { d_volume+=Volume[0]; if (Low[0]<d_low) d_low=Low[0]; if (High[0]>d_high) d_high=High[0]; d_close=Close[0]; } last_fpos=FileTell(ExtHandle); last_volume=Volume[i]; FileWriteInteger(ExtHandle, i_time, LONG_VALUE); FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE); FileFlush(ExtHandle); cnt++; if(time0>=i_time+periodseconds) { i_time=time0/periodseconds; i_time*=periodseconds; d_open=Open[i]; d_low=Low[i]; d_high=High[i]; d_close=Close[i]; d_volume=last_volume; } } else { d_volume+=Volume[i]; if (Low[i]<d_low) d_low=Low[i]; if (High[i]>d_high) d_high=High[i]; d_close=Close[i]; } } FileFlush(ExtHandle); Print(cnt," record(s) written"); //---- collect incoming ticks int last_time=LocalTime()-5; while(true) { int cur_time=LocalTime(); //---- check for new rates if(RefreshRates()) { time0=Time[0]; FileSeek(ExtHandle,last_fpos,SEEK_SET); //---- is there current bar? if(time0<i_time+periodseconds) { d_volume+=Volume[0]-last_volume; last_volume=Volume[0]; if (Low[0]<d_low) d_low=Low[0]; if (High[0]>d_high) d_high=High[0]; d_close=Close[0]; } else { //---- no, there is new bar d_volume+=Volume[1]-last_volume; if (Low[1]<d_low) d_low=Low[1]; if (High[1]>d_high) d_high=High[1]; //---- write previous bar remains FileWriteInteger(ExtHandle, i_time, LONG_VALUE); FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE); last_fpos=FileTell(ExtHandle); //---- i_time=time0/periodseconds; i_time*=periodseconds; d_open=Open[0]; d_low=Low[0]; d_high=High[0]; d_close=Close[0]; d_volume=Volume[0]; last_volume=d_volume; } //---- FileWriteInteger(ExtHandle, i_time, LONG_VALUE); FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE); FileFlush(ExtHandle); //---- if(hwnd==0) { hwnd=WindowHandle(Symbol(),i_period); if(hwnd!=0) Print("Chart window detected"); } //---- refresh window not frequently than 1 time in 2 seconds if(hwnd!=0 && cur_time-last_time>=2) { PostMessageA(hwnd,WM_COMMAND,33324,0); last_time=cur_time; } } } //---- return(0); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void deinit() { if(ExtHandle>=0) { FileClose(ExtHandle); ExtHandle=-1; } } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| rotate_text.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #include <stdlib.mqh> string line_name="rotating_line"; string object_name1="rotating_text"; void init() { Print("point = ", Point," bars=",Bars); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void deinit() { ObjectDelete(line_name); ObjectDelete(object_name1); ObjectsRedraw(); } //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { int time2; int error,index,fontsize=10; double price,price1,price2; double angle=0.0; //---- price2=High[10]+Point*10; ObjectCreate(line_name, OBJ_TRENDBYANGLE, 0, Time[10], price2); index=20; ObjectCreate(object_name1, OBJ_TEXT, 0, Time[index], Low[index]-Point*100); ObjectSetText(object_name1, "rotating_text", fontsize); while(IsStopped()==false) { index++; price=ObjectGet(object_name1, OBJPROP_PRICE1)+Point; error=GetLastError(); if(error!=0) { Print(object_name1," : ",ErrorDescription(error)); break; } ObjectMove(object_name1, 0, Time[index], price); ObjectSet(object_name1, OBJPROP_ANGLE, angle*2); ObjectSet(object_name1, OBJPROP_FONTSIZE, fontsize); ObjectSet(line_name, OBJPROP_WIDTH, angle/18.0); double line_angle=360.0-angle; if(line_angle==90.0) ObjectSet(line_name, OBJPROP_PRICE2, price2+Point*50); if(line_angle==270.0) ObjectSet(line_name, OBJPROP_PRICE2, price2-Point*50); time2=ObjectGet(line_name,OBJPROP_TIME2); if(line_angle>90.0 && line_angle<270.0) time2=Time[index+10]; else time2=Time[0]; ObjectSet(line_name, OBJPROP_TIME2, time2); ObjectSet(line_name, OBJPROP_ANGLE, line_angle); ObjectsRedraw(); angle+=3.0; if(angle>=360.0) angle=360.0-angle; fontsize++; if(fontsize>48) fontsize=6; Sleep(500); price1=ObjectGetValueByShift(line_name, index); if(GetLastError()==0) { if(MathAbs(price1-price) < Point*50) { Print("price=",price," price1=", price1); ObjectSetText(object_name1, "REMOVED", 48, "Arial", RGB(255,215,0)); ObjectsRedraw(); Sleep(5000); // ObjectDelete(object_name1); } } } return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| trade.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #include <stdlib.mqh> #include <WinUser32.mqh> //+------------------------------------------------------------------+ //| script "trading for all money" | //+------------------------------------------------------------------+ int start() { //---- if(MessageBox("Do you really want to BUY 1.00 "+Symbol()+" at ASK price? ", "Script",MB_YESNO|MB_ICONQUESTION)!=IDYES) return(1); //---- int ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE); if(ticket<1) { int error=GetLastError(); Print("Error = ",ErrorDescription(error)); return; } //---- OrderPrint(); return(0); } //+------------------------------------------------------------------+ Templates <expert> type=INDICATOR_ADVISOR description=Accelerator Oscilator separate_window=1 used_buffers=4 <ind> color=Green type=DRAW_HISTOGRAM </ind> <ind> color=Red type=DRAW_HISTOGRAM </ind> </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtGreenBuffer[]; double ExtRedBuffer[]; double ExtMABuffer[]; double ExtBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used#; //---- indicator buffers mapping SetIndexBuffer(0, ExtGreenBuffer); SetIndexBuffer(1, ExtRedBuffer); SetIndexBuffer(2, ExtMABuffer); SetIndexBuffer(3, ExtBuffer); //---- drawing settings #indicators_init# //---- IndicatorDigits(6); SetIndexDrawBegin(0,38); SetIndexDrawBegin(1,38); //---- name for DataWindow and indicator subwindow label IndicatorShortName("AC"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Accelerator/Decelerator Oscillator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); double prev,current; //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i<limit; i++) ExtMABuffer[i]=iMA(NULL,0,5,0,MODE_SMA,PRICE_MEDIAN,i)- iMA(NULL,0,34,0,MODE_SMA,PRICE_MEDIAN,i); //---- signal line counted in the 2-nd additional buffer for(i=0; i<limit; i++) ExtBuffer[i]=iMAOnArray(ExtMABuffer,Bars,5,0,MODE_SMA,i); //---- dispatch values between 2 buffers bool up=true; for(i=limit-1; i>=0; i--) { current=ExtMABuffer[i]-ExtBuffer[i]; prev=ExtMABuffer[i+1]-ExtBuffer[i+1]; if(current>prev) up=true; if(current<prev) up=false; if(!up) { ExtRedBuffer[i]=current; ExtGreenBuffer[i]=0.0; } else { ExtGreenBuffer[i]=current; ExtRedBuffer[i]=0.0; } } //---- done return(0); } //+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR description= used_buffers=3 <param> name=JawsPeriod type=int value=13 </param> <param> name=JawsShift type=int value=8 </param> <param> name=TeethPeriod type=int value=8 </param> <param> name=TeethShift type=int value=5 </param> <param> name=LipsPeriod type=int value=5 </param> <param> name=LipsShift type=int value=3 </param> <ind> color=Blue </ind> <ind> color=Red </ind> <ind> color=Lime </ind> </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtBlueBuffer[]; double ExtRedBuffer[]; double ExtLimeBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used# //---- line shifts when drawing SetIndexShift(0,JawsShift); SetIndexShift(1,TeethShift); SetIndexShift(2,LipsShift); //---- first positions skipped when drawing SetIndexDrawBegin(0,JawsShift+JawsPeriod); SetIndexDrawBegin(1,TeethShift+TeethPeriod); SetIndexDrawBegin(2,LipsShift+LipsPeriod); //---- 3 indicator buffers mapping SetIndexBuffer(0,ExtBlueBuffer); SetIndexBuffer(1,ExtRedBuffer); SetIndexBuffer(2,ExtLimeBuffer); //---- drawing settings #indicators_init# //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Bill Williams' Alligator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- main loop for(int i=0; i<limit; i++) { //---- ma_shift set to 0 because SetIndexShift called abowe ExtBlueBuffer[i]=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i); ExtRedBuffer[i]=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i); ExtLimeBuffer[i]=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i); } //---- done return(0); } //+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR description=Awesome Oscilator separate_window=1 used_buffers=3; <ind> color=Green type=DRAW_HISTOGRAM </ind> <ind> color=Red type=DRAW_HISTOGRAM </ind> </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtGreenBuffer[]; double ExtRedBuffer[]; double ExtMABuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used# //---- drawing settings #indicators_init# IndicatorDigits(5); SetIndexDrawBegin(0,34); SetIndexDrawBegin(1,34); //---- indicator buffers mapping SetIndexBuffer(0, ExtGreenBuffer); SetIndexBuffer(1, ExtRedBuffer); SetIndexBuffer(2, ExtMABuffer); //---- name for DataWindow and indicator subwindow label IndicatorShortName("AO"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Awesome Oscillator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); double prev,current; //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i<limit; i++) ExtMABuffer[i]=iMA(NULL,0,5,0,MODE_SMA,PRICE_MEDIAN,i)- iMA(NULL,0,34,0,MODE_SMA,PRICE_MEDIAN,i); //---- dispatch values between 2 buffers bool up=true; for(i=limit-1; i>=0; i--) { current=ExtMABuffer[i]; prev=ExtMABuffer[i+1]; if(current>prev) up=true; if(current<prev) up=false; if(!up) { ExtRedBuffer[i]=current; ExtGreenBuffer[i]=0.0; } else { ExtGreenBuffer[i]=current; ExtRedBuffer[i]=0.0; } } //---- done return(0); } //+------------------------------------------------------------------+ <expert> type=EXPERT_ADVISOR </expert> #header# #property copyright "#copyright#" #property link "#link#" #extern_variables# //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---- //---- return(0); } //+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used# //---- indicators #indicators_init# //---- return(0); } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { int counted_bars=IndicatorCounted(); //---- //---- return(0); } //+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR separate_window=1 used_buffers=2 <param> type=int name=FastEMA value=12 </param> <param> type=int name=SlowEMA value=26 </param> <param> type=int name=SignalSMA value=9 </param> <ind> color=Silver type=DRAW_HISTOGRAM </ind> <ind> color=Red </ind> </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtSilverBuffer[]; double ExtRedBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used#; //---- drawing settings #indicators_init# //---- SetIndexDrawBegin(1,SignalSMA); IndicatorDigits(5); //---- indicator buffers mapping SetIndexBuffer(0, ExtSilverBuffer); SetIndexBuffer(1, ExtRedBuffer); //---- name for DataWindow and indicator subwindow label IndicatorShortName("MACD("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Moving Averages Convergence/Divergence | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st buffer for(int i=0; i<limit; i++) ExtSilverBuffer[i]=iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,i)- iMA(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,i); //---- signal line counted in the 2-nd buffer for(i=0; i<limit; i++) ExtRedBuffer[i]=iMAOnArray(ExtSilverBuffer,Bars,SignalSMA,0,MODE_SMA,i); //---- done return(0); } //+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR separate_window=1 used_buffers=3 <param> name=FastEMA type=int value=12 </param> <param> name=SlowEMA type=int value=26 </param> <param> name=SignalSMA type=int value=9 </param> <ind> type=DRAW_HISTOGRAM color=Silver </ind> </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtSilverBuffer[]; double ExtMABuffer[]; double ExtBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used#; //---- drawing settings #indicators_init# //---- SetIndexDrawBegin(0,SignalSMA); IndicatorDigits(6); //---- indicator buffers mapping SetIndexBuffer(0,ExtSilverBuffer); SetIndexBuffer(1,ExtMABuffer); SetIndexBuffer(2,ExtBuffer); //---- name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Moving Average of Oscillator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i<limit; i++) ExtMABuffer[i]=iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,i)- iMA(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,i); //---- signal line counted in the 2-nd additional buffer for(i=0; i<limit; i++) ExtBuffer[i]=iMAOnArray(ExtMABuffer,Bars,SignalSMA,0,MODE_SMA,i); //---- main loop for(i=0; i<limit; i++) ExtSilverBuffer[i]=ExtMABuffer[i]-ExtBuffer[i]; //---- done return(0); } //+------------------------------------------------------------------+ <expert> type=SCRIPT_ADVISOR </expert> #header# #property copyright "#copyright#" #property link "#link#" #extern_variables# //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { //---- //---- return(0); } //+------------------------------------------------------------------+ Library //+------------------------------------------------------------------+ //| stdlib.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property library /* int init() { Print("Init function defined as feature sample"); } int deinit() { Print("Deinit function defined as feature sample too"); } */ //+------------------------------------------------------------------+ //| return error description | //+------------------------------------------------------------------+ string ErrorDescription(int error_code) { string error_string; //---- switch(error_code) { //---- codes returned from trade server case 0: case 1: error_string="no error"; break; case 2: error_string="common error"; break; case 3: error_string="invalid trade parameters"; break; case 4: error_string="trade server is busy"; break; case 5: error_string="old version of the client terminal"; break; case 6: error_string="no connection with trade server"; break; case 7: error_string="not enough rights"; break; case 8: error_string="too frequent requests"; break; case 9: error_string="malfunctional trade operation"; break; case 64: error_string="account disabled"; break; case 65: error_string="invalid account"; break; case 128: error_string="trade timeout"; break; case 129: error_string="invalid price"; break; case 130: error_string="invalid stops"; break; case 131: error_string="invalid trade volume"; break; case 132: error_string="market is closed"; break; case 133: error_string="trade is disabled"; break; case 134: error_string="not enough money"; break; case 135: error_string="price changed"; break; case 136: error_string="off quotes"; break; case 137: error_string="broker is busy"; break; case 138: error_string="requote"; break; case 139: error_string="order is locked"; break; case 140: error_string="long positions only allowed"; break; case 141: error_string="too many requests"; break; case 145: error_string="modification denied because order too close to market"; break; case 146: error_string="trade context is busy"; break; //---- mql4 errors case 4000: error_string="no error"; break; case 4001: error_string="wrong function pointer"; break; case 4002: error_string="array index is out of range"; break; case 4003: error_string="no memory for function call stack"; break; case 4004: error_string="recursive stack overflow"; break; case 4005: error_string="not enough stack for parameter"; break; case 4006: error_string="no memory for parameter string"; break; case 4007: error_string="no memory for temp string"; break; case 4008: error_string="not initialized string"; break; case 4009: error_string="not initialized string in array"; break; case 4010: error_string="no memory for array\' string"; break; case 4011: error_string="too long string"; break; case 4012: error_string="remainder from zero divide"; break; case 4013: error_string="zero divide"; break; case 4014: error_string="unknown command"; break; case 4015: error_string="wrong jump (never generated error)"; break; case 4016: error_string="not initialized array"; break; case 4017: error_string="dll calls are not allowed"; break; case 4018: error_string="cannot load library"; break; case 4019: error_string="cannot call function"; break; case 4020: error_string="expert function calls are not allowed"; break; case 4021: error_string="not enough memory for temp string returned from function"; break; case 4022: error_string="system is busy (never generated error)"; break; case 4050: error_string="invalid function parameters count"; break; case 4051: error_string="invalid function parameter value"; break; case 4052: error_string="string function internal error"; break; case 4053: error_string="some array error"; break; case 4054: error_string="incorrect series array using"; break; case 4055: error_string="custom indicator error"; break; case 4056: error_string="arrays are incompatible"; break; case 4057: error_string="global variables processing error"; break; case 4058: error_string="global variable not found"; break; case 4059: error_string="function is not allowed in testing mode"; break; case 4060: error_string="function is not confirmed"; break; case 4061: error_string="send mail error"; break; case 4062: error_string="string parameter expected"; break; case 4063: error_string="integer parameter expected"; break; case 4064: error_string="double parameter expected"; break; case 4065: error_string="array as parameter expected"; break; case 4066: error_string="requested history data in update state"; break; case 4099: error_string="end of file"; break; case 4100: error_string="some file error"; break; case 4101: error_string="wrong file name"; break; case 4102: error_string="too many opened files"; break; case 4103: error_string="cannot open file"; break; case 4104: error_string="incompatible access to a file"; break; case 4105: error_string="no order selected"; break; case 4106: error_string="unknown symbol"; break; case 4107: error_string="invalid price parameter for trade function"; break; case 4108: error_string="invalid ticket"; break; case 4109: error_string="trade is not allowed"; break; case 4110: error_string="longs are not allowed"; break; case 4111: error_string="shorts are not allowed"; break; case 4200: error_string="object is already exist"; break; case 4201: error_string="unknown object property"; break; case 4202: error_string="object is not exist"; break; case 4203: error_string="unknown object type"; break; case 4204: error_string="no object name"; break; case 4205: error_string="object coordinates error"; break; case 4206: error_string="no specified subwindow"; break; default: error_string="unknown error"; } //---- return(error_string); } //+------------------------------------------------------------------+ //| convert red, green and blue values to color | //+------------------------------------------------------------------+ int RGB(int red_value,int green_value,int blue_value) { //---- check parameters if(red_value<0) red_value=0; if(red_value>255) red_value=255; if(green_value<0) green_value=0; if(green_value>255) green_value=255; if(blue_value<0) blue_value=0; if(blue_value>255) blue_value=255; //---- green_value<<=8; blue_value<<=16; return(red_value+green_value+blue_value); } //+------------------------------------------------------------------+ //| right comparison of 2 doubles | //+------------------------------------------------------------------+ bool CompareDoubles(double number1,double number2) { if(NormalizeDouble(number1-number2,8)==0) return(true); else return(false); } //+------------------------------------------------------------------+ //| up to 16 digits after decimal point | //+------------------------------------------------------------------+ string DoubleToStrMorePrecision(double number,int precision) { double rem,integer,integer2; double DecimalArray[17]={ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, 100000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0, 1000000000000000.0, 10000000000000000.0 }; string intstring,remstring,retstring; bool isnegative=false; int rem2; //---- if(precision<0) precision=0; if(precision>16) precision=16; //---- double p=DecimalArray[precision]; if(number<0.0) { isnegative=true; number=-number; } integer=MathFloor(number); rem=MathRound((number-integer)*p); remstring=""; for(int i=0; i<precision; i++) { integer2=MathFloor(rem/10); rem2=NormalizeDouble(rem-integer2*10,0); remstring=rem2+remstring; rem=integer2; } //---- intstring=DoubleToStr(integer,0); if(isnegative) retstring="-"+intstring; else retstring=intstring; if(precision>0) retstring=retstring+"."+remstring; return(retstring); } //+------------------------------------------------------------------+ //| convert integer to string contained input's hexadecimal notation | //+------------------------------------------------------------------+ string IntegerToHexString(int integer_number) { string hex_string="00000000"; int value, shift=28; // Print("Parameter for IntegerHexToString is ",integer_number); //---- for(int i=0; i<8; i++) { value=(integer_number>>shift)&0x0F; if(value<10) hex_string=StringSetChar(hex_string, i, value+'0'); else hex_string=StringSetChar(hex_string, i, (value-10)+'A'); shift-=4; } //---- return(hex_string); } Indicators //+------------------------------------------------------------------+ //| CCI.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 LightSeaGreen //---- input parameters extern int CCIPeriod=14; //---- buffers double CCIBuffer[]; double RelBuffer[]; double DevBuffer[]; double MovBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 3 additional buffers are used for counting. IndicatorBuffers(4); SetIndexBuffer(1, RelBuffer); SetIndexBuffer(2, DevBuffer); SetIndexBuffer(3, MovBuffer); //---- indicator lines SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,CCIBuffer); //---- name for DataWindow and indicator subwindow label short_name="CCI("+CCIPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---- SetIndexDrawBegin(0,CCIPeriod); //---- return(0); } //+------------------------------------------------------------------+ //| Commodity Channel Index | //+------------------------------------------------------------------+ int start() { int i,k,counted_bars=IndicatorCounted(); double price,sum,mul; if(Bars<=CCIPeriod) return(0); //---- initial zero if(counted_bars<1) { for(i=1;i<=CCIPeriod;i++) CCIBuffer[Bars-i]=0.0; for(i=1;i<=CCIPeriod;i++) DevBuffer[Bars-i]=0.0; for(i=1;i<=CCIPeriod;i++) MovBuffer[Bars-i]=0.0; } //---- last counted bar will be recounted int limit=Bars-counted_bars; if(counted_bars>0) limit++; //---- moving average for(i=0; i<limit; i++) MovBuffer[i]=iMA(NULL,0,CCIPeriod,0,MODE_SMA,PRICE_TYPICAL,i); //---- standard deviations i=Bars-CCIPeriod+1; if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1; mul=0.015/CCIPeriod; while(i>=0) { sum=0.0; k=i+CCIPeriod-1; while(k>=i) { price=(High[k]+Low[k]+Close[k])/3; sum+=MathAbs(price-MovBuffer[i]); k--; } DevBuffer[i]=sum*mul; i--; } i=Bars-CCIPeriod+1; if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1; while(i>=0) { price=(High[i]+Low[i]+Close[i])/3; RelBuffer[i]=price-MovBuffer[i]; i--; } //---- cci counting i=Bars-CCIPeriod+1; if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1; while(i>=0) { if(DevBuffer[i]==0.0) CCIBuffer[i]=0.0; else CCIBuffer[i]=RelBuffer[i]/DevBuffer[i]; i--; } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Ichimoku.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_chart_window #property indicator_buffers 7 #property indicator_color1 Red #property indicator_color2 Blue #property indicator_color3 SandyBrown #property indicator_color4 Thistle #property indicator_color5 Lime #property indicator_color6 SandyBrown #property indicator_color7 Thistle //---- input parameters extern int Tenkan=9; extern int Kijun=26; extern int Senkou=52; //---- buffers double Tenkan_Buffer[]; double Kijun_Buffer[]; double SpanA_Buffer[]; double SpanB_Buffer[]; double Chinkou_Buffer[]; double SpanA2_Buffer[]; double SpanB2_Buffer[]; //---- int a_begin; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,Tenkan_Buffer); SetIndexDrawBegin(0,Tenkan-1); SetIndexLabel(0,"Tenkan Sen"); //---- SetIndexStyle(1,DRAW_LINE); SetIndexBuffer(1,Kijun_Buffer); SetIndexDrawBegin(1,Kijun-1); SetIndexLabel(1,"Kijun Sen"); //---- a_begin=Kijun; if(a_begin<Tenkan) a_begin=Tenkan; SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_DOT); SetIndexBuffer(2,SpanA_Buffer); SetIndexDrawBegin(2,Kijun+a_begin-1); SetIndexShift(2,Kijun); SetIndexLabel(2,NULL); SetIndexStyle(5,DRAW_LINE,STYLE_DOT); SetIndexBuffer(5,SpanA2_Buffer); SetIndexDrawBegin(5,Kijun+a_begin-1); SetIndexShift(5,Kijun); SetIndexLabel(5,"Senkou Span A"); //---- SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_DOT); SetIndexBuffer(3,SpanB_Buffer); SetIndexDrawBegin(3,Kijun+Senkou-1); SetIndexShift(3,Kijun); SetIndexLabel(3,NULL); SetIndexStyle(6,DRAW_LINE,STYLE_DOT); SetIndexBuffer(6,SpanB2_Buffer); SetIndexDrawBegin(6,Kijun+Senkou-1); SetIndexShift(6,Kijun); SetIndexLabel(6,"Senkou Span B"); //---- SetIndexStyle(4,DRAW_LINE); SetIndexBuffer(4,Chinkou_Buffer); SetIndexShift(4,-Kijun); SetIndexLabel(4,"Chinkou Span"); //---- return(0); } //+------------------------------------------------------------------+ //| Ichimoku Kinko Hyo | //+------------------------------------------------------------------+ int start() { int i,k; int counted_bars=IndicatorCounted(); double high,low,price; //---- if(Bars<=Tenkan || Bars<=Kijun || Bars<=Senkou) return(0); //---- initial zero if(counted_bars<1) { for(i=1;i<=Tenkan;i++) Tenkan_Buffer[Bars-i]=0; for(i=1;i<=Kijun;i++) Kijun_Buffer[Bars-i]=0; for(i=1;i<=a_begin;i++) { SpanA_Buffer[Bars-i]=0; SpanA2_Buffer[Bars-i]=0; } for(i=1;i<=Senkou;i++) { SpanB_Buffer[Bars-i]=0; SpanB2_Buffer[Bars-i]=0; } } //---- Tenkan Sen i=Bars-Tenkan; if(counted_bars>Tenkan) i=Bars-counted_bars-1; while(i>=0) { high=High[i]; low=Low[i]; k=i-1+Tenkan; while(k>=i) { price=High[k]; if(high<price) high=price; price=Low[k]; if(low>price) low=price; k--; } Tenkan_Buffer[i]=(high+low)/2; i--; } //---- Kijun Sen i=Bars-Kijun; if(counted_bars>Kijun) i=Bars-counted_bars-1; while(i>=0) { high=High[i]; low=Low[i]; k=i-1+Kijun; while(k>=i) { price=High[k]; if(high<price) high=price; price=Low[k]; if(low>price) low=price; k--; } Kijun_Buffer[i]=(high+low)/2; i--; } //---- Senkou Span A i=Bars-a_begin+1; if(counted_bars>a_begin-1) i=Bars-counted_bars-1; while(i>=0) { price=(Kijun_Buffer[i]+Tenkan_Buffer[i])/2; SpanA_Buffer[i]=price; SpanA2_Buffer[i]=price; i--; } //---- Senkou Span B i=Bars-Senkou; if(counted_bars>Senkou) i=Bars-counted_bars-1; while(i>=0) { high=High[i]; low=Low[i]; k=i-1+Senkou; while(k>=i) { price=High[k]; if(high<price) high=price; price=Low[k]; if(low>price) low=price; k--; } price=(high+low)/2; SpanB_Buffer[i]=price; SpanB2_Buffer[i]=price; i--; } //---- Chinkou Span i=Bars-1; if(counted_bars>1) i=Bars-counted_bars-1; while(i>=0) { Chinkou_Buffer[i]=Close[i]; i--; } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Custom MACD.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" //---- indicator settings #property indicator_separate_window #property indicator_buffers 2 #property indicator_color1 Silver #property indicator_color2 Red //---- indicator parameters extern int FastEMA=12; extern int SlowEMA=26; extern int SignalSMA=9; //---- indicator buffers double ind_buffer1[]; double ind_buffer2[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- drawing settings SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3); SetIndexDrawBegin(1,SignalSMA); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+1); //---- indicator buffers mapping if(!SetIndexBuffer(0,ind_buffer1) && !SetIndexBuffer(1,ind_buffer2)) Print("cannot set indicator buffers!"); //---- name for DataWindow and indicator subwindow label IndicatorShortName("MACD("+FastEMA+","+SlowEMA+","+SignalSMA+")"); SetIndexLabel(0,"MACD"); SetIndexLabel(1,"Signal"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Moving Averages Convergence/Divergence | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st buffer for(int i=0; i<limit; i++) ind_buffer1[i]=iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,i)- iMA(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,i); //---- signal line counted in the 2-nd buffer for(i=0; i<limit; i++) ind_buffer2[i]=iMAOnArray(ind_buffer1,Bars,SignalSMA,0,MODE_SMA,i); //---- done return(0); } //+------------------------------------------------------------------+ //| Momentum.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 DodgerBlue //---- input parameters extern int MomPeriod=14; //---- buffers double MomBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- indicator line SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,MomBuffer); //---- name for DataWindow and indicator subwindow label short_name="Mom("+MomPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---- SetIndexDrawBegin(0,MomPeriod); //---- return(0); } //+------------------------------------------------------------------+ //| Momentum | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); //---- if(Bars<=MomPeriod) return(0); //---- initial zero if(counted_bars<1) for(i=1;i<=MomPeriod;i++) MomBuffer[Bars-i]=0.0; //---- i=Bars-MomPeriod-1; if(counted_bars>=MomPeriod) i=Bars-counted_bars-1; while(i>=0) { MomBuffer[i]=Close[i]*100/Close[i+MomPeriod]; i--; } return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Custom Moving Average.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Red //---- indicator parameters extern int MA_Period=13; extern int MA_Shift=0; extern int MA_Method=0; //---- indicator buffers double ExtMapBuffer[]; //---- int ExtCountedBars=0; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { int draw_begin; string short_name; //---- drawing settings SetIndexStyle(0,DRAW_LINE); SetIndexShift(0,MA_Shift); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)); if(MA_Period<2) MA_Period=13; draw_begin=MA_Period-1; //---- indicator short name switch(MA_Method) { case 1 : short_name="EMA("; draw_begin=0; break; case 2 : short_name="SMMA("; break; case 3 : short_name="LWMA("; break; default : MA_Method=0; short_name="SMA("; } IndicatorShortName(short_name+MA_Period+")"); SetIndexDrawBegin(0,draw_begin); //---- indicator buffers mapping SetIndexBuffer(0,ExtMapBuffer); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { if(Bars<=MA_Period) return(0); ExtCountedBars=IndicatorCounted(); //---- check for possible errors if (ExtCountedBars<0) return(-1); //---- last counted bar will be recounted if (ExtCountedBars>0) ExtCountedBars--; //---- switch(MA_Method) { case 0 : sma(); break; case 1 : ema(); break; case 2 : smma(); break; case 3 : lwma(); } //---- done return(0); } //+------------------------------------------------------------------+ //| Simple Moving Average | //+------------------------------------------------------------------+ void sma() { double sum=0; int i,pos=Bars-ExtCountedBars-1; //---- initial accumulation if(pos<MA_Period) pos=MA_Period; for(i=1;i<MA_Period;i++,pos--) sum+=Close[pos]; //---- main calculation loop while(pos>=0) { sum+=Close[pos]; ExtMapBuffer[pos]=sum/MA_Period; sum-=Close[pos+MA_Period-1]; pos--; } //---- zero initial bars if(ExtCountedBars<1) for(i=1;i<MA_Period;i++) ExtMapBuffer[Bars-i]=0; } //+------------------------------------------------------------------+ //| Exponential Moving Average | //+------------------------------------------------------------------+ void ema() { double pr=2.0/(MA_Period+1); int pos=Bars-2; if(ExtCountedBars>2) pos=Bars-ExtCountedBars-1; //---- main calculation loop while(pos>=0) { if(pos==Bars-2) ExtMapBuffer[pos+1]=Close[pos+1]; ExtMapBuffer[pos]=Close[pos]*pr+ExtMapBuffer[pos+1]*(1-pr); pos--; } } //+------------------------------------------------------------------+ //| Smoothed Moving Average | //+------------------------------------------------------------------+ void smma() { double sum=0; int i,k,pos=Bars-ExtCountedBars+1; //---- main calculation loop pos=Bars-MA_Period; if(pos>Bars-ExtCountedBars) pos=Bars-ExtCountedBars; while(pos>=0) { if(pos==Bars-MA_Period) { //---- initial accumulation for(i=0,k=pos;i<MA_Period;i++,k++) { sum+=Close[k]; //---- zero initial bars ExtMapBuffer[k]=0; } } else sum=ExtMapBuffer[pos+1]*(MA_Period-1)+Close[pos]; ExtMapBuffer[pos]=sum/MA_Period; pos--; } } //+------------------------------------------------------------------+ //| Linear Weighted Moving Average | //+------------------------------------------------------------------+ void lwma() { double sum=0.0,lsum=0.0; double price; int i,weight=0,pos=Bars-ExtCountedBars-1; //---- initial accumulation if(pos<MA_Period) pos=MA_Period; for(i=1;i<=MA_Period;i++,pos--) { price=Close[pos]; sum+=price*i; lsum+=price; weight+=i; } //---- main calculation loop pos++; i=pos+MA_Period; while(pos>=0) { ExtMapBuffer[pos]=sum/weight; if(pos==0) break; pos--; i--; price=Close[pos]; sum=sum-lsum+price*MA_Period; lsum-=Close[i]; lsum+=price; } //---- zero initial bars if(ExtCountedBars<1) for(i=1;i<MA_Period;i++) ExtMapBuffer[Bars-i]=0; } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| OsMA.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" //---- indicator settings #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- indicator parameters extern int FastEMA=12; extern int SlowEMA=26; extern int SignalSMA=9; //---- indicator buffers double ind_buffer1[]; double ind_buffer2[]; double ind_buffer3[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- 2 additional buffers are used for counting. IndicatorBuffers(3); //---- drawing settings SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3); SetIndexDrawBegin(0,SignalSMA); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2); //---- 3 indicator buffers mapping if(!SetIndexBuffer(0,ind_buffer1) && !SetIndexBuffer(1,ind_buffer2) && !SetIndexBuffer(2,ind_buffer3)) Print("cannot set indicator buffers!"); //---- name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Moving Average of Oscillator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i<limit; i++) ind_buffer2[i]=iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,i)- iMA(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,i); //---- signal line counted in the 2-nd additional buffer for(i=0; i<limit; i++) ind_buffer3[i]=iMAOnArray(ind_buffer2,Bars,SignalSMA,0,MODE_SMA,i); //---- main loop for(i=0; i<limit; i++) ind_buffer1[i]=ind_buffer2[i]-ind_buffer3[i]; //---- done return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Parabolic.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Lime //---- input parameters extern double Step=0.02; extern double Maximum=0.2; //---- buffers double SarBuffer[]; //---- int save_lastreverse; bool save_dirlong; double save_start; double save_last_high; double save_last_low; double save_ep; double save_sar; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- indicators IndicatorDigits(Digits); SetIndexStyle(0,DRAW_ARROW); SetIndexArrow(0,159); SetIndexBuffer(0,SarBuffer); //---- return(0); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void SaveLastReverse(int last,int dir,double start,double low,double high,double ep,double sar) { save_lastreverse=last; save_dirlong=dir; save_start=start; save_last_low=low; save_last_high=high; save_ep=ep; save_sar=sar; } //+------------------------------------------------------------------+ //| Parabolic Sell And Reverse system | //+------------------------------------------------------------------+ int start() { static bool first=true; bool dirlong; double start,last_high,last_low; double ep,sar,price_low,price_high,price; int i,counted_bars=IndicatorCounted(); //---- if(Bars<3) return(0); //---- initial settings i=Bars-2; if(counted_bars==0 || first) { first=false; dirlong=true; start=Step; last_high=-10000000.0; last_low=10000000.0; while(i>0) { save_lastreverse=i; price_low=Low[i]; if(last_low>price_low) last_low=price_low; price_high=High[i]; if(last_high<price_high) last_high=price_high; if(price_high>High[i+1] && price_low>Low[i+1]) break; if(price_high<High[i+1] && price_low<Low[i+1]) { dirlong=false; break; } i--; } //---- initial zero int k=i; while(k<Bars) { SarBuffer[k]=0.0; k++; } //---- check further if(dirlong) { SarBuffer[i]=Low[i+1]; ep=High[i]; } else { SarBuffer[i]=High[i+1]; ep=Low[i]; } i--; } else { i=save_lastreverse+1; start=save_start; dirlong=save_dirlong; last_high=save_last_high; last_low=save_last_low; ep=save_ep; sar=save_sar; } //---- while(i>=0) { price_low=Low[i]; price_high=High[i]; //--- check for reverse if(dirlong && price_low<SarBuffer[i+1]) { SaveLastReverse(i,true,start,price_low,last_high,ep,sar); start=Step; dirlong=false; ep=price_low; last_low=price_low; SarBuffer[i]=last_high; i--; continue; } if(!dirlong && price_high>SarBuffer[i+1]) { SaveLastReverse(i,false,start,last_low,price_high,ep,sar); start=Step; dirlong=true; ep=price_high; last_high=price_high; SarBuffer[i]=last_low; i--; continue; } //--- price=SarBuffer[i+1]; sar=price+start*(ep-price); if(dirlong) { if(ep<price_high && (start+Step)<=Maximum) start+=Step; if(price_high<High[i+1] && i==Bars-2) sar=SarBuffer[i+1]; price=Low[i+1]; if(sar>price) sar=price; price=Low[i+2]; if(sar>price) sar=price; if(sar>price_low) { SaveLastReverse(i,true,start,price_low,last_high,ep,sar); start=Step; dirlong=false; ep=price_low; last_low=price_low; SarBuffer[i]=last_high; i--; continue; } if(ep<price_high) { last_high=price_high; ep=price_high; } } else { if(ep>price_low && (start+Step)<=Maximum) start+=Step; if(price_low<Low[i+1] && i==Bars-2) sar=SarBuffer[i+1]; price=High[i+1]; if(sar<price) sar=price; price=High[i+2]; if(sar<price) sar=price; if(sar<price_high) { SaveLastReverse(i,false,start,last_low,price_high,ep,sar); start=Step; dirlong=true; ep=price_high; last_high=price_high; SarBuffer[i]=last_low; i--; continue; } if(ep>price_low) { last_low=price_low; ep=price_low; } } SarBuffer[i]=sar; i--; } // sar=SarBuffer[0]; // price=iSAR(NULL,0,Step,Maximum,0); // if(sar!=price) Print("custom=",sar," SAR=",price," counted=",counted_bars); // if(sar==price) Print("custom=",sar," SAR=",price," counted=",counted_bars); //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| RSI.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_minimum 0 #property indicator_maximum 100 #property indicator_buffers 1 #property indicator_color1 DodgerBlue //---- input parameters extern int RSIPeriod=14; //---- buffers double RSIBuffer[]; double PosBuffer[]; double NegBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 2 additional buffers are used for counting. IndicatorBuffers(3); SetIndexBuffer(1,PosBuffer); SetIndexBuffer(2,NegBuffer); //---- indicator line SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,RSIBuffer); //---- name for DataWindow and indicator subwindow label short_name="RSI("+RSIPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---- SetIndexDrawBegin(0,RSIPeriod); //---- return(0); } //+------------------------------------------------------------------+ //| Relative Strength Index | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); double rel,negative,positive; //---- if(Bars<=RSIPeriod) return(0); //---- initial zero if(counted_bars<1) for(i=1;i<=RSIPeriod;i++) RSIBuffer[Bars-i]=0.0; //---- i=Bars-RSIPeriod-1; if(counted_bars>=RSIPeriod) i=Bars-counted_bars-1; while(i>=0) { double sumn=0.0,sump=0.0; if(i==Bars-RSIPeriod-1) { int k=Bars-2; //---- initial accumulation while(k>=i) { rel=Close[k]-Close[k+1]; if(rel>0) sump+=rel; else sumn-=rel; k--; } positive=sump/RSIPeriod; negative=sumn/RSIPeriod; } else { //---- smoothed moving average rel=Close[i]-Close[i+1]; if(rel>0) sump=rel; else sumn=-rel; positive=(PosBuffer[i+1]*(RSIPeriod-1)+sump)/RSIPeriod; negative=(NegBuffer[i+1]*(RSIPeriod-1)+sumn)/RSIPeriod; } PosBuffer[i]=positive; NegBuffer[i]=negative; if(negative==0.0) RSIBuffer[i]=0.0; else RSIBuffer[i]=100.0-100.0/(1+positive/negative); i--; } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Stochastic.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_minimum 0 #property indicator_maximum 100 #property indicator_buffers 2 #property indicator_color1 LightSeaGreen #property indicator_color2 Red //---- input parameters extern int KPeriod=5; extern int DPeriod=3; extern int Slowing=3; //---- buffers double MainBuffer[]; double SignalBuffer[]; double HighesBuffer[]; double LowesBuffer[]; //---- int draw_begin1=0; int draw_begin2=0; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 2 additional buffers are used for counting. IndicatorBuffers(4); SetIndexBuffer(2, HighesBuffer); SetIndexBuffer(3, LowesBuffer); //---- indicator lines SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0, MainBuffer); SetIndexStyle(1,DRAW_LINE); SetIndexBuffer(1, SignalBuffer); //---- name for DataWindow and indicator subwindow label short_name="Sto("+KPeriod+","+DPeriod+","+Slowing+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); SetIndexLabel(1,"Signal"); //---- draw_begin1=KPeriod+Slowing; draw_begin2=draw_begin1+DPeriod; SetIndexDrawBegin(0,draw_begin1); SetIndexDrawBegin(1,draw_begin2); //---- return(0); } //+------------------------------------------------------------------+ //| Stochastic oscillator | //+------------------------------------------------------------------+ int start() { int i,k; int counted_bars=IndicatorCounted(); double price; //---- if(Bars<=draw_begin2) return(0); //---- initial zero if(counted_bars<1) { for(i=1;i<=draw_begin1;i++) MainBuffer[Bars-i]=0; for(i=1;i<=draw_begin2;i++) SignalBuffer[Bars-i]=0; } //---- minimums counting i=Bars-KPeriod; if(counted_bars>KPeriod) i=Bars-counted_bars-1; while(i>=0) { double min=1000000; k=i+KPeriod-1; while(k>=i) { price=Low[k]; if(min>price) min=price; k--; } LowesBuffer[i]=min; i--; } //---- maximums counting i=Bars-KPeriod; if(counted_bars>KPeriod) i=Bars-counted_bars-1; while(i>=0) { double max=-1000000; k=i+KPeriod-1; while(k>=i) { price=High[k]; if(max<price) max=price; k--; } HighesBuffer[i]=max; i--; } //---- %K line i=Bars-draw_begin1; if(counted_bars>draw_begin1) i=Bars-counted_bars-1; while(i>=0) { double sumlow=0.0; double sumhigh=0.0; for(k=(i+Slowing-1);k>=i;k--) { sumlow+=Close[k]-LowesBuffer[k]; sumhigh+=HighesBuffer[k]-LowesBuffer[k]; } if(sumhigh==0.0) MainBuffer[i]=100.0; else MainBuffer[i]=sumlow/sumhigh*100; i--; } //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; int limit=Bars-counted_bars; //---- signal line is simple movimg average for(i=0; i<limit; i++) SignalBuffer[i]=iMAOnArray(MainBuffer,Bars,DPeriod,0,MODE_SMA,i); //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Custom Moving Average.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Red //---- indicator parameters extern int ExtDepth=12; extern int ExtDeviation=5; extern int ExtBackstep=3; //---- indicator buffers double ExtMapBuffer[]; double ExtMapBuffer2[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { IndicatorBuffers(2); //---- drawing settings SetIndexStyle(0,DRAW_SECTION); //---- indicator buffers mapping SetIndexBuffer(0,ExtMapBuffer); SetIndexBuffer(1,ExtMapBuffer2); SetIndexEmptyValue(0,0.0); ArraySetAsSeries(ExtMapBuffer,true); ArraySetAsSeries(ExtMapBuffer2,true); //---- indicator short name IndicatorShortName("ZigZag("+ExtDepth+","+ExtDeviation+","+ExtBackstep+")"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { int shift, back,lasthighpos,lastlowpos; double val,res; double curlow,curhigh,lasthigh,lastlow; for(shift=Bars-ExtDepth; shift>=0; shift--) { val=Low[Lowest(NULL,0,MODE_LOW,ExtDepth,shift)]; if(val==lastlow) val=0.0; else { lastlow=val; if((Low[shift]-val)>(ExtDeviation*Point)) val=0.0; else { for(back=1; back<=ExtBackstep; back++) { res=ExtMapBuffer[shift+back]; if((res!=0)&&(res>val)) ExtMapBuffer[shift+back]=0.0; } } } ExtMapBuffer[shift]=val; //--- high val=High[Highest(NULL,0,MODE_HIGH,ExtDepth,shift)]; if(val==lasthigh) val=0.0; else { lasthigh=val; if((val-High[shift])>(ExtDeviation*Point)) val=0.0; else { for(back=1; back<=ExtBackstep; back++) { res=ExtMapBuffer2[shift+back]; if((res!=0)&&(res<val)) ExtMapBuffer2[shift+back]=0.0; } } } ExtMapBuffer2[shift]=val; } // final cutting lasthigh=-1; lasthighpos=-1; lastlow=-1; lastlowpos=-1; for(shift=Bars-ExtDepth; shift>=0; shift--) { curlow=ExtMapBuffer[shift]; curhigh=ExtMapBuffer2[shift]; if((curlow==0)&&(curhigh==0)) continue; //--- if(curhigh!=0) { if(lasthigh>0) { if(lasthigh<curhigh) ExtMapBuffer2[lasthighpos]=0; else ExtMapBuffer2[shift]=0; } //--- if(lasthigh<curhigh || lasthigh<0) { lasthigh=curhigh; lasthighpos=shift; } lastlow=-1; } //---- if(curlow!=0) { if(lastlow>0) { if(lastlow>curlow) ExtMapBuffer[lastlowpos]=0; else ExtMapBuffer[shift]=0; } //--- if((curlow<lastlow)||(lastlow<0)) { lastlow=curlow; lastlowpos=shift; } lasthigh=-1; } } for(shift=Bars-1; shift>=0; shift--) { if(shift>=Bars-ExtDepth) ExtMapBuffer[shift]=0.0; else { res=ExtMapBuffer2[shift]; if(res!=0.0) ExtMapBuffer[shift]=res; } } } //+------------------------------------------------------------------+ //| Accelerator.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" //---- indicator settings #property indicator_separate_window #property indicator_buffers 3 #property indicator_color1 Black #property indicator_color2 Green #property indicator_color3 Red //---- indicator buffers double ExtBuffer0[]; double ExtBuffer1[]; double ExtBuffer2[]; double ExtBuffer3[]; double ExtBuffer4[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- 2 additional buffers are used for counting. IndicatorBuffers(5); //---- drawing settings SetIndexStyle(0,DRAW_NONE); SetIndexStyle(1,DRAW_HISTOGRAM); SetIndexStyle(2,DRAW_HISTOGRAM); IndicatorDigits(Digits+2); SetIndexDrawBegin(0,38); SetIndexDrawBegin(1,38); SetIndexDrawBegin(2,38); //---- 4 indicator buffers mapping SetIndexBuffer(0,ExtBuffer0); SetIndexBuffer(1,ExtBuffer1); SetIndexBuffer(2,ExtBuffer2); SetIndexBuffer(3,ExtBuffer3); SetIndexBuffer(4,ExtBuffer4); //---- name for DataWindow and indicator subwindow label IndicatorShortName("AC"); SetIndexLabel(1,NULL); SetIndexLabel(2,NULL); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Accelerator/Decelerator Oscillator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); double prev,current; //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i<limit; i++) ExtBuffer3[i]=iMA(NULL,0,5,0,MODE_SMA,PRICE_MEDIAN,i)- iMA(NULL,0,34,0,MODE_SMA,PRICE_MEDIAN,i); //---- signal line counted in the 2-nd additional buffer for(i=0; i<limit; i++) ExtBuffer4[i]=iMAOnArray(ExtBuffer3,Bars,5,0,MODE_SMA,i); //---- dispatch values between 2 buffers bool up=true; for(i=limit-1; i>=0; i--) { current=ExtBuffer3[i]-ExtBuffer4[i]; prev=ExtBuffer3[i+1]-ExtBuffer4[i+1]; if(current>prev) up=true; if(current<prev) up=false; if(!up) { ExtBuffer2[i]=current; ExtBuffer1[i]=0.0; } else { ExtBuffer1[i]=current; ExtBuffer2[i]=0.0; } ExtBuffer0[i]=current; } //---- done return(0); } //+------------------------------------------------------------------+ //| ADX.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_buffers 3 #property indicator_color1 LightSeaGreen #property indicator_color2 YellowGreen #property indicator_color3 Wheat //---- input parameters extern int ADXPeriod=14; //---- buffers double ADXBuffer[]; double PlusDiBuffer[]; double MinusDiBuffer[]; double PlusSdiBuffer[]; double MinusSdiBuffer[]; double TempBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- 3 additional buffers are used for counting. IndicatorBuffers(6); //---- indicator buffers SetIndexBuffer(0,ADXBuffer); SetIndexBuffer(1,PlusDiBuffer); SetIndexBuffer(2,MinusDiBuffer); SetIndexBuffer(3,PlusSdiBuffer); SetIndexBuffer(4,MinusSdiBuffer); SetIndexBuffer(5,TempBuffer); //---- name for DataWindow and indicator subwindow label IndicatorShortName("ADX("+ADXPeriod+")"); SetIndexLabel(0,"ADX"); SetIndexLabel(1,"+DI"); SetIndexLabel(2,"-DI"); //---- SetIndexDrawBegin(0,ADXPeriod); SetIndexDrawBegin(1,ADXPeriod); SetIndexDrawBegin(2,ADXPeriod); //---- return(0); } //+------------------------------------------------------------------+ //| Average Directional Movement Index | //+------------------------------------------------------------------+ int start() { double pdm,mdm,tr; double price_high,price_low; int starti,i,counted_bars=IndicatorCounted(); //---- i=Bars-2; PlusSdiBuffer[i+1]=0; MinusSdiBuffer[i+1]=0; if(counted_bars>=i) i=Bars-counted_bars-1; starti=i; //---- while(i>=0) { price_low=Low[i]; price_high=High[i]; //---- pdm=price_high-High[i+1]; mdm=Low[i+1]-price_low; if(pdm<0) pdm=0; // +DM if(mdm<0) mdm=0; // -DM if(pdm==mdm) { pdm=0; mdm=0; } else if(pdm<mdm) pdm=0; else if(mdm<pdm) mdm=0; //---- âû÷èñëÿåì èñòèííûé èíòåðâàë double num1=MathAbs(price_high-price_low); double num2=MathAbs(price_high-Close[i+1]); double num3=MathAbs(price_low-Close[i+1]); tr=MathMax(num1,num2); tr=MathMax(tr,num3); //---- counting plus/minus direction if(tr==0) { PlusSdiBuffer[i]=0; MinusSdiBuffer[i]=0; } else { PlusSdiBuffer[i]=100.0*pdm/tr; MinusSdiBuffer[i]=100.0*mdm/tr; } //---- i--; } //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; int limit=Bars-counted_bars; //---- apply EMA to +DI for(i=0; i<=limit; i++) PlusDiBuffer[i]=iMAOnArray(PlusSdiBuffer,Bars,ADXPeriod,0,MODE_EMA,i); //---- apply EMA to -DI for(i=0; i<=limit; i++) MinusDiBuffer[i]=iMAOnArray(MinusSdiBuffer,Bars,ADXPeriod,0,MODE_EMA,i); //---- Directional Movement (DX) i=Bars-2; TempBuffer[i+1]=0; i=starti; while(i>=0) { double div=MathAbs(PlusDiBuffer[i]+MinusDiBuffer[i]); if(div==0.00) TempBuffer[i]=0; else TempBuffer[i]=100*(MathAbs(PlusDiBuffer[i]-MinusDiBuffer[i])/div); i--; } //---- ADX is exponential moving average on DX for(i=0; i<limit; i++) ADXBuffer[i]=iMAOnArray(TempBuffer,Bars,ADXPeriod,0,MODE_EMA,i); //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Alligator.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_chart_window #property indicator_buffers 3 #property indicator_color1 Blue #property indicator_color2 Red #property indicator_color3 Lime //---- input parameters extern int JawsPeriod=13; extern int JawsShift=8; extern int TeethPeriod=8; extern int TeethShift=5; extern int LipsPeriod=5; extern int LipsShift=3; //---- indicator buffers double ExtBlueBuffer[]; double ExtRedBuffer[]; double ExtLimeBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- line shifts when drawing SetIndexShift(0,JawsShift); SetIndexShift(1,TeethShift); SetIndexShift(2,LipsShift); //---- first positions skipped when drawing SetIndexDrawBegin(0,JawsShift+JawsPeriod); SetIndexDrawBegin(1,TeethShift+TeethPeriod); SetIndexDrawBegin(2,LipsShift+LipsPeriod); //---- 3 indicator buffers mapping SetIndexBuffer(0,ExtBlueBuffer); SetIndexBuffer(1,ExtRedBuffer); SetIndexBuffer(2,ExtLimeBuffer); //---- drawing settings SetIndexStyle(0,DRAW_LINE); SetIndexStyle(1,DRAW_LINE); SetIndexStyle(2,DRAW_LINE); //---- index labels SetIndexLabel(0,"Gator Jaws"); SetIndexLabel(1,"Gator Teeth"); SetIndexLabel(2,"Gator Lips"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Bill Williams' Alligator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- main loop for(int i=0; i<limit; i++) { //---- ma_shift set to 0 because SetIndexShift called abowe ExtBlueBuffer[i]=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i); ExtRedBuffer[i]=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i); ExtLimeBuffer[i]=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i); } //---- done return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Awesome.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" //---- indicator settings #property indicator_separate_window #property indicator_buffers 3 #property indicator_color1 Black #property indicator_color2 Green #property indicator_color3 Red //---- indicator buffers double ExtBuffer0[]; double ExtBuffer1[]; double ExtBuffer2[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- drawing settings SetIndexStyle(0,DRAW_NONE); SetIndexStyle(1,DRAW_HISTOGRAM); SetIndexStyle(2,DRAW_HISTOGRAM); IndicatorDigits(Digits+1); SetIndexDrawBegin(0,34); SetIndexDrawBegin(1,34); SetIndexDrawBegin(2,34); //---- 3 indicator buffers mapping SetIndexBuffer(0,ExtBuffer0); SetIndexBuffer(1,ExtBuffer1); SetIndexBuffer(2,ExtBuffer2); //---- name for DataWindow and indicator subwindow label IndicatorShortName("AO"); SetIndexLabel(1,NULL); SetIndexLabel(2,NULL); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Awesome Oscillator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); double prev,current; //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd for(int i=0; i<limit; i++) ExtBuffer0[i]=iMA(NULL,0,5,0,MODE_SMA,PRICE_MEDIAN,i)- iMA(NULL,0,34,0,MODE_SMA,PRICE_MEDIAN,i); //---- dispatch values between 2 buffers bool up=true; for(i=limit-1; i>=0; i--) { current=ExtBuffer0[i]; prev=ExtBuffer0[i+1]; if(current>prev) up=true; if(current<prev) up=false; if(!up) { ExtBuffer2[i]=current; ExtBuffer1[i]=0.0; } else { ExtBuffer1[i]=current; ExtBuffer2[i]=0.0; } } //---- done return(0); } Samples Includes #import "ExpertSample.dll" int GetIntValue(int); double GetDoubleValue(double); string GetStringValue(string); double GetArrayItemValue(double arr[],int,int); bool SetArrayItemValue(double& arr[],int,int,double); double GetRatesItemValue(double rates[][6],int,int,int); int SortStringArray(string& arr[],int); int ProcessStringArray(string& arr[],int); Samples Indicators //+------------------------------------------------------------------+ //| ATR.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 DodgerBlue //---- input parameters extern int AtrPeriod=14; //---- buffers double AtrBuffer[]; double TempBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 1 additional buffer used for counting. IndicatorBuffers(2); //---- indicator line SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,AtrBuffer); SetIndexBuffer(1,TempBuffer); //---- name for DataWindow and indicator subwindow label short_name="ATR("+AtrPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---- SetIndexDrawBegin(0,AtrPeriod); //---- return(0); } //+------------------------------------------------------------------+ //| Average True Range | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); //---- if(Bars<=AtrPeriod) return(0); //---- initial zero if(counted_bars<1) for(i=1;i<=AtrPeriod;i++) AtrBuffer[Bars-i]=0.0; //---- i=Bars-counted_bars-1; while(i>=0) { double high=High[i]; double low =Low[i]; if(i==Bars-1) TempBuffer[i]=high-low; else { double prevclose=Close[i+1]; TempBuffer[i]=MathMax(high,prevclose)-MathMin(low,prevclose); } i--; } //---- if(counted_bars>0) counted_bars--; int limit=Bars-counted_bars; for(i=0; i<limit; i++) AtrBuffer[i]=iMAOnArray(TempBuffer,Bars,AtrPeriod,0,MODE_SMA,i); //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Bands.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_chart_window #property indicator_buffers 3 #property indicator_color1 LightSeaGreen #property indicator_color2 LightSeaGreen #property indicator_color3 LightSeaGreen //---- indicator parameters extern int BandsPeriod=20; extern int BandsShift=0; extern double BandsDeviations=2.0; //---- buffers double MovingBuffer[]; double UpperBuffer[]; double LowerBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- indicators SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,MovingBuffer); SetIndexStyle(1,DRAW_LINE); SetIndexBuffer(1,UpperBuffer); SetIndexStyle(2,DRAW_LINE); SetIndexBuffer(2,LowerBuffer); //---- SetIndexDrawBegin(0,BandsPeriod+BandsShift); SetIndexDrawBegin(1,BandsPeriod+BandsShift); SetIndexDrawBegin(2,BandsPeriod+BandsShift); //---- return(0); } //+------------------------------------------------------------------+ //| Bollinger Bands | //+------------------------------------------------------------------+ int start() { int i,k,counted_bars=IndicatorCounted(); double deviation; double sum,oldval,newres; //---- if(Bars<=BandsPeriod) return(0); //---- initial zero if(counted_bars<1) for(i=1;i<=BandsPeriod;i++) { MovingBuffer[Bars-i]=EMPTY_VALUE; UpperBuffer[Bars-i]=EMPTY_VALUE; LowerBuffer[Bars-i]=EMPTY_VALUE; } //---- int limit=Bars-counted_bars; if(counted_bars>0) limit++; for(i=0; i<limit; i++) MovingBuffer[i]=iMA(NULL,0,BandsPeriod,BandsShift,MODE_SMA,PRICE_CLOSE,i); //---- i=Bars-BandsPeriod+1; if(counted_bars>BandsPeriod-1) i=Bars-counted_bars-1; while(i>=0) { sum=0.0; k=i+BandsPeriod-1; oldval=MovingBuffer[i]; while(k>=i) { newres=Close[k]-oldval; sum+=newres*newres; k--; } deviation=BandsDeviations*MathSqrt(sum/BandsPeriod);; UpperBuffer[i]=oldval+deviation; LowerBuffer[i]=oldval-deviation; i--; } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Bears.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- input parameters extern int BearsPeriod=13; //---- buffers double BearsBuffer[]; double TempBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 1 additional buffer used for counting. IndicatorBuffers(2); IndicatorDigits(Digits); //---- indicator line SetIndexStyle(0,DRAW_HISTOGRAM); SetIndexBuffer(0,BearsBuffer); SetIndexBuffer(1,TempBuffer); //---- name for DataWindow and indicator subwindow label short_name="Bears("+BearsPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---- return(0); } //+------------------------------------------------------------------+ //| Bears Power | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); //---- if(Bars<=BearsPeriod) return(0); //---- int limit=Bars-counted_bars; if(counted_bars>0) limit++; for(i=0; i<limit; i++) TempBuffer[i]=iMA(NULL,0,BearsPeriod,0,MODE_EMA,PRICE_CLOSE,i); //---- i=Bars-counted_bars-1; while(i>=0) { BearsBuffer[i]=Low[i]-TempBuffer[i]; i--; } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Bulls.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- input parameters extern int BullsPeriod=13; //---- buffers double BullsBuffer[]; double TempBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 1 additional buffer used for counting. IndicatorBuffers(2); IndicatorDigits(Digits); //---- indicator line SetIndexStyle(0,DRAW_HISTOGRAM); SetIndexBuffer(0,BullsBuffer); SetIndexBuffer(1,TempBuffer); //---- name for DataWindow and indicator subwindow label short_name="Bulls("+BullsPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---- return(0); } //+------------------------------------------------------------------+ //| Bulls Power | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); //---- if(Bars<=BullsPeriod) return(0); //---- int limit=Bars-counted_bars; if(counted_bars>0) limit++; for(i=0; i<limit; i++) TempBuffer[i]=iMA(NULL,0,BullsPeriod,0,MODE_EMA,PRICE_CLOSE,i); //---- i=Bars-counted_bars-1; while(i>=0) { BullsBuffer[i]=High[i]-TempBuffer[i]; i--; } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Heiken Ashi.mq4 | //| Copyright c 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net | //+------------------------------------------------------------------+ //| For Heiken Ashi we recommend next chart settings ( press F8 or | //| select on menu 'Charts'->'Properties...'): | //| - On 'Color' Tab select 'Black' for 'Line Graph' | //| - On 'Common' Tab disable 'Chart on Foreground' checkbox and | //| select 'Line Chart' radiobutton | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net" #property indicator_chart_window #property indicator_buffers 4 #property indicator_color1 Red #property indicator_color2 White #property indicator_color3 Red #property indicator_color4 White //---- buffers double ExtMapBuffer1[]; double ExtMapBuffer2[]; double ExtMapBuffer3[]; double ExtMapBuffer4[]; //---- int ExtCountedBars=0; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //|------------------------------------------------------------------| int init() { //---- indicators SetIndexStyle(0,DRAW_HISTOGRAM, 0, 1, Red); SetIndexBuffer(0, ExtMapBuffer1); SetIndexStyle(1,DRAW_HISTOGRAM, 0, 1, White); SetIndexBuffer(1, ExtMapBuffer2); SetIndexStyle(2,DRAW_HISTOGRAM, 0, 3, Red); SetIndexBuffer(2, ExtMapBuffer3); SetIndexStyle(3,DRAW_HISTOGRAM, 0, 3, White); SetIndexBuffer(3, ExtMapBuffer4); //---- SetIndexDrawBegin(0,10); SetIndexDrawBegin(1,10); SetIndexDrawBegin(2,10); SetIndexDrawBegin(3,10); //---- indicator buffers mapping SetIndexBuffer(0,ExtMapBuffer1); SetIndexBuffer(1,ExtMapBuffer2); SetIndexBuffer(2,ExtMapBuffer3); SetIndexBuffer(3,ExtMapBuffer4); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Custom indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- TODO: add your code here //---- return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { double haOpen, haHigh, haLow, haClose; if(Bars<=10) return(0); ExtCountedBars=IndicatorCounted(); //---- check for possible errors if (ExtCountedBars<0) return(-1); //---- last counted bar will be recounted if (ExtCountedBars>0) ExtCountedBars--; int pos=Bars-ExtCountedBars-1; while(pos>=0) { haOpen=(ExtMapBuffer3[pos+1]+ExtMapBuffer4[pos+1])/2; haClose=(Open[pos]+High[pos]+Low[pos]+Close[pos])/4; haHigh=MathMax(High[pos], MathMax(haOpen, haClose)); haLow=MathMin(Low[pos], MathMin(haOpen, haClose)); if (haOpen<haClose) { ExtMapBuffer1[pos]=haLow; ExtMapBuffer2[pos]=haHigh; } else { ExtMapBuffer1[pos]=haHigh; ExtMapBuffer2[pos]=haLow; } ExtMapBuffer3[pos]=haOpen; ExtMapBuffer4[pos]=haClose; pos--; } //---- return(0); } //+------------------------------------------------------------------+ Samples Scripts //+------------------------------------------------------------------+ //| close.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "close first market order if it is first in the list" | //+------------------------------------------------------------------+ int start() { bool result; double price; int cmd,error; //---- if(OrderSelect(0,SELECT_BY_POS,MODE_TRADES)) { cmd=OrderType(); //---- first order is buy or sell if(cmd==OP_BUY || cmd==OP_SELL) { while(true) { if(cmd==OP_BUY) price=Bid; else price=Ask; result=OrderClose(OrderTicket(),OrderLots(),price,3,CLR_NONE); if(result!=TRUE) { error=GetLastError(); Print("LastError = ",error); } else error=0; if(error==135) RefreshRates(); else break; } } } else Print( "Error when order select ", GetLastError()); //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| delete_pending.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "delete first pending order" | //+------------------------------------------------------------------+ int start() { bool result; int cmd,total; //---- total=OrdersTotal(); //---- for(int i=0; i<total; i++) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) { cmd=OrderType(); //---- pending orders only are considered if(cmd!=OP_BUY && cmd!=OP_SELL) { //---- print selected order OrderPrint(); //---- delete first pending order result=OrderDelete(OrderTicket()); if(result!=TRUE) Print("LastError = ", GetLastError()); break; } } else { Print( "Error when order select ", GetLastError()); break; } } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| modify.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "modify first market order" | //+------------------------------------------------------------------+ int start() { bool result; double stop_loss,point; int cmd,total; //---- total=OrdersTotal(); point=MarketInfo(Symbol(),MODE_POINT); //---- for(int i=0; i<total; i++) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) { //---- print selected order OrderPrint(); cmd=OrderType(); //---- buy or sell orders are considered if(cmd==OP_BUY || cmd==OP_SELL) { //---- modify first market order while(true) { if(cmd==OP_BUY) stop_loss=Bid-20*point; else stop_loss=Ask+20*point; result=OrderModify(OrderTicket(),0,stop_loss,0,0,CLR_NONE); if(result!=TRUE) Print("LastError = ", GetLastError()); if(result==135) RefreshRates(); else break; } //---- print modified order (it still selected after modify) OrderPrint(); break; } } else { Print( "Error when order select ", GetLastError()); break; } } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| modify_pending.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "modify first pending order" | //+------------------------------------------------------------------+ int start() { bool result; double price,point; int cmd,total; int expiration; //---- total=OrdersTotal(); point=MarketInfo(Symbol(),MODE_POINT); //---- for(int i=0; i<total; i++) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) { cmd=OrderType(); //---- pending orders only are considered if(cmd!=OP_BUY && cmd!=OP_SELL) { //---- print selected order OrderPrint(); //---- modify first pending order price=OrderOpenPrice()-10*point; expiration=OrderExpiration(); result=OrderModify(OrderTicket(),price,0,0,expiration,CLR_NONE); if(result!=TRUE) Print("LastError = ", GetLastError()); //---- print modified order (it still selected after modify) else OrderPrint(); break; } } else { Print( "Error when order select ", GetLastError()); break; } } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| rotate_text.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #include <stdlib.mqh> string line_name="rotating_line"; string object_name1="rotating_text"; void init() { Print("point = ", Point," bars=",Bars); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void deinit() { ObjectDelete(line_name); ObjectDelete(object_name1); ObjectsRedraw(); } //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { int time2; int error,index,fontsize=10; double price,price1,price2; double angle=0.0; //---- price2=High[10]+Point*10; ObjectCreate(line_name, OBJ_TRENDBYANGLE, 0, Time[10], price2); index=20; ObjectCreate(object_name1, OBJ_TEXT, 0, Time[index], Low[index]-Point*100); ObjectSetText(object_name1, "rotating_text", fontsize); while(IsStopped()==false) { index++; price=ObjectGet(object_name1, OBJPROP_PRICE1)+Point; error=GetLastError(); if(error!=0) { Print(object_name1," : ",ErrorDescription(error)); break; } ObjectMove(object_name1, 0, Time[index], price); ObjectSet(object_name1, OBJPROP_ANGLE, angle*2); ObjectSet(object_name1, OBJPROP_FONTSIZE, fontsize); ObjectSet(line_name, OBJPROP_WIDTH, angle/18.0); double line_angle=360.0-angle; if(line_angle==90.0) ObjectSet(line_name, OBJPROP_PRICE2, price2+Point*50); if(line_angle==270.0) ObjectSet(line_name, OBJPROP_PRICE2, price2-Point*50); time2=ObjectGet(line_name,OBJPROP_TIME2); if(line_angle>90.0 && line_angle<270.0) time2=Time[index+10]; else time2=Time[0]; ObjectSet(line_name, OBJPROP_TIME2, time2); ObjectSet(line_name, OBJPROP_ANGLE, line_angle); ObjectsRedraw(); angle+=3.0; if(angle>=360.0) angle=360.0-angle; fontsize++; if(fontsize>48) fontsize=6; Sleep(500); price1=ObjectGetValueByShift(line_name, index); if(GetLastError()==0) { if(MathAbs(price1-price) < Point*50) { Print("price=",price," price1=", price1); ObjectSetText(object_name1, "REMOVED", 48, "Arial", RGB(255,215,0)); ObjectsRedraw(); Sleep(5000); // ObjectDelete(object_name1); } } } return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| send_pending.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "send pending order with expiration data" | //+------------------------------------------------------------------+ int start() { int ticket,expiration; double point; //---- point=MarketInfo(Symbol(),MODE_POINT); expiration=CurTime()+PERIOD_D1*60; //---- while(true) { ticket=OrderSend(Symbol(),OP_SELLSTOP,1.0,Bid-100*point,0,0,0,"some comment",16384,expiration,Green); if(ticket<=0) Print("Error = ",GetLastError()); else { Print("ticket = ",ticket); break; } //---- 10 seconds wait Sleep(10000); } //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| trade.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #include <stdlib.mqh> #include <WinUser32.mqh> //+------------------------------------------------------------------+ //| script "trading for all money" | //+------------------------------------------------------------------+ int start() { //---- if(MessageBox("Do you really want to BUY 1.00 "+Symbol()+" at ASK price? ", "Script",MB_YESNO|MB_ICONQUESTION)!=IDYES) return(1); //---- int ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE); if(ticket<1) { int error=GetLastError(); Print("Error = ",ErrorDescription(error)); return; } //---- OrderPrint(); return(0); } //+------------------------------------------------------------------+ Samples Program //+------------------------------------------------------------------+ //| ExportFunctions.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #include <sampledll.mqh> #define TIME_INDEX 0 #define OPEN_INDEX 1 #define LOW_INDEX 2 #define HIGH_INDEX 3 #define CLOSE_INDEX 4 #define VOLUME_INDEX 5 //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { double ret,some_value=10.5; string sret; int cnt; string strarray[6]={ "first", "second", "third", "fourth", "fifth" }; //---- simple dll-functions call cnt=GetIntValue(some_value); Print("Returned value is ",cnt); ret=GetDoubleValue(some_value); Print("Returned value is ",ret); sret=GetStringValue("some string"); Print("Returned value is ",sret); //---- cnt=SortStringArray(strarray,ArraySize(strarray)); for(int i=0; i<cnt; i++) Print(i," - ",strarray[i]); cnt=ProcessStringArray(strarray,ArraySize(strarray)); for(i=0; i<cnt; i++) Print(i," - ",strarray[i]); //---- return(0); } //+------------------------------------------------------------------+ //| array functions call | //+------------------------------------------------------------------+ int start() { double price; double arr[5]={1.5, 2.6, 3.7, 4.8, 5.9 }; double rates[][6]; //---- get first item from passed array price=GetArrayItemValue(arr,5,0); Print("Returned from arr[0] ",price); //---- change second item in the passed array if(SetArrayItemValue(arr,5,1,1234.5)==true) Print("Changed to ",arr[1]); //---- get current close ArrayCopyRates(rates); price=GetRatesItemValue(rates,Bars,0,CLOSE_INDEX); Print("Returned from Close ",price); //---- return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| MACD Sample.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ extern double TakeProfit = 50; extern double Lots = 0.1; extern double TrailingStop = 30; extern double MACDOpenLevel=3; extern double MACDCloseLevel=2; extern double MATrendPeriod=26; //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { double MacdCurrent, MacdPrevious, SignalCurrent; double SignalPrevious, MaCurrent, MaPrevious; int cnt, ticket, total; // initial data checks // it is important to make sure that the expert works with a normal // chart and the user did not make any mistakes setting external // variables (Lots, StopLoss, TakeProfit, // TrailingStop) in our case, we check TakeProfit // on a chart of less than 100 bars if(Bars<100) { Print("bars less than 100"); return(0); } if(TakeProfit<10) { Print("TakeProfit less than 10"); return(0); // check TakeProfit } // to simplify the coding and speed up access // data are put into internal variables MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0); MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1); SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0); SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1); MaCurrent=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0); MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1); total=OrdersTotal(); if(total<1) { // no opened orders identified if(AccountFreeMargin()<(1000*Lots)) { Print("We have no money. Free Margin = ", AccountFreeMargin()); return(0); } // check for long position (BUY) possibility if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious && MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && MaCurrent>MaPrevious) { ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,"macd sample",16384,0,Green); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice()); } else Print("Error opening BUY order : ",GetLastError()); return(0); } // check for short position (SELL) possibility if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious && MacdCurrent>(MACDOpenLevel*Point) && MaCurrent<MaPrevious) { ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,"macd sample",16384,0,Red); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice()); } else Print("Error opening SELL order : ",GetLastError()); return(0); } return(0); } // it is important to enter the market correctly, // but it is more important to exit it correctly... for(cnt=0;cnt<total;cnt++) { OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if(OrderType()<=OP_SELL && // check for opened position OrderSymbol()==Symbol()) // check for symbol { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious && MacdCurrent>(MACDCloseLevel*Point)) { OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(),OrderOpenPrice(),Bid- Point*TrailingStop,OrderTakeProfit(),0,Green); return(0); } } } } else // go to short position { // should it be closed? if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious && MathAbs(MacdCurrent)>(MACDCloseLevel*Point)) { OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if((OrderOpenPrice()-Ask)>(Point*TrailingStop)) { if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) { OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop, OrderTakeProfit(),0,Red); return(0); } } } } } } return(0); } // the end. //+------------------------------------------------------------------+ //| Moving Average.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #define MAGICMA 20050610 extern double Lots = 0.1; extern double MaximumRisk = 0.02; extern double DecreaseFactor = 3; extern double MovingPeriod = 12; extern double MovingShift = 6; //+------------------------------------------------------------------+ //| Calculate open positions | //+------------------------------------------------------------------+ int CalculateCurrentOrders(string symbol) { int buys=0,sells=0; //---- for(int i=0;i<OrdersTotal();i++) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break; if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA) { if(OrderType()==OP_BUY) buys++; if(OrderType()==OP_SELL) sells++; } } //---- return orders volume if(buys>0) return(buys); else return(-sells); } //+------------------------------------------------------------------+ //| Calculate optimal lot size | //+------------------------------------------------------------------+ double LotsOptimized() { double lot=Lots; int orders=HistoryTotal(); // history orders total int losses=0; // number of losses orders without a break //---- select lot size lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1); //---- calcuulate number of losses orders without a break if(DecreaseFactor>0) { for(int i=orders-1;i>=0;i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; } if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue; //---- if(OrderProfit()>0) break; if(OrderProfit()<0) losses++; } if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1); } //---- return lot size if(lot<0.1) lot=0.1; return(lot); } //+------------------------------------------------------------------+ //| Check for open order conditions | //+------------------------------------------------------------------+ void CheckForOpen() { double ma; int res; //---- go trading only for first tiks of new bar if(Volume[0]>1) return; //---- get Moving Average ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0); //---- sell conditions if(Open[1]>ma && Close[1]<ma) { res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red); return; } //---- buy conditions if(Open[1]<ma && Close[1]>ma) { res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue); return; } //---- } //+------------------------------------------------------------------+ //| Check for close order conditions | //+------------------------------------------------------------------+ void CheckForClose() { double ma; //---- go trading only for first tiks of new bar if(Volume[0]>1) return; //---- get Moving Average ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0); //---- for(int i=0;i<OrdersTotal();i++) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break; if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue; //---- check order type if(OrderType()==OP_BUY) { if(Open[1]>ma && Close[1]<ma) OrderClose(OrderTicket(),OrderLots(),Bid,3,White); break; } if(OrderType()==OP_SELL) { if(Open[1]<ma && Close[1]>ma) OrderClose(OrderTicket(),OrderLots(),Ask,3,White); break; } } //---- } //+------------------------------------------------------------------+ //| Start function | //+------------------------------------------------------------------+ void start() { //---- check for history and trading if(Bars<100 || IsTradeAllowed()==false) return; //---- calculate open orders by current symbol if(CalculateCurrentOrders(Symbol())==0) CheckForOpen(); else CheckForClose(); //---- } //+------------------------------------------------------------------+ • S cri p t i s a p rog ra m d esi g n ed f or si n g le f un cti on ex ecuti on . U n li k e the Ad v i sor, scri p ts a re b ei n g held on ly on ce (on d ema n d ) , a n d n ot b y ti ck s. An d of course ha s n o access to indicator functions. These w ere “W ha t” MQL4 i s? “W hy ” to use MQL4? N ow , “W here” d o I w ri te MQL4? To w ri te y our MQL4 cod e a n d a s a n y thi n g else i n w orld , y ou ca n choose on e of tw o w a y s, the ha rd w a y a n d the ea sy w a y . 1- T h e h a r d w a y The ha rd w a y i s usi n g y our f a v ori te tex t ed i tor a n d the comma n d p romp t to comp i le y our p rog ra m. N otep a d i s n ot b a d choi ce, b ut d o n ot f org et tw o thi n g s: 1- To sa v e the f i le y ou ha v e crea ted i n p la i n tex t f orma t. 2- To sa v e the f i le a s .mp 4 (tha t’ s to b e ea sy to reop en i t w i th Meta ed i tor) , b ut y ou ca n sa v e i t a s a n y ex ten si on y ou p ref er. Af ter sa v i n g y our p rog ra m there i s a n ex tra step to ma k e y our cod e comes out to the li g ht. It’s the Compiling step. C omp i li n g mea n s to con v ert the huma n rea d a b le scri p t tha t y ou ha v e j ust w rote to the ma chi n e la n g ua g e tha t y our comp uter un d ersta n d s. Meta Tra d er ha s b een shi p p ed w i th i ts ow n comp i ler (the p rog ra m w hi ch w i ll con v ert y our scri p t to the ma chi n e la n g ua g e) ca lled Me t a La n g .e x e . Meta la n g .ex e i s a con sole p rog ra m w hi ch ta k es 2 p a ra meters a n d outp ut a n .ex 4 f i le (the f i le w hi ch Meta tra d er un d ersta n d s) . The f i rst p a ra meter i s “op ti on s” p a ra meter a n d the on ly op ti on a v a i la b le i s –q q ui t The secon d p a ra meter i s the f ull p a th to y our .mq l f i le. The sy n ta x w i ll b e i n thi s f orma t. m e ta la n g [ o p t io n s … ] f ile n a m e E x a mp le 1- F i n d y our meta la n g .ex e p a th, i t w i ll b e the sa me p a th of Meta Tra d er (here my p a th i s D :\P rog ra m F i les\Meta Tra d er 4) 2- C rea te a b a tch f i le a n d n a me i t comp i le.b a t (or a n y n a me y ou p ref er) . 3- W ri te these li n es i n to the b a t f i le then sa v e i t. cd D : \P r ogr a m F iles\M eta T r a d er 4 meta la ng -q " D : \P r ogr a m F iles\M eta T r a d er 4 \my _ f ir st_ mq l4 _ scr ipt. mq 4 " (D on ’ t f org et to cha n g e the p a th to y ou Meta Tra d er i n sta lled p a th) 4- R un the b a tch f i le a n d i f y ou a re luck y p erson li k e me y ou w i ll g et a screen li k e thi s. F i g u r e 1 Metalang compiler As y ou see y ou w i ll g et the outp ut f i le “my _ f i rst_ mq l4_ scri p t.ex 4” 2-T h e e a s y w a y Meta tra d er ha s b een shi p p ed w i th a g ood I D E (i n teg ra ted d ev elop men t ed i tor) ca lled Meta E d i tor w hi ch ha s these f ea tures: 1- A tex t ed i tor ha s the f ea ture of hi g hli g hti n g d i f f eren t con structi on s of MQL4 la n g ua g e w hi le y ou a re w ri ti n g / rea d i n g cod e. 2- E a sy to comp i le y our p rog ra m, j ust cli ck F 5 a n d the Meta E d i tor w i ll ma k e a ll the ha rd w ork f or y ou a n d p rod uces the “ex 4” f i le. B esi d es i t’ s ea sy to see w ha t the w ron g i n y our p rog ra m i s (i n the E rror Ta b – see f i g ure 2) . 3- B ui lt-i n a d i cti on a ry b ook w hi ch y ou ca n a ccess b y hi g hli g ht the k ey w ord y ou w a n t to k n ow f urther a b out i t then p ress F 1. F i g u r e 2 MetaE d itor 4 I n the comi n g lesson s w e w i ll k n ow more a b out Meta E d i tor. Tod a y I j ust ca me to sa y hello, tomorrow w e w i ll sta rt the rea l w ork s. Tomorrow w e w i ll stud y the S y n ta x of MQL4? I w elcome v ery much the q uesti on s a n d the sug g esti on s. S ee y ou C o d e r s’ G u r u 19 -10 -20 0 5 MQL4 COURSE By Coders’ g u ru w w w . f orex -t sd. c om -2SYNTAX -------------------- I hope you enjoyed the “W el c om e” l esson w hi c h tr i ed to a nsw er the v er y b a si c q uesti ons; what MQ L 4 i s, why MQ L 4 a nd whe r e ( to w r i te) MQ L 4? Al w a ys the b i g g est a nd the m ost i m por ta nt q uesti on( s) a r e ho w, a nd the enti r e c om i ng l essons a r e the a nsw er . N ow , I w a nt you to em pty your m i nd f r om c onc epts. a ny c onf usi on a nd r ea d c a r ef ul l y the nex t f ew W e a r e ta l k i ng toda y a b out the S YN T AX r ul es of MQ L 4. And a s I tol d you b ef or e, If you are programming in C ( or it s superset C + + ) t h en you k now a l ot of M Q L 4 b efore ev en I st art my l essons. T ha t’ s b ec a use the synta x of MQ L 4 i s v er y l i k e of the synta x of C . T he di c ti ona r y m ea ns of the w or d S YN T AX of a pr og r a m m i ng l a ng ua g e i s: “T h e set of al l ow ed reserv ed w ord s and t h eir paramet ers and t h e c orrec t w ord ord er in t h e ex pression is c al l ed t h e synt ax of l anguage”. “Wikipedia” S o, w hen w e a r e studyi ng the synta x of the l a ng ua g e w e a r e studyi ng i ts g r a m m a r a nd w r i ti ng r ul es w hi c h c onsi st of : • • • • F or m a t C om m ents Identi f i er s R eser v ed w or ds L et’ s sl i c e the c a k e. 1. S i g na l C ur r ent. F or ex a m pl e thi s l i ne i s v a l i d: ex ter n i nt MA_P er i od= 13." T hi s i s the v a l i d “C ontr ol l i ng c om pi l a ti on”: # pr oper ty c opyr i g ht " C opyr i g ht © 20 0 4. B ut. ta b s a nd em pty l i nes you w a nt to sepa r a te your c ode a nd your l i ne of c ode to m a k e them r ea da b l e a nd eyes pl ea si ng .F o r m a t : W hen you w r i te your c ode. S i g na l C ur r ent. the f i r st l i ne i s m or e r ea da b l e a nd ea sy to under sta nd. F or ex a m pl e a l l of these l i nes a r e v a l i d i n MQ L 4: doub l e Ma c dC ur r ent. And a s ev er ythi ng i n the w or l d ther e a r e ex c epti ons to the r ul e: 1. F or ex a m pl e the nex t l i ne of c ode i s i nv a l i d a nd the MQ L 4 c om pi l er w i l l c om pl a i n: # pr oper ty c opyr i g ht " C opyr i g ht © 20 0 4.You c a n’ t use new l i ne or spa c e i n the m i ddl e of C onsta nt v a l ues. Ma c dP r ev i ous. S i g na l C ur r ent. Ma c dP r ev i ous. Meta Q uotes S of tw a r e C or p. doub l e Ma c dC ur r ent. you c a n f r eel y use a ny set of spa c es. Identi f i er s or Keyw or ds. Meta Q uotes S of tw a r e C or p.You c a n’ t use new l i ne i n the “C ontr ol l i ng c om pi l a ti on” You w i l l k now m or e a b out “C ontr ol l i ng c om pi l a ti on” i n nex t l esson b ut just r em em b er thi s i s a n ex c epti on. doub l e Ma c dC ur r ent." 2. . a s you see. Ma c dP r ev i ous. / / T hi s i s a nother c om m ent . ex ter n i nt MA_P er i od= 13.. N ot ic e t h e t ab b et w een 1 and 3 . a ny pr og r a m m i ng l a ng ua g e ha s i ts styl e of w r i ti ng c om m ents. MQ L 4 ( & C / C + + ) uses tw o k i nds of c om m ents styl es: 1. W i thout c om m ents -ev en you a r e the c ode’ s c r ea tor .you c a n’ t under sta nd a l l these puz z l ed l i nes. You use C om m ents to w r i te l i nes i n your c ode w hi c h the c om pi l er w i l l i g nor e then b ut i t c l ea r s your c ode a nd m a k es i t under sta nda b l e. F or ex a m pl e: / / T hi s i s a c om m ent ex ter n i nt MA_P er i od= 13.S i ng l e l i ne c om m ents T he S i ng l e l i ne c om m ent sta r ts w i th “/ / ” a nd ends w i th the new l i ne. 2. “M A _ P eriod ” is an Id ent ifier and “1 3 ” is a C onst ant v al ue.“ex t ren” and “int ” h ere are Keyw ord s . ex ter n i nt MA_P er i od= 1 3. F or ex a m pl e the nex t l i nes a r e i nv a l i ds: ex ter n i nt MA_P er i od= 1 3. Y ou w il l k now more in t h e nex t l essons.C o m m e n t s : T o m a k e the pr og r a m m i ng w or l d ea si er . Assum e tha t you w r i te a pr og r a m i n the sum m er a nd i n the w i nter you w a nt to r ea d i t. ex ter n i nt MA_P er i od= 13. c onsta nts a nd f unc ti ons. F or ex a m pl e: / * thi s is m ul ti l i ne c om m ent* / You c a n a l so nest si ng l e l i ne c om m ent i nsi de m ul ti l i nes c om m ent l i k e tha t: / * thi s is m ul ti / / a nother c om m ent nested her e. l i ne c om m ent* / T hi s i s a v a l i d c om m ent too: ex ter n i nt / * H E L L O ! I’ m a c om m ent* / MA_P er i od= 13.2. 3.I d e n t i f i e r s : An i denti f i er i s the na m e you c hoose to your v a r i a b l es.Mul ti -l i ne c om m ents T he m ul ti -l i ne c om m ent sta r t w i th “/ * ” a nd ends w i th “* / ”. F or ex a m pl e MA_P er i od her e i s a n i denti f i er : ex ter n i nt MA_P er i od= 13. And you c a n c om m ent m or e tha n l i ne or m or e b y putti ng “/ * ” a t the sta r t of the f i r st l i ne. a nd “* / ” a t the end of the l a st l i ne. . B ut thi s i s i nv a l i d c om m ent: ex ter n i nt / / test MA_P er i od= 13. T her e a r e f ew r ul es a nd r estr i c ti ons f or c hoosi ng those na m es: 1.You c a n’ t use a ny r eser v ed w or ds a s a n Identi f i er . 2. S o.T he l eng th of the Identi f i er m ust not ex c eed 3 1 c ha r a c ter s. they a r e r eser v ed to the l a ng ua g e usa g e a nd you c a n’ t use them a s a n i denti f i er na m e or f or a ny other pur pose.R e s e r v e d w o r d s : T her e a r e “w or ds” w hi c h the l a ng ua g e uses them f or spec i f i c a c ti ons. You w i l l see the l i st of the r eser v ed w or ds too soon. i t c a n’ t b e sta r ted w i th a num b er or a nother sym b ol ex c ept the under l i ni ng sym b ol . a nd c o l o r i s one of them ) Nam e _ Nam 1 Nam ~ Nam N~ am i_ lo v e 1 e 1 4. 4. M A _ P E R I O D not the sa m e a s m a_ p e r i o d or M A _ P e r i o d L et’ s ta k e som e ex a m pl es: V a lid V a lid e Inv a l i d ( don’ t sta r t w i th num b er ) e 1 Inv a l i d ( you c a n onl y use under l i ne sym b ol ) e 1 Inv a l i d ( you c a n onl y use under l i ne sym b ol ) _ m y _ c o u n tr y _ an d _ m y _ c o u n tr y _ l o v e s _ al l _ the _ wo r l d Inv a l i d ( you c a n’ t ex c eed the 31 c ha r a c ter s l eng th) C o lo r V a lid c o lo r Inv a l i d ( you c a n’ t use r ev er sed w or d.T he i denti f i er s’ na m es a r e c a se sensi ti v e. S o. T hi s i s the l i st of the r eser v ed w or ds ( from t h e M Q L 4 guid e): Data types bool c olor d a t e t im e d ou ble M em o r y c l asses e x te rn s t a t ic O per ato r s br e a k c a s e c on t i n u e d e f a u lt f a ls e tru e O th er .T he Identi f i er m ust b eg i n w i th a l etter ( c a pi ta l or sm a l l ) or the under l i ni ng sym b ol _. S o. 3. in t s t r in g v oi d e ls e f or if re tu rn wh i le s wi t c h F or ex a m pl e the nex t l i nes of c ode a r e i nv a l i d: ex ter n i nt d ateti m e = 13. B e R ea dy. T he nex t l esson w i l l b e a b out the “D ata T y p e s ”. S o. doub l e c o n ti n u e = 0 . i nt e x te r n = 20 . I hope you enjoyed the l esson. S ee you C o d e r s’ G u r u 20 -10 -20 0 5 . the r ea l ha r d w or k i s c om i ng ! I w el c om e v er y m uc h the q uesti ons a nd the sug g esti ons. the most of the p rog ra mmi ng la ng u a g es w i ll na me thi s d a ta a s “ I nt eg er ” d a ta ty p e. f orex -t sd. • • In ord er to u se a box to store d a ta .com/ a tta chment. W h a t ’ s t h e D a t a t yp e m ea n? A ny p rog ra mmi ng la ng u a g e ha s a set of na mes of the memory rep resenta ti on of the d a ta .com/ a tta chment. T he box si z e i s memory stora g e a rea req u i red i n by tes. let’ s enjoy the D A T A T Y P E S. w hi ch tri ed to g i ve y ou the a nsw ers f or: • W ha t f orma t y ou ca n u se to w ri te M Q L 4 cod e? • H ow to ma k e the w orld better by commenti ng y ou r cod e? • W ha t the Id enti f i ers a re. a nd w ha t a re the ru les of choosi ng them? • W ha t a re the M Q L 4 R eserved w ord s? If y ou d i d n’ t rea d the “ SY N T A X ” lesson p lea se d ow nloa d i t f rom here: http :/ / f orex -tsd .p hp ? a tta chmenti d = 37 2 Don’t f or g e t to l og i n f i r s t.p hp ? a tta chmenti d = 39 9 A nd y ou ca n d ow nloa d the “ W elcome” lesson f rom here: http :/ / f orex -tsd . thi s w ord k now n a s k eyw or d . F or ex a mp le i f the memory hold s nu mbers betw een -214 7 4 8 36 4 8 to 214 7 4 8 36 4 7 . c om -3DATA TYPES -------------------- Welcome to my thi rd lesson i n my M Q L 4 cou rse. In the d ecla ra ti on p rocess y ou u se a w ord tell the comp u ter w ha t’ s the k i nd a nd si z e of the box y ou w a nt to u se. N ow . T o help y ou thi nk of thi s a s a p i ctu re.MQL4 COURSE By Coders’ g u ru w w w . i ma g i ne tha t memory i s a seri es of d i f f erent si z e box es. I hop e y ou enj oy ed the “ SY N T A X ” lesson. thi s p rocess i s k now n a s d ec l a r a t i on. . the box mu st be g i ven a na me. V a r i a b l es ? V a ri a bles a re the na mes tha t ref er to secti ons of memory i nto w hi ch d a ta ca n be stored . In M Q L 4 . In the p revi ou s ex a mp le w e ha ve u sed : i nt Key w ord i nt Integ er d a ta ty p e. M Q L 4 p resents the i nteg er i n d eci ma l or hex a d eci ma l f orma t. F or ex a mp le i f w e sa i d thi s li ne of cod e to the comp u ter: i nt M y V a ra i ble= 0 . a letter or a la rg e nu mber i s not g oi ng to occu p y the sa me sp a ce i n memory . these a re the k i nd s of D a ta ty p es: • • • • • • • Integ er (i nt) B oolea n (bool) C ha ra cter (cha r) Stri ng (stri ng ) F loa ti ng -p oi nt nu mber (d ou ble) C olor (color) D a teti me (d a teti me) 1. thi s p rocess i s k now n a s i ni t i a l i z a t i on. W hen w e crea te a va ri a ble w e a re telli ng the comp u ter tha t w e w a nt hi m to a ssi g n a sp eci f i ed memory leng th (i n by tes) to ou r va ri a ble. T ha t’ s mea n w e a re a sk i ng the comp u ter to set a block of 4 by tes leng th to ou r va ri a ble na med “ M y V a ra i a ble” . = 0 Ini ti a li z a ti on W e w i ll k now more a bou t va ri a bles i n a comi ng lesson. D a ta i s p la ced i nto a box by a s s i g ni ng the d a ta to the box .• • • It help s i f y ou g i ve a box a mea ni ng f u l na me tha t rela tes to the ty p e of i nf orma ti on w hi ch ma k e i t ea si er to f i nd the d a ta . W hen w e set the va lu e of the box y ou ha ve crea ted i n the sa me li ne y ou d ecla red the va ri a ble. thi s na me i s the v a r i a b l e c ons t a nt .si g n a nd i s ma d e of d i g i ts. si nce stori ng a si mp le nu mber. . so the comp u ter w i ll a sk u s w ha t’ s the k i nd of d a ta a nd how mu ch the leng th of the d a ta ? T ha t i s the D a ta ty p e f or. A nd i ts ra ng e va lu e i s betw een -214 7 4 8 36 4 8 to 214 7 4 8 36 4 7 . i nt D ecla ra ti on M yV a r a i b l e V a ri a ble’ s consta nt.I n t e g e r A n i nteg er. i s a nu mber tha t ca n sta rt w i th a + or a . i nt i ntA notherIntg er = -10 0 .tru e. 8 a nd 9 p oi nt w h i c h + ( p l u s ) or th e w r i ti ng of nu ) to r e p r e s e nt nu i nd i c a te s th e s ta − ( m i nu s ) to i nd m b e r s i n th e b a s e of 1 0.F a lse. a nd u s e s d i g i ts ( 0. tru e a nd f a lse (or thei r nu meri c rep resenta ti on. W e u se the k ey w ord b ool to crea te a boolea n va ri a ble. F or ex a mp le: bool I = tru e. bool bF la g = 1. 6 d e c im a l s y m b ol s nota ti on i s . 0 X 12. A nd i t occu p i es 1 bi t of the memory .F A L SE . 2. 4 . 3. 0 X 7 C 7 W e u se the k ey w ord i nt to crea te a n i nteg er va ri a ble. 7 . F or ex a mp le: i nt i ntInteg er = 0 . 2134 . In M Q L 4 . 5 . 0 X a 3. 0 .B o o l e a n B oolea n va ri a ble i s a d a ta ty p e w hi ch ca n hold only tw o va lu es.F or ex a mp le the nex t nu mbers a re Integ ers: 12. De c i m a l a nd H e x a d e c i m a l : De c i m a l 3 .T R U E a nd T ru e a re eq u a ls. m b e r s . a nd w i th one of th e s i g n i c a te s i g n. 2 . f a lse. 0 x 2f . F or e x a m p l e . 0 x A 3. th e d e c i m a l nu m e r a l 7 9 c a n b e w r i tte n a s 4 F i n h e x a d e c i m a l . bool bB ool= F A L SE . -230 0 x 0 A . i nt i ntH ex Intg er= 0 x 12. B ool e a n na m e d l i k e th i s i n th e h onor of th e g r e a t m a th e m a ti c i a n B ool e G e or g e . 0 x 12. 1 . 0 a nd 1). . T h e s e d i g i ts a r e f r e q u e ntl y u s e d w i th a r t of a f r a c ti ona l p a r t. H e x a d e c i m a l i s a nu m e r a l s y s te m w i th a b a s e of 1 6 u s u a l l y w r i tte n u s i ng th e s y m b ol s 0–9 a nd A –F or a –f . A cha ra cter i s one of 256 d ef i ned a lp ha beti c. i nt chrB = '\n'. C ha ra cters ha ve i nteg er va lu es corresp ond i ng to loca ti on i n the A SC II set. Y ou w ri te the cha ra cter consta nt by u si ng si ng le q u otes (') su rrou nd i ng the cha ra cter. F or ex a mp le: 'a ' . 'Z ' W e u se the k ey w ord i nt to crea te a cha ra cter va ri a ble. F or ex a mp le: i nt chrA = '\\'. A nd tha t by p ref i x i ng the cha ra cter w i th the ba ck sla sh cha ra cter (\). nu meri c.3. i nt chrB = '$ '. ca rri a g e retu rn new li ne hori z onta l ta b reverse sla sh si ng le q u ote d ou ble q u ote hex a d eci ma l A SC II-cod e \r \n \t \\ \' \" \x hh . H ere w e u se somethi ng ca lled E s c a p e S eq u enc e to p resent those sp eci a l cha ra cters. / / sla sh cha ra cter / / new li ne T hi s i s the li st of E sca p e Seq u ence cha ra cters u sed i n M Q L 4 . a nd sp eci a l k ey elements d ef i ned i n the A SC II (A meri ca n Sta nd a rd C od e f or Inf orma ti on Intercha ng e) set.Ch a r a c t e r M Q L 4 na m e s th i s Da ta ty p e “ L i te r a l ” . Some cha ra cters ca lled Sp eci a l C ha ra cters ca n’ t p resent d i rectly i nsi d e the si ng le q u otes beca u se they ha ve a reserved mea ni ng s i n M Q L 4 la ng u a g e. F or ex a mp le: i nt chrA = 'A '. '$ ' . It d oes not ma tter i f there a re u nu sed a rra y loca ti ons a f ter tha t. a N U L L cha ra cter i s p la ced i n the nex t a rra y loca ti on. 44 0054 0x2c | L 76 0114 0x4c | l 108 0154 0x6c (cr) 13 0015 0x0d | 45 0055 0x2d | M 77 0115 0x4d | m 109 0155 0x6d (so) 14 0016 0x0e | . See f i g u re 1 f or a si mp le rep resenta ti on of the stri ng consta nt “ hello” i n the cha ra cters a rra y .St r i n g T he stri ng d a ta ty p e i s a n a rra y of cha ra cters enclosed i n d ou ble q u ote ("). 46 0056 0x2e | N 78 0116 0x4e | n 110 0156 0x6e (si) 15 0017 0x0f | / 47 0057 0x2f | O 79 0117 0x4f | o 111 0157 0x6f (dle) 16 0020 0x10 | 0 48 0060 0x30 | P 80 0120 0x50 | p 112 0160 0x70 (dc1) 17 0021 0x11 | 1 49 0061 0x31 | Q 81 0121 0x51 | q 113 0161 0x71 (dc2) 18 0022 0x12 | 2 50 0062 0x32 | R 82 0122 0x52 | r 114 0162 0x72 (dc3) 19 0023 0x13 | 3 51 0063 0x33 | S 83 0123 0x53 | s 115 0163 0x73 (dc4) 20 0024 0x14 | 4 52 0064 0x34 | T 84 0124 0x54 | t 116 0164 0x74 (nak) 21 0025 0x15 | 5 53 0065 0x35 | U 85 0125 0x55 | u 117 0165 0x75 (syn) 22 0026 0x16 | 6 54 0066 0x36 | V 86 0126 0x56 | v 118 0166 0x76 (etb) 23 0027 0x17 | 7 55 0067 0x37 | W 87 0127 0x57 | w 119 0167 0x77 (can) 24 0030 0x18 | 8 56 0070 0x38 | X 88 0130 0x58 | x 120 0170 0x78 (em) 25 0031 0x19 | 9 57 0071 0x39 | Y 89 0131 0x59 | y 121 0171 0x79 (sub) 26 0032 0x1a | : 58 0072 0x3a | Z 90 0132 0x5a | z 122 0172 0x7a (esc) 27 0033 0x1b | . A N U L L cha ra cter i s a sp eci a l cha ra cter (rep resented by the A SC II cod e 0 ) u sed to ma rk the end of thi s ty p e of stri ng . sta rti ng a t i nd ex 0 . T he a rra y of cha ra cters i s a n a rra y w hi ch hold s one cha ra cter a f ter a nother. 59 0073 0x3b | [ 91 0133 0x5b | { 123 0173 0x7b (fs) 28 0034 0x1c | < 60 0074 0x3c | \ 92 0134 0x5c | | 124 0174 0x7c (gs) 29 0035 0x1d | = 61 0075 0x3d | ] 93 0135 0x5d | } 125 0175 0x7d (rs) 30 0036 0x1e | > 62 0076 0x3e | ^ 94 0136 0x5e | ~ 126 0176 0x7e (us) 31 0037 0x1f | ? 63 0077 0x3f | _ 95 0137 0x5f | (del) 127 0177 0x7f 4.ASCI I t a b l e Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex ------------------------------------------------------------------------------------(nul) 0 0000 0x00 | (sp) 32 0040 0x20 | @ 64 0100 0x40 | ` 96 0140 0x60 (soh) 1 0001 0x01 | ! 33 0041 0x21 | A 65 0101 0x41 | a 97 0141 0x61 (stx) 2 0002 0x02 | " 34 0042 0x22 | B 66 0102 0x42 | b 98 0142 0x62 (etx) 3 0003 0x03 | # 35 0043 0x23 | C 67 0103 0x43 | c 99 0143 0x63 (eot) 4 0004 0x04 | $ 36 0044 0x24 | D 68 0104 0x44 | d 100 0144 0x64 (enq) 5 0005 0x05 | % 37 0045 0x25 | E 69 0105 0x45 | e 101 0145 0x65 (ack) 6 0006 0x06 | & 38 0046 0x26 | F 70 0106 0x46 | f 102 0146 0x66 (bel) 7 0007 0x07 | ' 39 0047 0x27 | G 71 0107 0x47 | g 103 0147 0x67 8 0010 0x08 | ( 40 0050 0x28 | H 72 0110 0x48 | h 104 0150 0x68 (bs) (ht) 9 0011 0x09 | ) 41 0051 0x29 | I 73 0111 0x49 | i 105 0151 0x69 (nl) 10 0012 0x0a | * 42 0052 0x2a | J 74 0112 0x4a | j 106 0152 0x6a (vt) 11 0013 0x0b | + 43 0053 0x2b | K 75 0113 0x4b | k 107 0153 0x6b (np) 12 0014 0x0c | . . A f ter the la st cha ra cter of d a ta . ". / / N oti ce the u se of (") cha ra cter.0 .-115. 5. stri ng str3 = "1234 56 7 8 9 0 ". Y ou ca n u se a ny sp eci a l cha ra cter -menti oned a bove. W e u se the k ey w ord s t r i ng to crea te a stri ng va ri a ble.7 5.F l o a t i n g -p o i n t n u m b e r ( d o u b l e ) F loa ti ng p oi nt nu mber i s the R ea l N u mber (tha t i s.0 0 0 1.8 e30 8 . a nu mber tha t ca n conta i n a f ra cti ona l p a rt besi d e the i nteg er p a rt sep a ra ted w i th (. w i th y ou cod ers g u ru ” .) d ot). F or ex a mp le: stri ng str1 = "H ello w orld 1. \"F orex -tsd f oru m\". d ou ble d blN u mber3 = 5.E x : 3. A nd i ts ra ng e va lu e i s betw een 2.i n y ou r stri ng consta nt by p ref i x i ng i t w i th the ba ck sla sh (\).5. . stri ng str2 = "C op y ri g ht © 20 0 5.F i g u r e 1 – Ch a r a c t e r s a r r a y M Q L 4 li mi ts the si z e of the stri ng va ri a ble to 255 cha ra cters a nd a ny cha ra cter a bove 255 cha ra cters w i ll g enera te thi s error: (too l ong s tr i ng ( 2 5 5 c h a r a c te r s m a x i m u m ) ). W e u se the k ey w ord d ou b l e to crea te a f loa ti ng -p oi nt va ri a ble. F or ex a mp le: d ou ble d blN u mber1 = 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . d ou ble d blN u mber3 = 1/ 4 . 15 a nd 0 .2e-30 8 to 1. 2. .B y t h e i nt eg er v a l u e: E very color i n the W eb C olors Set ha s i ts i nteg er va lu e w hi ch y ou ca n w ri te i t i n d eci ma l or hex a d eci ma l f orma t. color clr1= C '128 .Co l o r C olor d a ta ty p e i s a sp eci a l M Q L 4 d a ta ty p e.128 .B y t h e c ol or na m e: F or the w ell k now colors (ca lled W eb C olors Set) y ou ca n a ssi g n the na me of the color to the color va ri a ble.0 x 0 0 . see the li st of the W eb C olors Set. 3.128 . F or ex a mp le: color clr1= R ed . T hese va lu es ha ve to be betw een: 0 to 255.128 ' / / g ra y C '0 x 0 0 . F or ex a mp le: / / sy mbol consta nts C '128 . T he hex a d eci ma l color f orma t look s li k e thi s: 0 x B B G G R R w here B B i s the blu e va lu e. B etw een the tw o si g na l q u ota ti ons y ou set the va lu e of the red . g reen a nd blu e (k now a s R G B va lu e of the color).0 x F F ' / / blu e / / na med color R ed Y ellow B la ck / / i nteg er-va lu ed rep resenta ti on 0 x F F F F F F / / w hi te 16 7 7 7 215 / / w hi te 0 x 0 0 8 0 0 0 / / g reen 327 6 8 / / g reen W e u se the k ey w ord c ol or to crea te a color va ri a ble. A nd y ou ca n w ri te these va lu es i n d eci ma l or hex a d eci ma l f orma t. G G i s g reen va lu e a nd R R i s the red va lu e.B y C h a r a c t er r ep r es ent a t i on (M Q L 4 na med i t thi s na me): In thi s method y ou u se the k ey w ord (C ) f ollow ed by tw o si g na l q u ota ti ons ('). Y ou ca n set the C olor va ri a ble consta nt i n three w a y s: 1.128 ' . w hi ch hold s a color a p p ea rs on the M eta T ra d er cha rt w hen y ou crea te y ou r ow n E x p ert A d vi sor or C u stom Ind i ctor a nd the u ser ca n cha ng e i t f rom the p rop erty ta b of y ou r E x p ert A d vi sor or C u stom Ind i ctor. A nd y ou ca n a ssi g n the Integ er va lu e of the color to the color va ri a ble.6. mi nu tes. w hi ch hold s a d a te a nd ti me d a ta . 20 37 .0 1. month. . hou r.0 7 .20 0 4 ' ' / / N ew Y ea r :27 ' :27 ' / / eq u a l to D '19 8 0 . W e b Co l o r s Se t M ar o o n Black D ar kG r e e n D ar kG o ld e n r o d M e d iu m S p r in g G r e e n O r an g e Blu e D ar kV i o le t I n d ig o D ar kS lat e G r ay D ar kS lat e Blu e L aw n G r e e n M ag e n t a G o ld F i r e Br i ck M i d n i g h t Blu e D ar kBlu e O li v e D ar kO li v e G r e e n M e d i u m S e aG r e e n D ar kO r ch i d C h ar t r e u s e T u r q u o is e D ar kG r ay V i o le t S i lv e r G r ay M e d i u m Blu e G re e n S ad d le Br o w n C h o co lat e L im e Br o w n T e al F o re s tG re e n C r im s o n N av y O li v e D r ab S t e e lBlu e A q u a D i m G r ay P u r p le L i g h t S e aG r e e n D ar kO r an g e G o ld e n r o d S e aG r e e n M e d i u m V i o le t R e d C ad e t Blu e Y e llo w R e d S ie n n a D ar kT u r q u o i s e L im e G r e e n P e r u Y e llo w G r e e n S lat e G r ay T o m at o L i g h t S lat e G r ay M e d i u m P u r p le D ar kS alm o n P ale G r e e n L e m o n C h if f o n L av e n d e r Blu s h L av e n d e r M o ccas i n P lu m I n d i an R e d D e e p S ky Blu e S p r in g G r e e n S lat e Blu e O r an g e R e d Blu e V i o le t O r ch i d T an M e d i u m O r ch i d P ale V i o le t R e d Bu r ly W o o d T h i s t le Be i g e K h aki D e e p P in k M e d iu m T u r q u o is e G r e e n Y e llo w H o t P in k C o r al M e d i u m A q u am ar i n e C o r n f lo w e r Blu e A q u am ar i n e P e ach P u f f S alm o n D o d g e r Blu e D ar kS e aG r e e n R o y alBlu e S an d y Br o w n L ig h t P in k M is t y R o s e P o w d e r Blu e A n t iq u e W h it e O ld L ace S n o w G ai n s b o r o L ig h t G r e e n P ale G o ld e n r o d P ap ay aW h i p W h it e P ale T u r q u o i s e C o r n s i lk P in k L i g h t S ky Blu e L ig h t G r e y Bi s q u e Iv o r y L i g h t C o r al M e d i u m S lat e Blu e L i g h t S t e e lBlu e L i g h t G o ld e n R o d H o n e y d e w L i g h t C y an W h e at S ky Blu e R o s y Br o w n D ar kK h aki L i g h t S alm o n N av aj o W h i t e L in e n L i g h t Blu e M i n t C r e am W h i t e S m o ke S e as h e ll L i g h t Y e llo w Blan ch e d A lm o n d A li ce Blu e 7.0 1.0 1 0 0 :0 0 D '19 8 0 .0 7 .19 8 0 12' D '0 1.19 12:0 0 :0 0 ' / / eq u a l to D '0 1. B etw een the tw o si g na l q u ota ti ons y ou w ri te a cha ra cter li ne consi sti ng of 6 p a rts f or va lu e of y ea r.0 1. d a te.Da t e t i m e D a teti me d a ta ty p e i s a sp eci a l M Q L 4 d a ta ty p e.20 0 4 0 0 :0 0 :0 0 ' W e u se the k ey w ord d a t et i m e to crea te a d a teti me va ri a ble.0 7 . 19 7 0 to D ec 31. Y ou set the D a teti me va ri a ble by u si ng the k ey w ord (D ) f ollow ed by tw o si g na l q u ota ti ons (').19 12:30 D '19 .0 7 . D a teti me consta nt ca n va ry f rom J a n 1. F or ex a mp le: D '20 0 4 .19 8 0 12:30 D '19 .color clr1= 327 6 8 . a nd second s. 19 12:0 0 :0 0 '.10 . I hop e y ou enj oy ed the lesson. See y ou C od er s ’ G u r u 22-10 -20 0 5 .10 .F or ex a mp le: d a teti me d tM y B i rthD a y = D '19 7 2. d a teti me d t1= D '20 0 5.22 0 4 :30 :0 0 '. I w elcome very mu ch the q u esti ons a nd the su g g esti ons. T he nex t lesson w i ll be a bou t the “ O p era ti ons & E x p ressi ons” . her e a r e i dent i f i er s. y ou w i ll r ememb er v er y f a st w ha t’ s the op er a tor mea n s.com/a tta chmen http ://f or ex -tsd .* a n d / a r e the op er a t or s.com/a tta chmen http ://f or ex -tsd . f orex -t sd.y. I kn ow the op er a ti on s. P u z z led ? Let’ s i llu str a te i t i n a n ex a mp le: x = ( y *z )/w . x. /) a r e the b a si c a r i thmeti ca l op er a tor s.p hp ? a f r om her e: tta chmen ti d =399 tta chmen ti d =37 2 tta chmen ti d =469 Welcome to the f ou N ow . I f I told y ou tha t ( + . T he w hole li n e i s a n exp r essi on.*. R ev i ew the SY N T AX lesson ) tog ether w i th the Op er a t i ons p r od u ce the Exp r essi ons. c om -4Operations & Expressions -------------------r th lesson i n my cou r se a b ou t M Q L4.z a n d w.MQL4 COURSE By Coders’ g u ru w w w . =. . s lesson t. let’ s en j oy the O p er a ti on s & E x p r essi on s. I hop e y ou u n d er sta n d i t. a n d a b ov e a ll y ou enjoyed i t. W h a t ’ s t h e m ea ni ng of Op er a t i ons & Exp r essi ons? Y ou kn ow the op er a ti on s v er y w ell.p hp ? a t. T he p r ev i ou s lesson “ D a ta T y p es” p r esen ted a lot of n ew con cep ts. cou ld y ou tell me w ha t’ s the mea n i n g of the ex p r essi on ? ” I dent i f i er s ( d o y ou r ememb er them? I f n ot.com/a tta chmen Don’t forget to login first.p hp ? a t. A nd w h en th e sta tem ents c om b ined togeth er it m a k es a f u nc ti o n a nd w h en th e fu nc tions c om b ined togeth er it m a k es a p r o g r am. I hea r y ou sa y i n g “ O K . Y ou ca n d ow n loa d the p r ev i ou http ://f or ex -tsd .-. W h en th e ex p ressions c om b ined togeth er it m a k es a statement. 10 %8 =2 T hi s i s b eca u se i f y ou d i v i d e 10 b y 8 y ou w i ll g et 1 ( 1*8 =8 ). Ad d B to C a n d a ssi g n the r esu lt to A. So. A = B / C. D i v i d e B on C a n d a ssi g n the r esu lt to A. 10 0 %15 =10 . D ecr ea se 1 f r om A ( ex : i f A =2 ma ke i t 1). A = -A. F or ex a mp le: 10 %5 =0 T hi s i s b eca u se i f y ou d i v i d e 10 b y 5 y ou w i ll g et 2 a n d ther e n o r ema i n i n g v a lu e. let’ s sta r t w i th the b a si c a r i thmeti ca l op er a tor s: 1. 10 % 3 w i ll p r od u ce 1).A r i t h m e t i c a l o p e r a t o r s: I n M Q L4 ther e a r e 9 Ar i thmeti ca l op er a ti on s T hi s i s the li st of them w i th the u sa g e of ea ch: Op er a t or + +* / % ++ -N a m e Ad d i ti on op er a tor Su b tr a cti on op er a tor Si g n cha n g er op er a tor s M u lti p li ca ti on op er a tor D i v i si on op er a tor M od u lu s op er a tor I n cr emen t op er a tor D ecr emen t op er a tor Exa m p l e A = B + C. A++. M u lti p ly B a n d C a n d a ssi g n the r esu lt to A. so the r ema i n d er i s ( 10 -8 = 2).I n the r ema i n i n g of thi s lesson w e a r e g oi n g to ta lk a b ou t the ki n d s op er a tor s u sed i n M Q L4. I n cr ea se A b y 1 ( ex : i f A =1 ma ke i t 2). A i s the r emi n d er of d i v i si on of B on C. A--. A = B . D esc r i p t i on C ha n g e the si g n of A f r om p osi ti v e to n eg a ti v e. ( ex : 10 % 2 w i ll p r od u ce 0 . N ot e: T he r ema i n d er op er a tor w or ks b y d i v i d i n g the f i r st n u mb er b y the secon d n u mb er f or the f i r st i n teg er r esu lts a n d then r etu r n s the r ema i n i n g n u mb er .C. A = B * C. Su b tr a ct C f r om B a n d a ssi g n the r esu lt to A. A =A % C. so the r ema i n d er i s 0 . (=) h ere is th e a ssignm ent op era tor. N ot e: H ow the a b ov e ex a mp le w or ks? Let’ s a ssu me: i n t A=1.A ssi g n m e n t o p e r a t o r s: T he p u r p ose of a n y ex p r essi on i s p r od u ci n g a r esu lt a n d the a ssi g n men t op er a tor s setti n g the lef t op er a n d w i th thi s r esu lt. W h a t a b ou t 6 %8 ? I t w i ll b e 6 b eca u se i f y ou d i v i d e 6 b y 8 y ou w i ll g et 0 ( 8 *0 =0 ). . I n M Q L4 ther e a r e 11 a ssi g n men ts op er a ti on s T hi s i s the li st of them w i th the u sa g e of ea ch: Op er a t or = += N a m e Exa m p l e D esc r i p t i on Assi g n men t op er a tor Ad d i ti v e Assi g n men t op er a tor A = B.T hi s i s b eca u se i f y ou d i v i d e 10 0 b y 15 y ou w i ll g et 6 ( 6*15 =90 ). F or ex a mp le: A=B*C . A += B. //i n cr ea se A b y 1. so the r ema i n d er i s ( 10 0 -90 =10 ). F or ex a mp le y ou ca n ’ t sa y : A=( B+ + )*5 . B=A*5 . n ow A=2 B=A*5 . H er e w e mu lti p ly B a n d C a n d a ssi g n the r esu lt to A. //w hi ch mea n s B=2*5 2. so the r ema i n d er i s ( 60 =6). //set A to 1 i n t B. N ot e: Y ou ca n ’ t comb i n e the i n cr emen t a n d d ecr emen t op er a tor w i th other ex p r essi on s. A+ + . Bu t y ou ca n w r i te i t li ke tha t: A+ + . I t’ s eq u a l to: A = A + B. Ad d B to A a n d a ssi g n the r esu lt to A. Assi g n B to A. Looks a t the b i n a r y r ep r esen ta ti on of the v a lu es of A a n d B a n d d oes a b i tw i se O R op er a ti on on them.R e l a t i o n a l o p e r a t o r s: T he r ela ti on a l op er a tor s comp a r e tw o v a lu es ( op er a n d s) a n d r esu lt f a lse or tr u e on ly . op er a tor s M u lti p li ca ti v e Assi g n men t op er a tor A *= B. 4 <= 4 //tr u e //f a lse //tr u e. I t’ s eq u a l to: A = A . D i v i d e A on B a n d a ssi g n the r esu lt to A. A |= B. ^ = A ^ = B. A /= B. I t’ s eq u a l to: A = A * B. M u lti p ly A a n d B a n d a ssi g n the r esu lt to A. I t’ s eq u a l to: A = A % B.-= *= /= %= >>= <<= &= |= Su b tr a cti v e Assi g n men t A -= B. 4 < 4. I t’ s i s li ke the q u esti on “ I s J oh n ta ller tha n Al f r ed? Y es / n o? ” T he r esu lt w i ll b e f a lse on ly i f the ex p r essi on p r od u ce z er o a n d tr u e i f i t p r od u ces a n y n u mb er d i f f er i n g f r om z er o. Su b tr a ct B f r om A a n d a ssi g n the r esu lt to A. D i v i si on a l Assi g n men t op er a tor M od u la ti n g Assi g n men t A %= B. op er a tor AN D Assi g n men t op er a tor O R Assi g n men t op er a tor XO R Assi g n men t op er a tor A &= B. Looks a t the b i n a r y r ep r esen ta ti on of the v a lu es of tw o A a n d B a n d d oes a b i tw i se ex clu si v e O R ( XO R ) op er a ti on on them. I n M Q L4 ther e a r e 6 R ela ti on a l op er a ti on s T hi s i s the li st of them w i th the u sa g e of ea ch: . F or ex a mp le: 4 == 4. op er a tor Lef t Shi f t Assi g n men t op er a tor A >>= B. 3. I t shi f ts the b i ts of A lef t b y the n u mb er of b i ts sp eci f i ed i n B. I t’ s eq u a l to: A = A / B.B. R i g ht Shi f t Assi g n men t A <<= B. Looks a t the b i n a r y r ep r esen ta ti on of the v a lu es of A a n d B a n d d oes a b i tw i se AN D op er a ti on on them. G et the r emi n d er of d i v i si on of A on B a n d a ssi g n the r esu lt to A. I t shi f ts the b i ts of A r i g ht b y the n u mb er of b i ts sp eci f i ed i n B. A <= B. T hi s i s the li st of them w i th the u sa g e of ea ch: Op er a t or N a m e Exa m p l e D esc r i p t i on && AN D op er a tor A && B. N ot op er a tor i s a p p li ed to a n on - .Op er a t or == != < > <= >= E q u a l op er a tor N a m e A == B. then the r i g ht ha n d v a lu e i s n ot con si d er ed . A < B. I f b oth of the v a lu es a r e z er o then the v a lu e of the ex p r essi on i s 0 other w i se the v a lu e of the ex p r essi on i s 1. na m es th e L ogic a l op era tors a s B oolea n op era a lg eb r a . T he tr u th v a lu st on e of tw o p ossi b le v a lu es: tr u e or f a lse.L o g i c a l o p e r a t o r s: Log i ca w a y of a b ou t w ha v e j u M Q L 4 l op er a tor s a r e g en er a lly d er i v ed f r om Boolea n ma n i p u la ti n g the tr u th v a lu es of con cep ts i n a n ha t the con cep ts a ctu a lly m ea n. T r u e i f A i s g r ea ter tha n B else F a lse. w hi ch i s a ma thema ti ca l a b str a ct w a y w i thou t b other i n g e of a con cep t i n Boolea n v a lu e ca n tors M Q L4 u ses the most i mp or ta n t 3 log i ca l op er a tor s. T r u e i f A i s g r ea ter tha n or eq u a ls B else F a lse. I f ei ther of the v a lu es a r e z er o the v a lu e of the ex p r essi on i s z er o. A != B. || O R op er a tor A || B. 4. A > B. ! N O T op er a tor !A. I f the lef t ha n d v a lu e i s n on -z er o. D esc r i p t i on N ot E q u a l op er a tor Less T ha n op er a tor s G r ea ter T ha n op er a tor Less T ha n or E q u a l op er a tor T r u e i f A d oes n ot eq u a l B else F a lse. A >= B. I f the lef t ha n d v a lu e i s z er o. G r ea ter T ha n or E q u a l op er a tor T r u e i f A i s less tha n or eq u a ls B else F a lse. T r u e i f A i s less tha n B else F a lse. other w i se the v a lu e of the ex p r essi on i s 1. then the r i g ht ha n d v a lu e i s n ot con si d er ed . Exa m p l e T r u e i f A eq u a ls B else F a lse. C omp a r es tw o b i ts a n d g en er a tes a r esu lt of 1 i f the b i ts a r e comp lemen ta r y . C omp a r es tw o b i ts a n d g en er a tes a r esu lt of 1 i f ei ther or b oth b i ts a r e 1. U sed to i n v er t a ll of the b i ts of the op er a n d . >> A >> B. ^ ~ A ^ B. T he f ollow i n g op er a tor s a r e a v a i la b le i n M Q L4: Op er a t or & N a m e AN D op er a tor Exa m p l e A & B. a n d a ssi g n s the r i g htmost b i t a v a lu e of 0 . other w i se. other w i se. a n d a ssi g n s the lef tmost b i t a v a lu e of 0 . 5.z er o v a lu e then the v a lu e i s z er o. E a ch mov e to the lef t ef f ecti v ely mu lti p li es op1 b y 2. i f i t i s a p p li ed to a z er o v a lu e.B i t w i se o p e r a t o r s: T he b i tw i se op er a tor s a r e si mi la r to the log i ca l op er a tor s. ~A. . M ov es the b i ts to the r i g ht. other w i se. << T he SH I F T LE F T op er a tor A << B. the v a lu e i s 1. d i sca r d s the f a r lef t b i t. M ov es the b i ts to the lef t. i t r etu r n s 0 . D esc r i p t i on C omp a r es tw o b i ts a n d g en er a tes a r esu lt of 1 i f b oth b i ts a r e 1. E a ch mov e to the r i g ht ef f ecti v ely d i v i d es op1 i n ha lf . N ot e Both op er a n d s a ssoci a ted w i th the b i tw i se op er a tor mu st b e i n teg er s.b i n a r y r ep r esen ta ti on s of d a ta . | O R op er a tor E XC LU SI V E -O R op er a tor C O M P LE M E N T op er a tor T he SH I F T R I G H T op er a tor A | B. ex cep t tha t they w or k on a sma ller sca le -. i t r etu r n s 0 . d i sca r d s the f a r r i g ht b i t. i t r etu r n s 0 . O p er a tor s on the sa me g r ou p ha v e eq u a l p r eced en ce. W hen op er a tor s of eq u a l p r eced en ce a p p ea r i n the sa me ex p r essi on .) W e w i ll kn ow mor e a b ou t the Ar r a y s a n d F u n cti on s i n the n ex t lesson s. O p e r a t o r sP r e c e d e n c e : I f y ou d on ' t ex p li ci tly i n d i ca te the or d er i n w hi ch y ou w a n t the op er a ti on s i n a comp ou n d ex p r essi on to b e p er f or med . recommended W hen w r i ti n g comp ou n d ex p r essi on s. so j u st r ememb er these 3 op er a tor s a s “ O ther op er a tor s”. F or ex a mp le. the tw o f ollow i n g sta temen ts a r e eq u i v a len t: x + y / 10 0 x + (y / 100) //unambiguous. O p er a tor s w i th a hi g her p r eced en ce g et ev a lu a ted f i r st.6. the or d er i s d eter mi n ed b y the p r eced en ce a ssi g n ed to the op er a tor s i n u se w i thi n the ex p r essi on . T he op er a tor s i n thi s ta b le a r e li sted i n p r eced en ce or d er : T he hi g her i n the ta b le a n op er a tor a p p ea r s.T he f u n cti on a r g u men ts sep a r a tor op er a tor -comma ( .T he f u n cti on ca ll op er a tor ( ( ) ). () [] ! F u n cti on ca ll F rom left to righ t Ar r a y elemen t selecti on N eg a ti on F rom left to righ t . T hi s p r a cti ce w i ll ma ke y ou r cod e ea si er to r ea d a n d to ma i n ta i n . T he f ollow i n g ta b le show s the p r eced en ce a ssi g n ed to the op er a tor s i n the M Q L4. T hu s. the hi g her i ts p r eced en ce. the d i v i si on op er a tor ha s a hi g her p r eced en ce tha n d oes the a d d i ti on op er a tor . Assi g n men t op er a tor s a r e ev a lu a ted r i g ht to lef t. All b i n a r y op er a tor s ex cep t f or the a ssi g n men t op er a tor s a r e ev a lu a ted f r om lef t to r i g ht. 2. a r u le mu st g ov er n w hi ch i s ev a lu a ted f i r st.O t h e r o p e r a t o r s: T her e a r e some op er a tor s w hi ch u sed i n M Q L4 a n d d on ’ t b elon g to on e of the p r ev i ou s ca teg or i es: 1. 3. O p er a tor s w i th hi g her p r eced en ce a r e ev a lu a ted b ef or e op er a tor s w i th a r ela ti v ely low er p r eced en ce. y ou shou ld b e ex p li ci t a n d i n d i ca te w i th p a r en theses ( ) w hi ch op er a tor s shou ld b e ev a lu a ted f i r st.T he a r r a y i n d ex i n g op er a tor ( [ ] ). ~ * / % + Bi tw i se n eg a ti on Si g n cha n g i n g op er a ti on M u lti p li ca ti on D i v i si on M od u le d i v i si on Ad d i ti on Su b tr a cti on Lef t shi f t R i g ht shi f t F rom left to righ t << > > F rom left to righ t F rom left to righ t < Less tha n F rom left to righ t <= Less tha n or eq u a ls > G r ea ter tha n > = G r ea ter tha n or eq u a ls == E q u a ls ! = N ot eq u a l & ^ & & || = Bi tw i se AN D op er a ti on Bi tw i se ex clu si v e O R Log i ca l AN D Log i ca l O R F rom left to righ t F rom left to righ t F rom left to righ t F rom left to righ t F rom left to righ t Assi g n men t F rom righ t to left + = Assi g n men t a d d i ti on -= Assi g n men t su b tr a cti on *= Assi g n men t mu lti p li ca ti on /= Assi g n men t d i v i si on % = Assi g n men t mod u le . See y ou Coder s’ G u r u 23-10 -20 0 5 . Assi g n men t r i g ht shi f t Assi g n men t lef t shi f t Assi g n men t b i tw i se AN D Assi g n men t b i tw i se O R Assi g n men t ex clu si v e O R C omma F rom left to righ t I hop e y ou en j oy ed the lesson .> > = <<= & = |= ^ = . I w elcome v er y mu ch the q u esti on s a n d the su g g esti on s. MQL4 COURSE By Coders’ g u ru www.p h sson p ? a p ? a p ? a p ? a fr om tta c h tta c h tta c h tta c h m m m m h e e n e n e n e n re : tid =3 tid =3 tid =4 tid =4 9 9 7 2 6 9 8 1 Y ou c a n d ow n l oa d th e p r e v h ttp :/ / for e x -tsd . B u t th e top b ottom e x e c u tion is n ot th e on l y c a se a n d it h a s tw o e x c e p tion s.c om / a tta c h m Don’t forget to login first.p h t.p h t.forex-t sd. I n th e se c a se s th e fl ow of c on tr ol j u m p s fr om on e p a r t of th e p r og r a m to a n oth e r . A sta te m e n t b y a sta te m e n t.c om / a tta c h m h ttp :/ / for e x -tsd .d e c id e s w h a t to d o in r e sp on se of c ir c u m sta n c e s . Th e n or m a l fl ow c on tr ol of th e p r og r a m y ou w r ite in M Q L 4 ( A n d in oth e r s l a n g u a g e s a s w e l l ) e x e c u te s fr om top to b ottom . A sta tem ent is a line of c od e telling th e c om p u ter to d o som eth ing. iou e n e n e n e n sle t. Th e y a r e th e l oop s a n d th e d e c ision s.c om / a tta c h m h ttp :/ / for e x -tsd . F or ex a m p le: Print("Hello World"). A sem ic olon a t end of th e sta tem ent is a c ru c ia l p a rt of th e sy nta x b u t u su a lly ea sy to forget. a nd th a t' s m a k e it th e sou rc e of 9 0 % of errors.c om / a tta c h m h ttp :/ / for e x -tsd .p h t. ts c a u se su c h j u m p s is c a l l e d Con tr ol Sta te m e n ts. Th e p r og c h a n g in g Sta te m e n Su c h c on r a m s y ou w r ite l ik e -th e h u m a n . retu rn 0 .c om -5Loops & Decisions ---------------------------Part 1 We l c om e to th e fifth l e sson in m y c ou r se a b ou t M Q L 4 . tr ol s c on sist of L oop s a n d D e c ision s. . j + + ) P r in t( j ). j < 15 . F or e x a m p l e : in t j . A n d th is r e p e tition c on tin u e s w h il e som e c on d ition is tr u e a n d e n d s w h e n it b e c om e s fa l se . j+ + ) Th e se th r e e e x p r e ssion s a r e th e in it ia l iz a t io n e x p r e ssion .----------------L oop s c a u sin g a se c tion of y ou r p r og r a m to b e r e p e a te d a c e r ta in n u m b e r of tim e s. N o t e : th e fo r sta te m e n t in n ot fol l ow e d b y a se m ic ol on . for ( j =0 . W h e n th e l oop e n d it p a sse s th e c on tr ol to n e x t sta te m e n t fol l ow th e l oop se c tion . H o w d o e s t h is w o r k ? Th e fo r sta te m e n t c on sists of fo r k e y w or d . th e t e s t e x p r e ssion a n d th e in c r e m e n t e x p r e ssion : j= 0 j< 15 J + + in itia l iz a tion e x p r e ssion te st e x p r e ssion in c r e m e n t e x p r e ssion Th e b o d y of th e l oop is th e c od e to b e e x e c u te d th e fix e d n u m b e r of th e l oop : P r in t ( j) . Th a t' s b e c a u se th e fo r sta te m e n t . j< 15 . I n M Q L 4 th e r e a r e tw o k in d s of l oop s: LOOPS T h e f o r Lo o p -------------------------Th e fo r l oop c on sid e r e d th e e a sie st l oop b e c a u se a l l of its c on tr ol e l e m e n ts a r e g a th e r e d in on e p l a c e . fol l ow e d b y p a r e n th e se s th a t c on ta in th r e e e x p r e ssion s se p a r a te d b y se m ic ol on s: fo r ( j= 0 . T h is ex ec u tes th e b od y of th e loop in ou r ex a m p le for 1 5 tim es. Th e fo r l oop e x e c u te s a se c tion of c od e a fix e d n u m b e r of tim e s. 2 . in t j . w h e n th e l oop fir st sta r ts. w h il e o l in e s of c od e a r e e q u a l . k to k n ow a b ou t th e n ow a b ou t th e v a r ia b l e . for ( i=0 . O r y ou c a n m a k e th e d e c l a r a tion in sid e th e l oop p a r e n th e se s l ik e th is: fo r ( in t j= 0 . Th e I n c r e m e n t e x p r e s s i o n : .5 .9 .a n d th e l oop b od y a r e tog e th e r c on sid e r e d to b e a p r og r a m sta te m e n t.) l ik e th is: in t i.3 .4 .10 .i+ + ) P r in t( i). Th e Te s t e x p r e s s i o n : Th e te st e x p r e ssion a l w a y s a r e l a tion a l e x p r e ssion th a t u se s r e l a tion a l op e r a tor s ( p l e a se r e fe r to r e l a tion a l op e r a tor s in th e p r e v iou s l e sson ). w ith Y ou c a n u se m or e th a t on e in itia l iz a tion e x p r e ssion in fo r l oop b y se p a r a tin g th e m c om m a ( .8 . j+ + ) Th e p r e v iou s tw m or e a b ou t th e Th e ou tsid e d e c v a r ia b l e .13 a n d 14 . A n d its p u r p ose to g iv e th e l oop v a r ia b l e a n in itia l v a l u e ( 0 in ou r e x a m p l e ).j =0 . Th e i n i t i a l i z a t i o n e x p r e s s i o n : Th e in itia l iz a tion e x p r e ssion is e x e c u te d on l y on c e .11. A n d w h e n j r e a c h e s 15 th e l oop w il l stop s a n d th e c on tr ol p a sse s to th e sta te m e n t fol l ow in g th e l oop . j< 15 . e x c e p t th e S c v a r ia b l e d e c l a r a tion a n d sc op e s in th e V l a r a tion m e th od m a k e s e v e r y l in e in th e th e in sid e d e c l a r a tion m a k e s on l y th e fo o p e of e a c a r ia b l e s l e c od e b l oc r l oop to k h v a r ia b l e ( y ou w il l k n ow sson ). I t w il l c on tin u e if th e r e su l t of th e e x p r e ssion is tr u e a n d w il l stop if it fa l se .7 . I t e v a l u a te d b y th e l oop e v e r y tim e th e l oop e x e c u te d to d e te r m in e if th e l oop w il l c on tin u e or w il l stop .1. Y ou c a n d e c l a r e th e l oop v a r ia b l e ou tsid e ( b e for e ) th e l oop l ik e ou r e x a m p l e : in t j. I n ou r e x a m p l e th e b o d y l oop w il l c on tin u e p r in tin g i ( P r in t ( i) ) w h il e th e c a se j< 15 is tr u e .i< 15 . F or e x a m p l e th e j = 0 .12 .6 . in th e in c r e m e n t e x p r e ssion y ou c a n u se m or e th a n on e in c r e m e n t e x p r e ssion in th e fo r l oop b y se p a r a tin g th e m w ith c om m a ( . I n it ia l iz a t io n e x p r e s s io n T e s t e x p r e s s io n F a ls e E x it B o d y o flo o p In c r e m e n t e x p r e s s io n F ig u r e 1 . in t j . a fte r in itia l iz in g th e l oop v a r ia b l e .j =0 . for ( i=0 . te stin g th e e x e c u tin g th e b od y of th e l oop . F ig u r e 1 sh ow s a fl ow c h a r t of th e fo r l oop . B u t y ou c a n on l y u se on e te st e x p r e ssion .i< 15 .i< .j + + ) P r in t( i).Th e in c r e m e n t e in c r e a se it v a l u e I t e x e c u te d a s th te st e x p r e ssion a x p r b y e la n d e ssion c h a n g e s th e v a l u e of th e l oop v a r ia b l e ( j in ou r e x a m p l e ) b y 1.i+ + . st ste p in th e l oop ste p s.F l o w c h a r t o f t h e fo r l o o p L ik e th e in itia l iz a tion e x p r e ssion . .) l ik e th is: in t i. th e p r og r a m th e fir st sta te m e n t th e n th e se c on d on e e v e r y tim e th e l oop e x e c u te d .i< =15 .4 .7 . it’ s n ot on l y c a n in c r e a se th e v a r ia b l e of th e l oop .6 . } Th e a b ov e e x a m p l e w il l e x e c u te th e l oop u n til i r e a c h e s 10 . Y ou c a n u se m u l ti sta te m e n ts in th e l oop b od y d e l im ite d b y b r a c e s l ik e th is: for ( in t i=1.1.2 .11.i> 0 . for ( i=15 .i< 15 .10 . th is is n ot a l w a y s th e c a se .12 . M u l t i s t a t e m e n t in t h e l o o p b o d y : I n ou r p r e v iou s e x a m p l e s. F or e x a m p l e : for ( in t i=0 .14 . w e u se d on l y on e sta te m e n t in th e b od y of th e l oop .9 . T h e B r e a k S ta te m e n t: W h e n th e k e y w or d p r e se n ts in th e fo r l oop ( a n d in w h il e l oop a n d s w it c h sta te m e n t a s w e l l ) th e e x e c u tion of th e l oop w il l te r m in a te a n d th e c on tr ol p a sse s to th e sta te m e n t fol l ow e d th e l oop se c tion . e v e r y tim e it d e c r e a se s i b y 1 a n d c h e c k th e te st e x p r e ssion ( i> 0 ). } I n th e a b ov e c od e th e b od y of th e l oop c on ta in s tw o sta te m e n ts.8 . Th e a b ov e e x a m p l e w il l in itia l iz e th e i to 15 a n d sta r t th e l oop . P l a y Sou n d ( " a l e r t.i--) P r in t( i).i< . D on ’ t for g e t to p u t a se m ic ol on a t th e e n d of e v e r y sta te m e n t.A n oth e r n otic e a b ou t th e in c r e m e n t e x p r e ssion .w a v " ).i+ + ) { P r in t( i).3 . Th e p r og r a m w il l p r od u c e th e se r e su l ts: 15 . b u t it c a n p e r for m a n d op e r a tion it l ik e for e x a m p l e d e c r e m e n ts th e l oop v a r ia b l e l ik e th is: in t i. P r in t( i).i+ + ) { if( ( i==10 ) b re a k . in th a t c a se th e b r e a k k e y w or d w il l e x e c u te .5 .13 . W e w il l in tr od u c e th e w h il e l oop to y ou r ig h t n ow . .1. T h e w h i l e Lo o p --------------------Th e fo r l oop u su a l l y u se d in th e c a se y ou k n ow h ow m a n y tim e s th e l oop w il l b e e x e c u te d . w h il e ( i< 15 ) { P r in t( i).i< 15 .14 . F or e x a m p l e : for ( in t i=0 .1.5 .6 .8 .7 . P r in t( i) } Th e a b ov e e x a m p l e w il l e x e c u te th e l oop u n til i r e a c h e s 10 . in th a t c a se th e c on tin u e k e y w or d w il l g e t th e l oop b a c k to th e top of th e l oop w ith ou t p r in tin g i th e te n th tim e . i+ + ) { if( i==10 ) c on tin u e .w il l te r m in a te th e l oop .6 .5 . Th e c od e w il l p r od u c e th e se v a l u e s: 0 . T h e C o n t in u e S t a t e m e n t : Th e b r e a k sta te m e n t ta k e s y ou ou t th e l oop . w h il e th e c on tin u e sta te m e n t w il l g e t y ou b a c k to th e top of th e l oop ( p a r e n th e se s).11. W h a t h a p p e n if y ou d on ’ t k n ow h ow m a n y tim e s y ou w a n t to e x e c u te th e l oop ? Th is th e w h il e l oop is for . L a te st n o te : Y ou c a n l e a v e ou t som e or a l l of th e e x p r e ssion s in fo r l oop if y ou w a n t. B u t it h a sn ’ t I n itia l iz a tion or I n c r e m e n t e x p r e ssion s.8 .9 . Th e c od e w il l p r od u c e th e se v a l u e s: 0 .9 .3 . Th is is a n e x a m p l e : in t i=0 .3 . Th e w h il e l oop l ik e th e fo r l oop h a s a Te st e x p r e ssion .4 .12 .4 . ) Th is l oop is l ik e w h il e l oop w ith a te st e x p r e ssion a l w a y s se t to tr u e . . for e x a m p l e : fo r ( .13 . i+ + .2 .7 .2 . H o w t h e a b o v e e x a m p le d o e s w o r k ? Th e w h il e sta te m e n t c on ta in s on l y th e Te st e x p r e ssion . l oop e th e s y ou e s th . if it’ s fa l se th e l oop w il l e n d a n d th e c on tr ol p a sse s to th e sta te m e n t fol l ow e d th e l oop se c tion .F l o w c h a r t o f t h e w h il e l o o p I tol d y ou b e for e th a t th e w h il e l oop is l ik e th e fo r l oop . a n d it w il l e x a m in e it e v e r y l oop . b u t th e e l oop v a r ia b l e . m a y th in k . F ig u r e 2 sh ow s a fl ow c h a r t of th e w h il e l oop . th e se a r e th e s im il a r a s p e c t s : . I n th e e x a m p l e th e l oop w il l e x e c u te til l i r e a c h e s 16 in th is c a se i< 15 = fa l s e a n d th e l oop e n d s. y ou c a n n ot d e c l a r e fo r l oop .} I n th e e x a m p l e y ou w il l n otic e th e fol l ow in g s: • • Th e l oop v a r ia b l e h a d d or in itia l iz e it in sid e th e Th e i+ + sta te m e n t h e r e b od y of th e l oop m u st c oth e r w ise th e l oop w ou e c l a r e d a n d in itia l iz e d b e for e th e p a r e n th e se s of th e w h il e l oop l ik is n ot th e in c r e m e n t e x p r e ssion a on ta in som e sta te m e n t th a t c h a n g ld n e v e r e n d . T e s t e x p r e s s io n F a ls e E x it T r u e B o d y o flo o p F ig u r e 2 . if it’ s tr u e th e l oop w il l c on tin u e . Y ou c a n u se 2 . Y ou c a n sin g c a se of u sin g 3 . . ) is w h il e ( t r u e ) I h op e y ou e n j oy e d th e l e sson . I w e l c om e v e r y m u c h th e q u e stion s a n d th e su g g e stion s.1. Se e y ou C o d e r s’ G u r u 2 4 -10 -2 0 0 5 . or m u l ti sta te m e n ts in th e b od y of th e l oop in b oth of th e m . y of fo r ( . Th e sim il a r c b r le m op e a k sta te m e n t a n d c o n t in u e in b oth of th e m . in th e u l ti sta te m e n ts y ou h a v e to d e l im it th e m b y b r a c e s. h e r e ’ s a n e x a m pl e : if ( x < 10 0 ) P r in t ( " h i" ). T h e s e a r e t h e k in d s o f d e c is io n s s t a t e m e n t s a v a il a b l e in M Q L 4 : The i f S t a t em en t -------------------------------T h e i f s t a t e m e n t is t h e s im pl e s t d e c is io n s t a t e m e n t .a n d if it is f a l s e . w e h a v e t a l k e d a b o u t t h e L o o ps . c om -6Loops & Decisions ---------------------------Part 2 We l c o m e t o t h e s ix t h l e s s o n in m y c o u r s e a b o u t M Q L 4 . I n t h e pr e v io u s l e s s o n . T h e s e c o n d w a y is t h e D e c is io n s . in s id e t h e pa r e n t h e s e s t h e T e s t e xp re s s i o n ( x < 1 0 0 ). d e pe n d in g o n t h e v a l u e o f a n e x pr e s s io n . Fig u r e 1 s h o w s t h e f l o w c h a r t o f t h e i f s t a t e m e n t : . w h e n t h e r e s u l t o f t e s t e x pr e s s io n is tru e t h e b o d y o f t h e i f w il l e x e c u t e ( Pri n t( " h i " ) . t h e c o n t r o l pa s s e s t o t h e s t a t e m e n t f o l l o w s t h e i f b lo c k . ) . I h o pe y o u e n j o y e d t h e pr e v io u s l e s s o n s . A n d w e h a v e s e e n t h a t t h e L o o ps a r e o n e o f t w o w a y s w e u s e t o c h a n g e t h e n o r m a l f l o w o f t h e pr o g r a m e x e c u t io n -f r o m t o p t o b o t t o m . D e c is io n s in a pr o g r a m c a u s e a o n e -t im e j u m p t o a d if f e r e n t pa r t o f t h e pr o g r a m . f orex -t sd.MQL4 COURSE By Coders’ guru w w w . H e r e t h e i f k e y w o r d h a s f o l l o w e d b y pa r e n t h e s e s . w a v " ).T e s t e xp re s s i o n T ru e B o d y o f if F al s e E xi t F i g u re 1 . } Notice th e s ym b ol == in th e T es t ex p r es s ion . y o u c a n n e s t i f s . it' s on e of th e R el a tion a l O p er a tor s you h a v e s tu d ied in th e l es s on 4 . op er a tion s & ex p r es s ion s . t h e b o d y o f i f c a n c o n s is t o f m o r e t h a n s t a t e m e n t d e l im it e d b y b r a c e s . Fo r e x a m pl e : if ( c u r r e n t _ pr ic e = = s t o p_ l o s e ) { P r in t ( " y o u h a v e t o c l o s e t h e o r d e r " ). T h is is a s ou r ce of a l ot of er r or s . N e s ti n g : T h e l o o ps a n d d e c is io n s t r u c t u r e s c a n b e b a s t e d in s id e o n e a n o t h e r . w h en you f or g et a n d u s e th e a s s ig n m en t op er a tor = .F l o w c h art o f th e i f s tate m e n t M u l ti S tate m e n ts i n th e i f B o d y : L ik e t h e l o o ps . P l a y S o u n d ( " w a r n in g . a n d s o o n . l o o ps in s id e i f s .th e n th e e ls e te m e n ts . th is is b eca u s e th e i f s ta tem en t a n d th e s ta tem en ts in s id e its b od y. T h a t 's t h e e n t fo llo w e d b a n o th e r s ta te m e t h in i f . it . i< 10 . } I n t h e pr e v io u s e x a m pl e t h e i f s t r u c t u r e n e s t e d in s id e t h e f o r l o o p. Fig u r e 2 s h o w s t h e f l o w c h a r t o f t h e i f … e ls e s ta te m e n t: o n e m e s s a g e . P l a y S o u n d ( " w a r n in g .. i+ + ) if ( i% 2= = 0 ) { P r in t ( " I t ' s n o t a pr im e n o m b e r " ). k o f s ta te m e n ts . The i f . s u ppo s e w e w a n t t o d o m e s in .w a v " ).. if it is n ’ t t r u e . L ik e t h is e x a m pl e : if ( c u r r e n t _ pr ic e > s t o p_ l o s e ) P r in t ( " I t ’ s t o o l a t e t o s t o p. . Notice: you w il l n otice th a t th er e a r e n o b r a ces a r ou n d th e l oop b od y.in s id e l o o ps . e ls e P r in t ( " y o u pl a y in g w e l l t o d a y ! " ). I f t h e t e s t e x pr e s s io n in t h e i f s t a t e m e n t is t r u e . H e r e ' s a n e x a m pl e : f o r ( in t i= 2 . . t h e pr o g r a m pr in t s t h e o t h e r . i f s in s id e i f s . el s e S t a t em en t T h e if a n o th e It c o n s k e y w o s ta te m e n r t h in g if is t o f i f s rd fo llo w t l e t 's it ' s f a ta te m e d b y -----------------------------------------y o u to d o s o m l s e .e y s ta e n t g if a c o n ls e s ta te m te m e n t o r o r a b lo c k d it io n e n t c o a b lo c o f s ta is t r u e . a r e con s id er ed to b e a s in g l e s ta tem en t. pl e a s e s t o p! " ). . T o s o l v e t h is c a s e y o u c a n d o o n e o f t w o t h in g s : . e l s e s t a t e m e n t in r in t ( " y o u pl a y in g w e l l t o d a y ! " ). L ik e t h is : if ( c u r r e n P if ( c u r r e n P e ls e P t _ pr ic r in t ( " t _ pr ic r in t ( " e > It’ e = It’ s t o p_ l o s s to o la te = s t o p_ l o s t im e t o e ) t o s t o p.T e s t e xp re s s i o n T ru e B o d y o f if F al s e B o d y o f e ls e E xi t F i g u re 2 . in n e s t e d if … e l s e s t a t e m e n t s . se ) s t o p! " ). a n d s o o n . pl e a s e s t o p! " ). y o u c a n n e s t if … if … e l s e s t a t e m e n t . y o u c a n in a d v e r t e n t l y m a t c h a n T h e r e ’ s a po t e n t ia l pr o b l e m e l s e w it h t h e w r o n g if .F l o w c h art o f th e i f .e l s e s tate m e n t N e s te d i f … e l s e S tate m e n ts Y o u c a n n e s t if … e l s e s t a t e m e n t in if s s t a t e m e n t s . 1- y o u c a n d e l im it e d t h e i f … if ( c u r r e n { P if ( c u r r e n P e ls e P } t _ pr ic e > s t o p_ l o s e ) e l s e pa ir s w it h b r a c e s l ik e t h is : r in t ( " I t ’ s t o o l a t e t o s t o p, pl e a s e s t o p! " ); t _ pr ic e = = s t o p_ l o s e ) r in t ( " I t ’ s t im e t o s t o p! " ); r in t ( " y o u pl a y in g w e l l t o d a y ! " ); 2- I f y o u c a n ’ t d o t h e f ir s t s o l u t io n ( in t h e c a s e o f a l o t o f if … e l s e s t a t e m e n t s o r y o u a r e l a z y t o d o it ) t a k e it a s r u l e . M atc h e l s e w i th th e n e are s t i f . ( H e r e it ’ s t h e l in e i f ( c u rre n t_ p ri c e = = s to p _ l o s e ) ). The s w i t c h S t a t em en t -----------------------------------------I f y o u h a v e a l a r g e d e c is io n t r e e , a n d a l l t h e d e c is io n s d e pe n d o n t h e v a l u e o f t h e s a m e v a r ia b l e , y o u c a n u s e a s w it c h s t a t e m e n t h e r e . H e r e ’ s a n e x a m pl e : s w it c { c a s P b c a s c a s P h (x ) A S E A " ); e 'A ': r in t ( " C re a k ; e 'B ': e 'C ': r in t ( " C b re d e fa u lt: P r in t ( " N b re a k ; } A S E B o r C " ); a k ; O T A , B o r C " ); I n t h e a b o v e e x a m pl e t h pa r e n t h e s e s y o u ’ l l f in d c o n s ta n t o r a c o n sta n t e e x a m pl e : c as e X + Y : is in v a l id s w e s w it c h k e y w o r d is f o l l o w e d b y pa r e n t h e s e s , in s id e t h e t h e s w i tc h c o n s tan t, t h is c o n s t a n t c a n b e a n in t e g e r , a c h a r a c t e r x pr e s s io n . T h e c o n s t a n t e x pr e s s io n m u s t n ’ t in c l u d e v a r ia b l e f o r it c h c o n s t a n t . H o w th e ab o v e e xam p l e w o rk s ? T h e s w it c h s t a t e m e n t m a t c h e s t h e c o n s t a n t x w it h o n e o f t h e c as e s c o n s tan ts . I n t h e c a s e x= = ' A ' t h e pr o g r a m w il l pr in t " C A S E A " a n d t h e b re ak s t a t e m e n t w il l t a k e y o u t h e c o n t r o l o u t o f t h e s w it c h b l o c k . I n t h e c a s e s x= = ' B ' o r x= = ' C ' , t h e pr o g r a m w il l pr in t " C A S E B o r C " . T h a t ’ s b e c a u s e t h e r e ’ s n o b re ak s t a t e m e n t a f t e r c as e ' B ' :. I n t h e c a s e t h a t x ! = a n y o f t h e c a s e s c o n s t a n t s t h e s w it c h s t a t e m e n t w il l e x e c u t e t h e d e f au l t c a s e a n d pr in t " N O T A , B o r C " . F i g u re 3 s h o w s th e f l o w c h art o f th e s w i tc h s tate m e n t s w i tc h v ari ab l e e q u al s f i rs t c as e c o n s tan t F al s e T ru e F i rs t c as e b o d y s w i tc h v ari ab l e e q u al s s e c o n d c as e c o n s tan t F al s e T ru e S e c o n d c as e b o d y s w i tc h v ari ab l e e q u al s th i rd c as e c o n s tan t F al s e T ru e T h i rd c as e b o d y D e f au l t b o d y E xi t F i g u re 3 - F l o w c h art o f th e s w i tc h s tate m e n t I h o pe y o u e n j o y e d t h e l e s s o n . I w e l c o m e v e r y m u c h t h e q u e s t io n s a n d t h e s u g g e s t io n s . S e e y o u C o d e rs ’ G u ru 25 -10 -20 0 5 MQL4 COURSE By Coders’ guru w w w . f orex -t sd. c om -7Functions ------------------lc o m e T h e fu n c tio Le a r n i n g t h U s in g th e m We to n s e m w th e in w h ic w o r l d o f M Q L4 F u n c t i o n s . a n y la n g u a g e ta k e tw o p h a s e s : h ic h s o m e tim e s a b o rin g th in g . h a l w a y s a lifeboat. fro m h e re : I w a n t t o t e l l y o u m y t r a di t i o n a l s e n t e n c e : I h o p e y o u e n j o y e d t h e p r e v i o u s l e s s o n s , w h i c h y o u c a n do w n l o a d t h e m 1- Le s h ttp 2- Le s h ttp 3- Le s h ttp 4- Le s h ttp 5- Le s h ttp 6- Le s h ttp so n :/ / w so n :/ / w so n :/ / w so n :/ / w so n :/ / w so n :/ / w 1 - W e l c o m e t o t h e M Q L4 c o u r w w .f o r e x -t s d.c o m / a t t a c h m e n t .p 2–S Y N T A X . w w .f o r e x -t s d.c o m / a t t a c h m e n t .p 3 - M Q L4 D a t a t y p e s . w w .f o r e x -t s d.c o m / a t t a c h m e n t .p 4 - M Q L4 O p e r a t i o n s & E x p r e s w w .f o r e x -t s d.c o m / a t t a c h m e n t .p 5- Lo o p s & D e c i s i o n s ( P a r t 1). w w .f o r e x -t s d.c o m / a t t a c h m e n t .p 6 - Lo o p s & D e c i s i o n s ( P a r t 2). w w .f o r e x -t s d.c o m / a t t a c h m e n t .p se . h p ? a t t a c h m e n t i d= 37 2 h p ? a t t a c h m e n t i d= 39 9 h p ? a t t a c h m e n t i d= 469 s io n s . h p ? a t t a c h m e n t i d= 48 1 h p ? a t t a c h m e n t i d= 50 4 h p ? a t t a c h m e n t i d= 547 Le t ’ s s t a r t t h e s e v e n t h l e s s o n . W h a t’ s th e m e a ning of f unctions? T h e fu n c tio n is v e ry lik e th e s a u s a g e o u t s t h e sau sag e. T h e m e a t a n d t h e s p i c e s a r e t h e fu n c v a l u e . T h e m a c h i n e i t s e l f i s t h e fu n c T h e r e ’ s o n l y o n e di f f e r e n c e b e t w e e n th e fu n c tio n s w ill re tu rn n o th in g (n o m ac h in e, y o u i n p u t t h e m eat a n d t h e sp ic es a n d i t tion tion th e th in g p ar am eter s; t h e s a u s a g e i s t h e fu n c tion r etu r n bod y . fu n c tio n s a n dy o u r s a u s a g e m a c h in e , s o m e o f i n M Q L4 c a l l e d v oid ). Le t ’ s t a k e s o m e e x a m p l e s : do u b l e // ty p e o f th e s a u s a g e –r e tu rn v a lu e m y _ f u n c ( do u b l e a , do u b l e b , do u b l e c ) / / f u n c t i o n n a m e a n d p a r a m e t e r s l i s t ( m e a t & s p ic e s ) { r e t u r n ( a * b + c ); // s a u s a g e o u ts -r e tu r n e dv a lu e } A s y o u s e e a b o v e , t h e f u n c t i o n s t a r t s w i t h t h e ty p e o f t h e r e t u r n e d v a l u e “ d ou ble” f o l l o w e d b y t h e fu n c tion n am e w h i c h f o l l o w e d b y p a r e n t h e s e s . I n s i de t h e p a r e n t h e s e s y o u p u t t h e m e a t a n d s p i c e s , s o r r y , y o u p u t t h e p ar am eter s o f t h e fu n c tio n . H e r e w e h a v e p u t t h r e e p a r a m e t e r s d ou ble a, d ou ble b, d ou ble c . T h e n t h e f u n c t i o n b o dy s t a r t s a n d e n ds w i t h b r a c e s . I n o u r e x a m p l e t h e f u n c t i o n b o dy w i l l p r o du c e t h e o p e r a t i o n ( a* b + c ) . T h e r etu r n k e y w o r d i s r e s p o n s i b l e a b o u t r e t u r n i n g t h e f i n a l r e s u l t . R e tur n k e y w or d : T h e r e t u r n k e y w o r d t e r m i n a t e t h e f u n c t i o n ( l i k e t h e br eak i t g i v e s t h e c o n t r o l t o t h e fu n c tion c aller ( w e w i l l k n o w i t T h e r e t u r n k e y w o r d c a n i n c l u de a n e x p r e s s i o n i n s i de i t s p a e x a m p l e r etu r n ( a* b + c ) ; a n d t h i s m e a n s t o t e r m i n a t e t h e o f th e e x p re s s io n . A n dit c a n b e w ith o u t e x p re s s io n a n dits o n ly jo b in th is c a k e y w so o n r e n th fu n c o r d do e s i n t h e l o o p ), a n d ). e s e s lik e th e a b o v e tio n a n dre tu rn th e r e s u lt s e is to te r m in a te th e fu n c tio n . N o t i c e : N o t a l l t h e f u n c t i o n s u s e t h e r e t u r n k e y w o r d, e s p e c i a l l y i f t h e r e ’ s n o r e t u r n v a l u e . Li k e t h e n e x t e x a m p l e : v o id // v o idm e a n th e r e ’ s n o s a u s a g e –re tu rn e dv a lu e . m y _ fu n c ( s tr in g s )// fu n c tio n n a m e a n dp a r a m e te rs lis t ( m e a t & s p ic e s ) { P r i n t ( s ); } T h e fu W h e n T h e se c a llin g n c tio n th e fu k i n ds th e m a b o v e w i l l n o t r e t u r n v a l u e , b u t i t w i l l p r i n t t h e p a r a m e t e r s y o u p r o v i de d. n c t i o n h a s n o r e t u r n v a l u e y o u u s e “ v oid ” a s t h e f u n c i o t n r e t u r n s t y p e . o f f u n c t i o n s i n s o m e p r o g r a m m i n g l a n g u a g e c a l l e d “ M eth od s” , b u t M Q L4 fu n c tio n s . Function ca l l : T h e e x a m p l e a b o v e w i l l p r i n t 2 5 ( i s i t a m a g i c ). i n t s e c o n d_ n u m b e r ) { i n t s u m = c o l l e c t ( f i r s t _ n u m b e r . Y o u b a s i c a l l y c alled th e fu n c tion . u m = c ollec t( a . b u t y o u w a n t to u s e it. s e c o n d_ n u m b e r ). P r i n t ( s u m ). T h i s s t e p i s c allin g it ( u s i n g i t ). T h a t ’ s b e c a u s e t h e c a l l e r l i n e i s t r e a t e d l i k e a n y n o r m a l s t a t e m e n t ( i t ’ s a c t u a l l y a s t a t e m e n t ). b) . i n t s e c o n d_ n u m b e r ) { r e t u r n ( f i r s t _ n u m b e r + s e c o n d_ n u m b e r ). i t w i l l t a k e y o u p a r a m e t e r s a n d g o t o t h e f u n c t i o n a n d i t w i l l r e t u r n –s o o n . h e r e y o u de c l a r e d a v a r i a b l e ( su m ) t o h o l d t h e f u n c t i o n r e t u r n v a l u e a n d g a v e t h e f u n c t i o n i t s t w o p a r a m e t e r s ( a. T h is is th e fu n c tio n : i n t c o l l e c t ( i n t f i r s t _ n u m b e r . = 15. F o r e x a m p le : W e w i l l u s e t h e c o l l e c t f u n c t i o n de s c r i b e d a b o v e i n s i de a n o t h e r n e w f u n c t i o n w h i c h i t s jo b is p rin tin g th e re s u lt o f th e c o lle c tio n : v o i d p r i n t _ c o l l e c t i o n ( i n t f i r s t _ n u m b e r . B u t h o w di d i t k n o w ? T h e m a g i c l i n e i s in t su m = c ollec t( a.W e k n o w v e r y w e l l n o w w h a t t h e f u n c t i o n i s ( I h o p e )? H o w t o u s e t h e f u n c t i o n s i n y o u r M Q L4? T h e r e ’ s a n e x tr a s te p s a fte r w ritin g y o u r fu n c tio n to u s e th e fu n c tio n in y o u p r o g ra m . Y o u u s e it lik e th is : in t a in t b in t s P rin = 10 . b ). M Q L4 w h e n s e e y o u r fu n c tion n am e. b).w i t h t h e r e s u l t a n d p l a c e t h e m i n s a m e l i n e . t ( s u m ). I t’ s v e r y lik e c o p y in g a ll th e lin e s o f th e f u n c tio n in s te a do f th e p la c e y o u c a lle dth e fu n c tio n in . e a s y r ig h t? N e sting f unctions insid e f unction: Y o u c a n n e s t f u n c t i o n ( o r m o r e ) i n s i de t h e b o dy o f a n o t h e r f u n c t i o n . . } Y o u k n o w h o w th e p r e v io u s fu n c tio n w o rk s . A s s u m e y o u h a v e a fu n c tio n w h ic h c o lle c ts th e s u m m a tio n o f tw o in te g e rs . S e e y o u C od er s’ G u r u 25-10 -20 0 5 . W e w i l l k n o w a l o t a b o u t t h e s e f u n c t i o n s i n o u r r eal w or ld lesson s w h e n w e w r i t e o u r o w n E x p e r t a dv i s o r a n d C u s t o m I n di c t o r . I h o p e y o u e n jo y e dth e le s s o n . e v e r y p r o w h e n y o u a tta c h y o u c h a rts o r in th e c a s e jo b is in itia liz in g th e in itia liz a tio n in th e n M Q L 4 S p e cia l f unctions init( ) . I n M Q L4. A n d i t s ( y o u w ill k n o w a b o u t th e v a ria b le s W h e n y o u r p r o g r a m f i n i s h e s i t s j o b o r y o u c l o s e t h e c h a r t w i n do w o r c h a n g e t h e f i n a n c i a l s y m b o l o r t h e c h a r t p e r i o di c i t y o r s h u t do w n M e t a T r a de r t e r m i n a l . y o u s p e n d 9 0 o f y o u r p r o g r a m m i n g l i f e i n s i de t h i s fu n c tio n . v oid m e a n s t h e r e ’ s n o r e t u r n v a l e ( do y o u s t i l l r e m e m b e r ? ). t h e f u n c t i o n " d ein it( ) " ( de -i n i t i a l i z e ) w i l l o c c u r . d e init( ) a nd sta r t( ) : g ra m r p r y o u m a e x t b e g in s w ith th e fu o g r a m ( E x p e r t a dv i s c h a n g e th e fin a n c ia in v a ria b le s o f y o u r l e s s o n ).} H e r e w e c a l l e d t h e c ollec t f u n c t i o n i n s i de t h e p r in t_ c ollec tion f u n c t i o n b o dy a n d p r i n t e d t h e r e s u l t . I w elc om e v er y m u c h th e q u estion s an d th e su g g estion s. n c tio o r o r l s y m p ro g n “ C u b o ra m in it( ) ” ( i n i t i a l i z e ) a n d i t o c c u r s s t o m i n di c a t o r ) t o t h e M e t a T r a de r l o r t h e c h a r t p e r i o di c i t y . T h e t h i r d f u n c t i o n ( w h i c h i s t h e m o s t i m p o r t a n t o n e ) “ star t( ) ” w i l l o c c u r e v e r y t i m e n e w q u o t a t i o n s a r e r e c e i v e d . MQL4 COURSE By Coders’ g u ru w w w . T h e b ox s i z e i s memory s tora g e a rea req u i red i n b y tes .com/ a tta ch men t. i ma g i n e th a t memory i s a s eri es of d i f f eren t s i z e b ox es . th i s w ord k n ow n a s k eyw or d. th i s p roces s i s k n ow n a s decl ar at i on. W h en w e s et th e v a lu e of th e b ox y ou h a v e crea ted i n th e s a me li n e y ou d ecla red th e v a ri a b le. I h op e y ou en j oy ed th e p rev i ou s les s on s a n d I h op e y ou a re rea d y f or th e v a ri a b les ch a llen g e: I recommen d y ou to rea d th e “ D A T A T YP E S ” les s on b ef ore rea d i n g th i s les s on . In th e d ecla ra ti on p roces s y ou u s e a w ord tell th e comp u ter w h a t’ s th e k i n d a n d s i z e of th e b ox y ou w a n t to u s e. T o h elp y ou th i n k of th i s a s a p i ctu re. You ca n d ow n loa d i t h ere: h ttp :/ / f orex -ts d . th e b ox mu s t b e g i v en a n a me. th i s n a me i s th e v ar i abl e cons t ant . f orex -t sd. • • • • • In ord er to u s e a b ox to s tore d a ta . c om -8Variables -------------------- Welcome to my M Q L 4 v a ri a b les . s o th e comp u ter w i ll . W h en w e crea te a v a ri a b le w e a re telli n g th e comp u ter th a t w e w a n t h i m to a s s i g n a s p eci f i ed memory len g th ( i n b y tes ) to ou r v a ri a b le. It h elp s i f y ou g i v e a b ox a mea n i n g f u l n a me th a t rela tes to th e ty p e of i n f orma ti on w h i ch ma k e i t ea s i er to f i n d th e d a ta . s i n ce s tori n g a s i mp le n u mb er. th e v a ri a b les a re th e n a mes th a t ref er to s ecti on s of memory i n to w h i ch d a ta ca n b e s tored . th i s p roces s i s k n ow n a s i ni t i al i z at i on.p h p ? a tta ch men ti d = 4 6 9 N ow . D a ta i s p la ced i n to a b ox b y as s i g ni ng th e d a ta to th e b ox . W h at ar e t h e v ar i abl es m ean? A s I told y ou th e s ecret b ef ore. let’ s enjoy th e V a ri a b les . a letter or a la rg e n u mb er i s n ot g oi n g to occu p y th e s a me s p a ce i n memory . a s k u s w h a t’ s th e k i n d of d a ta a n d h ow mu ch th e len g th of th e d a ta ? T h a t i s th e D a ta ty p e f or. s tri n g . d ou b le. color a n d d a teti me) w i th th e n a me y ou ch os e to th e v a ri a b le. b ool. i nt D ecla ra ti on M yV ar ai bl e V a ri a b le’ s con s ta n t. In M Q L 4 . F or ex a mp le i f w e s a i d th i s li n e of cod e to th e comp u ter: i n t M y V a ra i b le= 0 . T o k n ow w h a t’ s th e v a ri a b le. ch a r. In th e p rev i ou s ex a mp le w e h a v e u s ed : i nt Key w ord i nt In teg er d a ta ty p e. B y u s i n g th e k eyw or ds y ou h a v e lea rn ed i n th e D A T A T YP E S les s on ( i n t. th es e a re th e k i n d s of D a ta ty p es : • • • • • • • In teg er ( i n t) B oolea n ( b ool) C h a ra cter ( ch a r) S tri n g ( s tri n g ) F loa ti n g -p oi n t n u mb er ( d ou b le) C olor ( color) D a teti me ( d a teti me) I’ v e cop i ed th e p rev i ou s f ew li n es f rom th e D A T A T YP E S les s on f or y ou . T h a t’ s mea n w e a re a s k i n g th e comp u ter to s et a b lock of 4 b y tes len g th to ou r v a ri a b le n a med “ M y V a ra i a b le” . n ow h ow d o to d ecla re th e v a ri a b les : D ec larat io n : D ecla ri n g a v a ri a b le mea n s to i n trod u ce i t to th e w orld a n d s p eci f y i ts ty p e. F or ex a mp le: i n t M y V a ra i b le. = 0 In i ti a li z a ti on W e w i ll k n ow more a b ou t v a ri a b les i n a comi n g les s on . . S o w e ca n ’ t w ri te a li n e a f ter th e f u n cti on a b ov e s a y i n g f or ex a mp le: d= 1 0 . w h i ch ca n b e u s ed on ly i n s i d e th e f u n cti on b lock of cod e ( a n y th i n g b es i d e th e b ra ces ) a n d ca n ’ t b e u s ed b y ou ts i d e cod e. … … M y V a ra i b le= 5 . You ca n i n i ti a li z e th e v a ri a b le a t th e s a me li n e of th e d ecla ra ti on li k e th e ex a mp le: i nt M yV ar ai bl e= 0 .b. F or ex a mp le th e v a ri a b les d ecla red i n s i d e f u n cti on a re loca l to th e f u n cti on b lock of cod e. I n it ializ at io n : In i ti a li z i n g th e v a ri a b le mea n s to a s s i g n a v a lu e to i t. A n d y ou ca n d ecla re th e v a ri a b le i n on e p la ce a n d i n i ti a li z e i t i n a n oth er p la ce li k e th i s : i n t M y V a ra i b le. F or ex a mp le: d ou b le my _ f u n c ( d ou b le a . } In th e a b ov e ex a mp le th e v a ri a b les a. a n d th e v a ri a b les d ecla red i n s i d e th e loop or d eci s i on s b lock of cod e a re loca l to th os e b lock s a n d ca n b e s een or u s ed ou ts i d e th em. A n d b ef ore n ’ t u s e th e M yV ar i abl e i n y ou r cod e. B u t k eep i n y ou r mi n d th i s f a ct: t h e decl ar at i on m u s t be bef or e t h e i ni t i al i z at i on. S c o p es o f v ariables: T h ere a re tw o s cop es of th e v a ri a b les . . S cop e mea n s . b eca u s e d i s n ot s een to th e n ex t li n e of th e f u n cti on b eca u s e i t’ s ou ts i d e i t. L ocal v ar i abl e mea n s th ey a re n ot s een to ou ts i d e w orld w h ere th ey h a d d ecla red . L oca l a n d G lob a l. d ou b le b . f or ex a mp le M yV ar ai bl e= 0 . retu rn ( a * b + c) .c a n d d a re loca l v a ri a b les . If y ou u s ed i t w i th ou t comp i ler w i ll comp la i n a n d w i ll tell y ou s ometh i n g li k e ar i abl e not def i ned. d ou b le c) { in td . 1 er r or ( s ) .H ere y ou d ecla red th e d ecla ra ti on y ou d ecla ra ti on th e M Q th i s :' M yV ar ai bl e' a v ca L 4 -v a ri a b le n a med M yV ar ai bl e w h i ch i s a n i n teg er ty p e. w h i ch p a rt of cod e w i ll k n ow a b ou t th e v a ri a b le a n d ca n u s e i t. 0 w ar ni ng ( s ) . T h e G lob a l v a ri a b les w i ll a u toma ti ca lly s et to z er o i f y ou d i d n ’ t i n i ti a li z e th em. / / b lu e i n t i n i t( ) { .0 x 0 0 . } H ere th e v a ri a b le G l obal _ V ar i abl e d ecla red ou ts i d e th e f u n cti on ( f u n cti on lev el d ecla ra ti on ) s o. E x t ern v ariables: T h e k ey w ord “ ex t er n” u s ed to d ecla re a s p eci a l k i n d of v a ri a b les .T h e s econ d k i n d of th e s cop es i s th e G l obal v ar i abl es .0 x F F ' . . d ou b le c) { retu rn ( a * b + c + G lob a l_ V a ri a b le) . w h i ch y ou ca n s et th em f orm th e p rop erty of y ou r E x p ert a d v i s or or C u s tom i n d i ca tor. F or ex a mp le: ex tern color In d i ca tor_ color = C ' 0 x 0 0 . th os e k i n d s of v a ri a b les a re u s ed to d ef i n e i n p u t d a te of th e p rog ra m. d ou b le my _ f u n c ( d ou b le a . i t ca n b e s een b y a ll th e f u n cti on s i n y ou p rog ra m. L ook a t F i g u re 1 .. F or ex a mp le: i n t G lob a l_ V a ri a b le. d ou b le b . } H ere th e v a ri a b le I ndi cat or _ col or h a d d ef i n ed a s a n ex t er n v a ri a b le w h i ch y ou w i ll s ee i t th e f i rs t ti me y ou a tta ch y ou r i n d i ca tor ( or E A ) to th e M eta T ra d er ch a rt a n d w h i ch y ou ca n ch a n g e i t f rom th e p rop erti es s h eet w i n d ow s . a n d th ey a re th e v a ri a b les w h i ch h a d d ecla red ou ts i d e a n y b lock of cod e a n d ca n b e s een f rom a n y p a rt of y ou r cod e.. S ee y ou C oder s ’ G u r u 2 9 -1 0 -2 0 0 5 . I h op e y ou en j oy ed th e les s on . ma k e i t ex tern v a ri a b le. I w el com e v er y m u ch t h e q u es t i ons and t h e s u g g es t i ons . A p p l y_ t o a n d S t yl e a re v a ri a b les d ef i n ed u s i n g th e “ ex t er n” k ey w ord s o th ey a p p ea r i n th e p rop erty s h eet. M A _ m et h od.F i g u r e 1 : P r op er t y s h eet of M A i ndi cat or H ere th e v a ri a b les P er i od. A n y v a ri a b le y ou w a n t th e u s er of y ou r p rog ra m b e a b le to ch a n g e a n d s et. S h i f t . h> th at’ s mean you telli n g th e comp i ler to i n clu d e th e con ten t of th e f i le “w in 3 2 . F or ex amp le i f you u sed th e p r ep r ocessor d i r ecti v e # in clu de < w in 3 2 .MQL4 COURSE By Coders’ g u ru -9Preprocessors -------------------i n th i s ser i es.def in e direct iv e: Th e con stan t i s v er y li k e th e v ar i ab le w i th on ly on e d i f f er en t. S o I r ecommen d you to r ead all th e n i n e lesson s car ef u lly b ef or e th e r eal w or k star ts. h” i n th e p lace you w r ote th e i n clu d e k eyw or d b ef or e p r ocessi n g you r cod e. N ow . you set i ts v alu e on ly on ce an d you can n ot ch an g e i ts v alu e i n you r cod e li k e th e v ar i ab le. F or ex amp le: # d ef i n e my_ con stan t 1 0 0 def in e d i r ecti v e u sed to g en er ate a con stan t. I n th e n ex t ser i es of lesson s w e w i ll star t to b u i ld ou r f i r st C u stomer I n d i cator . let’ s en j oy th e P r ep r ocessor s: Welcome to my last theoretical lesson W h a t a re t h e Preprocessors m ea n ? P r ep r ocessor s ar e th e i n str u cti on s you g i v e to th e comp i ler to car r y th em ou t b ef or e star ti n g ( p r ocessi n g ) you r cod e. I n M Q L 4 th er e ar e f ou r of p r ep r ocessor s d i r ecti v es: 1. . com" # p r op er ty cop yr i g h t " A n yon e w an ts to u se" Th i s i s th e li st of th e M Q L 4 p r ed ef i n ed con stan ts: li n k C on stan t cop yr i g h t str i n g str i n g Typ e a li n k to th e comp an y w eb si te th e comp an y n ame D escr i p ti on .propert y direct iv e: Th er e ar e p r ed ef i n ed con stan ts called “Con trollin g Com p ilation ” i n clu d ed i n th e M Q L 4 lan g u ag e. w h i ch you can set th em i n you r p r og r am.f or ex -tsd . Th e n ame of con stan t ob eys th e same r u les you h ad lear n t ab ou t ch oosi n g th e i d en ti f i er n ames ( lesson 2 S Y N TA X ). S o you can u se th e ab ov e con stan t i n you r cod e li k e th at: su m = con stan t1 * 1 0 .A s you can n oti ce i n th e ab ov e ex amp le th er e’ s n o assi g n men t symb ol ( =) b u t on ly sp ace b etw een th e con stan t n ame ( m y _ con s tan t ) an d i ts v alu e ( 1 0 0 ). Th ey ar e th e p r op er ti es of you r p r og r am w h i ch you can set th em u si n g th e comp i ler d i r ecti v e “p rop erty ” an d th e comp i ler w i ll w r i te th em i n th e setti n g s of you r ex ecu tab le p r og r am ( ex 4 f i le). Th e comp i ler w i ll r ep lace each occu r r en ce of con stan t n ame i n you r sou r ce cod e w i th th e cor r esp on d i n g v alu e. 2. Th e v alu e of th e con ten t can b e an y typ e you w an t. A n d you can n oti ce too th at th e li n e d i d n ’ t en d w i th semi -colon b u t i t en d ed w i th a car r i ag e-r etu r n ch ar acter ( n ew li n e). F or ex amp le: # p r op er ty li n k " h ttp :/ / w w w . f or ex amp le you can ’ t star t th e con stan t n ame w i th a n u mb er or ex ceed s 3 1 ch ar acter s. w h er e N li es b etw een 1 an d 8 p r ed ef i n ed lev el N f or sep ar ate w i n d ow cu stom i n d i cator . I f th e f i le you w an t to i n clu d e located at th e same p ath of you r cod e. w h er e N li es b etw een 1 an d 8 b ef or e scr i p t r u n messag e b ox w i th con f i r mati on ap p ear s b ef or e scr i p t r u n i ts p r op er ty sh eet ap p ear s. i t’ s v er y li k e w h en you cop y th e en ti r e f i le con ten t an d p aste i t i n th e p lace of th e li n e you w r i te i n clu d e. u p to 8 i n d i cator _ max i mu m th e color f or d i sp layi n g li n e N . h” an d r ead s all of i ts con ten t an d cop y th em i n th e same p lace of th e i n clu d e statemen t.h > I n th e ab ov e ex amp le you telli n g th e comp i ler to op en th e f i le “w in 3 2 . you h av e to u se q u otes i n stead of an g le b r ack ets li k e th i s: . d i sab les sh ow _ con f i r m p r op er ty 3. ter mi n al_ d i r ector y\ex p er ts\i n clu d e) to sear ch f or th e f i le w in 3 2 .stack si z e i n d i cator _ ch ar t_ w i n d ow i n d i cator _ b u f f er s in t i n d i cator _ sep ar ate_ w i n d ow i n d i cator _ mi n i mu m i n d i cator _ color N i n d i cator _ lev elN sh ow _ con f i r m sh ow _ i n p u ts v oi d v oi d in t in t in t color d ou b le v oi d v oi d stack si z e sh ow th e i n d i cator i n th e ch ar t w i n d ow sh ow th e i n d i cator i n a sep ar ate w i n d ow th e b ottom b or d er f or th e ch ar t th e top b or d er f or th e ch ar t th e n u mb er of b u f f er s f or calcu lati on .in cl u de direct iv e: W h en you ask i n g th e comp i ler to i n clu d e a f i le n ame w i th th e “in clu de” d i r ecti v e. h an d d on ’ t sear ch th e cu r r en t d i r ector y. N ote: i n th e ab ov e ex amp le you en closed th e f i le n ame w i th A n g le b r ack ets ( < > ) an d th at’ s mean you telli n g th e comp i ler to u se th e d ef au lt d i r ector y ( u su ally. F or ex amp le: # i n clu d e < w i n 3 2 . str i n g lp C ap ti on . i n t R eleaseD C ( i n t h W n d . .str i n g lp C ap ti on .i n t h D C ).d ll" i n t M essag eB ox A ( i n t h W n d . 4.str i n g lp Tex t.h ” I n th e b oth cases i f th e f i le can ’ t b e f ou n d you w i ll g et an er r or messag e.ex 4 ) or li b r ar y f i les ( .d ll" i n t G etD C ( i n t h W n d ).str i n g lp C ap ti on . F or ex amp le: # i mp or t " u ser 3 2 .str i n g lp Tex t. i n t u Typ e).i n t w L an g u ag eI d ). # i mp or t W h en you i mp or t f u n cti on s f r om “ex 4 ” f i le you h av en ’ t to d eclar e th ei r f u n cti on s to b e r ead y f or u se. i n t M essag eB ox E x A ( i n t h W n d . Y ou can u se i n clu d e at an yw h er e you w an t b u t i t u su ally u sed at th e b eg i n n i n g of th e sou r ce cod e. W h i le i mp or ti n g th e f u n cti on s f r om a “. Y ou u se im p ort on ly w i th M Q L 4 ex ecu tab les f i les ( .d ll” f i le r eq u i r es you to d eclar e th e f u n cti on s you w an t to u se li k e th i s: i n t M essag eB ox A ( i n t h W n d . B u t th er e ar e d i f f er en ces b etw een th em. i n t u Typ e). i n t u Typ e.ex 4 " # i mp or t " g d i 3 2 .d ll) to i mp or t th ei r f u n cti on s to you r p r og r am. # i mp or t " meli b .im port direct iv e: I t’ s li k e i n clu d e d i r ecti v e i n th e asp ect of u si n g ou tsi d e f i le i n you r p r og r am.# i n clu d e “myli b .str i n g lp Tex t. A n d on ly th e f u n cti on s you h as d eclar ed you can u se i n you r cod e. T ip : It’s a good programming practice to write the f req u entl y u sed code in a separate f il e and u se incl u de directiv e to pu t it in y ou r code when y ou need ( j u st an adv ice) . I w elcom e v ery m u ch the q u es tion s an d the s u g g es tion s . I h op e you en j oyed th e lesson . A n d I h op e you ar e r ead y n ow f or you r f i r st C u stom I n d i cator . S ee you Coders ’ G u ru 3 0 -1 0 -2 0 0 5 .Y ou mu st en d th e i mp or t d i r ecti v es w i th a b lan k i mp or t li n e # im p ort ( w i th ou t p ar ameter s). If y ou w a n t t o r un M et a E d i t or y ou h a v e t h r ee ch oi ces. ch oose M et a E d i t or f r om T ools men u or cli ck i t s i con on t h e S t a n d a r d t oolb a r ( F i g ur e 1) . 2.ex e a n d cli ck i t ( I r ecommen d t o ma k e a sh or t cut on y ou d esk t op ) . t h en cli ck F 4 . comp i le y our p r og r a m a n d M or e. T od a y w e a r e g oi n g t o cr ea t e a si mp le i n d i ct or w h i ch w i ll n ot mea n t oo much f or our t r a d e w or ld b ut i t mea n s t oo much t o our M Q L 4 p r og r a mmi n g un d er st a n d i n g . f i n d t h e M et a E d i t or . 1.MQL4 COURSE By Coders’ g u ru -10- ------------------------------- Your Fi rs t In d i c a t or P a rt 1 Welcome t o t h e p r a ct i ca l w or ld of M Q L 4 cour ses. t h a t ’ s b eca use w e w i ll use t h em so much i n our ex p la n a t i on s a n d st ud i es of t h e E x p er t A d v i sor s a n d Cust om In d i ca t or s w h i ch w e w i ll cr ea t e i n t h i s ser i es of lesson s. Let’s swim! MetaEditor: T h i s i s t h e p r og r a m w h i ch h a s b een sh i p p ed w i t h M T 4 ( M et a T r a d er 4) en a b les y ou t o w r i t e y our p r og r a ms.F i n d t h e M T 4 i n st a lla t i on p a t h ( usua lly C:\P r og r a m F i les\M et a T r a d er 4) . r ea d M Q L 4 h elp . y ou w i ll k n ow ev er y t h i n g v er y soon . 3. w elcome t o y our f i r st i n d i ca t or i n M Q L 4. It si mp ly w i ll collect t h e sub t r a ct i on of High [] of t h e p r i ce – L o w [] of t h e p r i ce.F r om S t a r t men u P r og r a ms. I r ecommen d y ou t o r ea d t h e p r ev i ous n i n e lesson s v er y ca r ef ully . Figure 1 – M et a T ra d er S t a n d a rd T o o l b a r . b ef or e con t i n ui n g w i t h t h ese ser i es of cour ses. d on ’ t b e i n a h ur r y . I’ v e ma d e a sh or t cut f or M et a E d i t or on my d esk t op f or ea si ly a ccess t o t h e p r og r a m.R un M T 4. f i n d M et a T r a d er 4 g r oup t h en cli ck M et a E d i t or . T h e E d i t or w i n d ow w h i ch y ou ca n w r i t e y our p r og r a m i n . H elp t a b .T h e T oolb ox w i n d ow w h i ch con t a i n s t h r ee t a b s: a . y ou see h er e t h e f i les w h i ch con t a i n t h e k ey w or d y ou a r e sea r ch i n g f or usi n g t h e t oolb a r comma n d “ F i n d i n f i les” or b y cli ck i n g CT R L + S H IF T + F h ot k ey s. 3. c. E r r or s t a b .A n y met h od y ou h a v e ch osen lea d s y ou t o M et a E d i t or a s y ou ca n see i n f i g ur e 2. y ou ca n h i g h li g h t t h e k ey w or d y ou w a n t t o k n ow mor e a b out i t a n d cli ck F 1. f or ea sy a ccess t o t h e f i les sa v ed i n t h e M T 4 f old er . Editor w in dow N av ig ator W in dow T ool b ox w in dow Figure 2 – M et a E d it o r W in d o w s I r ecommen d y ou t o n a v i g a t e a r oun d t h e M et a E d i t or M en us. F i les t a b . y ou see h er e t h e er r or s ( i f t h er e a n y ) i n y our cod e. S ea r ch t a b en a b les y ou t o sea r ch t h e M Q L 4 d i ct i on a r y . N ow let ’ s en j oy cr ea t i n g our f i r st cust om i n d i ca t or .T h e N a v i g a t or w i n d ow w h i ch con t a i n s t h r ee t a b s: a . A s y ou ca n see i n f i g ur e 2. b . t h er e a r e t h r ee w i n d ow s i n M et a E d i t or : 1. b . D i ct i on a r y t a b en a b les y ou t o a ccess t h e M Q L 4 h elp sy st em. F i n d i n f i les t a b . a n d y ou w i ll see t h e h elp t op i cs i n t h i s t a b . 2. . c. T oolb a r a n d w i n d ow s t o b e f a mi li a r w i t h i t . Figure 3 . y ou w i ll g et t h e secon d st ep w i z a r d ( F i g ur e 4) w h i ch w i ll en a b le y ou t o ed i t t h e p r op er t i es of y our p r og r a m. In t h i s st ep y ou ca n en t er t h ese p r op er t i es: . T o cr ea t e a cust om i n d i ca t or y ou h a v e t o st a r t w i t h t h r ee st ep s ( y ou w i ll lea r n la t er h ow t o sk i p t h ese b or i n g st ep s ( my p er son a l op i n i on ) .C us t o m I n d ic a t o r is a p ro gra m w h ic h en a b l es y o u t o us e t h e f un c t io n s o f t h e t ec h n ic a l in d ic a t o rs a n d it c a n n o t a ut o m a t e y o ur d ea l s .N ew p ro j ec t w iz a rd S t e p 2: W h en y ou cli ck ed N e x t . S t e p 1: Cli ck F il e men u N e w ( y ou use CT R L + N h ot k ey or cli ck t h e N ew Icon i n t h e S t a n d a r d t oolb a r ) . Y ou w i ll g et a w i z a r d ( F i g ur e 3) g ui d i n g y ou t o t h e n ex t st ep . let ’ s U S E i t . F irs t th ree s tep s : N ow y ou h a v e r un y our M et a E d i t or a n d n a v i g a t ed a r oun d i t s M en us. a n d t h en cli ck n ex t . T oolb a r a n d w i n d ow s. Ch oose Cust om In d i ca t or P r og r a m op t i on . E x t e r n a l v a r i a b les li st : I w a n t t o p a use h er e t o r ememb er y ou a b out ex t er n a l v a r i a b le. color s a n d w h er e t o d r a w y our i n d i ca t or ( i n t h e ma i n ch a r t or i n sep a r a t e w i n d ow s) .A u t ho r n a me. f or ex a mp le: h ow ma n y li n es.1. m q 4 2.N a m e of y our p r og r a m. In our f i r st i n d i ca t or ex a mp le w e w i ll n ot n eed a n y ex t er n a l v a r i a b les j ust w r i t e t h e v a lues y ou see i n f i g ur e 4 a n d let ’ s g o t o st ep 3 b y cli ck i n g N e x t b ut t on . 3. S t e p 3: T h e t h i r d w i z a r d y ou w i ll g et w h en y ou cli ck ed N e x t b ut t on i s t h e D r a w i n g p r op er t i es w i z a r d ( F i g ur e 5) . . t h i s i s t h e n a me w h i ch t h e w or ld w i ll ca ll y ou p r og r a m w i t h a n d i t w i ll b e sa v ed a s t he _ n a m e _ y o u _ ha v e _ c ho s e n . Figure 4 – P ro gra m p ro p ert ies w iz a rd . 4. It s j ob i s en a b li n g y ou t o set t h e d a w n i n g p r op er t i es of t h e li n es of y our i n d i ca t or . F or ex a mp le: M A _ P e r io d i n t h e v er y p op ula r E M A i n d i ca t or . A n d t h ese v a r i a b les w i ll b e d ecla r ed w i t h t h e “ e x t e r n ” k ey w or d i n y our cod e ( P lea se r ev i ew V a r ia b l e s lesson ) . E x t er n a l v a r i a b les a r e t h e v a r i a b les w h i ch w i ll b e a v a i la b le t o t h e user of y ou i n d i ca t or t o set f r om t h e p r op er t i es t a b of y our i n d i ca t or i n M et a T r a d er . t h i s sect i on of t h e w i z a r d en a b les y ou t o a d d t h ese k i n d s of v a r i a b les. t h e cr ea t or of t h e p r og r a m n a me.L in k t o y our w eb si t e. S o. M in im u m op t i on : i t w i ll b e a v a i la b le ( en a b led ) on ly i f y ou h a v e ch eck ed t h e In d i ca t or i n sep a r a t e w i n d ow op t i on . a n d i t s j ob i s set t i n g t h e t op b or d er f or t h e ch a r t 4. 3. 2. a n d i t s j ob i s set t i n g t h e b ot t om b or d er f or t h e ch a r t . If y ou d i d n ’ t ch eck t h e op t i on .T h i s w i z a r d con t a i n s t h e f ollow i n g op t i on s: 1. F or our f i r st i n d A d d b ut t on . I w a n t y ou t o w a h ur r y . y our i n d i ca t or w i ll b e d r a w n i n t h e ma i n ch a r t w i n d ow . y our i n d i ca t or w i ll b e d r a w n i n sep a r a t e w i n d ow s a n d n ot on t h e ma i n ch a r t w i n d ow .D r a w i n g p r op er t i es w i z a r d .M a x im u m op t i on : i t w i ll b e a v a i la b le ( en a b led ) on ly i f y ou h a v e ch eck ed t h e In d i ca t or i n sep a r a t e w i n d ow op t i on . W h en y ou cli ck F in is h b ut t on t h e M a g i c w i ll st a r t . Y ou w i ll see t h e w i z a r d d i sa p p ea r ed a n d t h e f ocus r et ur n ed t o t h e M et a E d i t or en v i r on men t a n d … g uess w h a t ? . F i g ur e 5 . ch oose In d i ca t or i n sep a r a t e w i n d ow op t i on a n d cli ck en y ou cli ck a d d b ut t on t h e w i z a r d w i ll a d d a li n e t o t h e i n d ex es li st li k e e 5.In d ic a t o r in s e p a r a t e w in d o w op t i on : b y cli ck i n g t h i s op t i on . w h y ou see i n f i g ur a i t t o t h e n ex t lesson ( s) t o k n ow mor e a b out t h ese op t i on s a n d d on ’ t b e i n i ca t or ex a mp le.In d e x e s L i st : h er e y ou a d d y our i n d i ca t or li n e a n d set i t s d ef a ult color s. } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0).ExtMapBuffer1).indicators SetIndexStyle(0.mq4 | //| Codersguru | //| http://www. } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { int counted_bars=IndicatorCounted(). //---//---return(0). SetIndexBuffer(0.Y ou h a v e r ea d y t o use f i r st i n d i ca t or d r a f t cod e.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Codersguru" #property link "http://www. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---.DRAW_LINE). T h i s i s t h e cod e y ou w i ll g et : //+------------------------------------------------------------------+ //| My_First_Indicator.com" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Red //---.buffers double ExtMapBuffer1[]. } //+------------------------------------------------------------------+ .forex-tsd. //---return(0). In t h e n ex t lesson w e w i ll d i scov er ev er y li n e of cod e y ou h a v e seen a b ov e a n d a d d our cod e t o ma k e our f i r st i n d i ca t or . I w e l c o m e v e r y m u c h t he q u e s t io n s a n d t he s u gge s t io n s . t h e w i z a r d h a s w r i t t en a lot of cod e f or y ou. S ee y ou C o d e r s’ G u r u 0 1-11-20 0 5 .A s y ou see i n t h e a b ov e cod e. T o t h i s lesson I h op e y ou b e r ea d y ! P lea se d on ’ t f or g et t o d ow n loa d t h e sour ce cod e of t h e f i r st i n d i ca t or a n d w a r m y our self f or t h e n ex t lesson . n ow I h a v e t o t h a n k t h e w i z a r d a n d t o t h a n k y ou t oo. Afterwards. that’s because the New Project Wizard wrote all the code for us.forex-tsd.forex-tsd.forex-tsd. .DRAW_LINE). Thanks! Today we are going to add few lines to the code the wizard had generated to make our program more useful.MQL4 COURSE By Coders’ guru www.indicators SetIndexStyle(0.com -11- Your First Indicator Part 2 ------------------------------- Welcome to the second part of “Your First Indicator” lesson.buffers double ExtMapBuffer1[]. In the previous lesson we didn’t write any line of code. we are going to explain the whole of the code line by line.ExtMapBuffer1).mq4 | //| Codersguru | //| http://www. string short_name = "Your first indicator is running!". IndicatorShortName(short_name).com | //+------------------------------------------------------------------+ #property copyright "Codersguru" #property link "http://www. Let’s coding Code we have added: We have added the code which in a bold dark blue to our previous code: //+------------------------------------------------------------------+ //| My_First_Indicator.com" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Red //---. SetIndexBuffer(0. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---. int pos=Bars-counted_bars. dResult = dHigh .dLow. we will explain the line(s) of code directly. //---. I want to here your suggestion about this method please! Now let’s crack this code line by line. ExtMapBuffer1[pos]= dResult . //---. dLow = Low[pos]. Comment("Hi! I'm here on the main chart windows!"). But at the most of the time we will pause to discuss some general topics. if there are no topics. double dHigh .//---return(1). pos--.main calculation loop while(pos>=0) { dHigh = High[pos]. dLow . } //---return(0). . } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0).check for possible errors if (counted_bars<0) return(-1). } //+------------------------------------------------------------------+ How will we work? We will write the line(s) of the code we are going to explain then we will explain them afterwards.last counted bar will be recounted if (counted_bars>0) counted_bars--. } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { int counted_bars=IndicatorCounted(). //---. dResult. forex-tsd. author and the link and wrote them as comments at the top of our program. In our program the MQL4 wizard gathered from the data we entered the name of the program. The Preprocessors are the instructions you give to the compiler to carry them out before starting (processing) your code. • To make it understandable. • To tell us how the code you have written is work. That’s because they are kind of the Preprocessors directives called property directives.com | //+------------------------------------------------------------------+ Comments: The first five lines of code (which are in gray color) are comments.com" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Red Property directive: As you notice all of these lines start with the word (#property). You are commenting your code for a lot of reasons: • To make it clearer • To document some parts like the copyright and creation date etc. #property copyright "Codersguru" #property link "http://www. You use Comments to write lines in your code which the compiler will ignore them.forex-tsd.mq4 | //| Codersguru | //| http://www. • … You can write comments in two ways: Single line comments: The Single line comment starts with “//” and ends with the new line. Multi-line comments: The multi-line comment start with “/*” and ends with “*/” and you can comment more than one line.//+------------------------------------------------------------------+ //| My_First_Indicator. . . The data type of this property is integer. indicator_separate_window: When you set this property. or drawing them in separate windows by choosing the indicator_separate_window. same as the link property you asked to enter it in step 2 in the Expert Advisor Wizard. You can set the scale of the separate indicator window using two properties indicator_minimum for the minimum value and indicator_maximum for the maximum value of the scale. the default value is 16384. your indicator will be drawn in the main chart window (Figure 1). your indicator will be drawn in a separate window (Figure 1). which means it takes no value. indicator_chart_window: When you set this property. You can’t use the both of them at the same time. You have to choose one of two options for your Indicators. stacksize: It’s an integer value sets the memory size for every thread. link: This property setting the web link to your web site which you asked to enter it in step 2 in the Expert Advisor Wizard (review the previous lesson). We will try to discuss here the property directives available in MQL4. For example: is your Indicator will appear in the main chart window or in a separate window? Who is the writer of the program? Note: The preprocessors lines end with a carriage-return character (new line) not a semi-colon symbol. The data type of this property is string. The data type of this property is string.The property directives are predefined constants called “Controlling Compilation” built in the MQL4 language. The data type of this property is void. drawing them in the main chart windows by using this property. their job is setting the properties of your program. copyright: It’s the name of the author of the program. And you can set the level of your indicators on these scales using the property indicator_levelN where’s the N is the indicator number. . This value must be greater than the indicator_minimum value. In our program we will draw our indicator in a separate window: #property indicator_separate_window Main chart window Separate window Figure 1 indicator_minimum: With the aid of this property we are setting the minimum value of the separate windows scale. which mean they don’t take value and you just write them. indicator_maximum: With the aid of this property we are setting the maximum value of the separate windows scale.Both of the properties indicator_chart_window and indicator_separate_window are void data type. hence we have a scale ranged from 0 to 100 in our separate window which we are drawing our indicator. For example: #propery indicator_minimum 0 #propery indicator_ maximum 100 Here we have set the bottom border of the window to 0 and the top border to 100 (see indicator_ maximum). The data type of this property is integer. The data type of this property is integer. which is the top border of the windows. which is the bottom border of the windows. The user of your Indicator can change this color from the properties dialog of your Indicator (Figure 2). In our program the indicator line color will be red. #property indicator_color1 Red The data type of this property is color.5 //set the second indicator buffer level The data type of this property is double. you can set the color of each of them using this property indicator_colorN . where the N is the line number which defined by indicator_buffers. #property indicator_buffers 1 That’s because we will draw only one line. this value must be greater than the indicator_minimum value and smaller than the indicator_maximum value. so we can set the indicator_level for each of them using its number). When we set the number (ranged from 1 up to 8) we are telling MQL4: “Please allocate a memory space for me to draw my indicator line”. . For example: #propery indicator_minimum 0 #propery indicator_minimum 100 #propery indicator_level1 10 //set the first indicator buffer level #propery indicator_level2 65. N is the indicator number which we are setting its level. indicator_colorN: We can use up to 8 lines in our indicator.indicator_levelN: With the aid of this property we are setting the level of the indicator in the scale we have created with the properties indicator_minimum and indicator_maximum. it must range from 1 to 8 (because we are allowed only to use up to 8 indicator buffers in our program. In our program we used only one buffer. indicator_buffers: With the aid of this property we are setting the number of memories spaces (Arrays) allocated to draw our line(s). In our program we used this line of code: double ExtMapBuffer1[].24. . Arrays are very like the list tables. You can initialize the array at the same line of the declaration like that: int my_array[5] = {1. like that: My_array[10] = 500. in the programming we also need to group together the data items of the same type. Here. You can access each item in the array using the index of the item. you have set the item number 10 in the array to 500. you group the items in the table and access them the number of the row. Arrays: In our life we usually group similar objects into units. To declare an array you use a code like that: int my_array[50]. you have declared an array of integer type.500}.66.Figure 2 double ExtMapBuffer1[].15. Rows in the Arrays called Indexes. Here. which can hold up to 50 items. We use Arrays to do this task. Custom indicator functions: I can’t give you a description for all of the indicators functions in this lesson. you have to put here you initialization values of you variables.DRAW_LINE). We will use array to calculate our values which we will draw them on the chart. SetIndexBuffer(0. int init() { } Special functions: Functions are blocks of code which like a machine takes inputs and returns outputs (Please review lesson 7 – Functions). every time a new quotation have received your program will call this function.ExtMapBuffer1). start(): Here’s the most of the work. SetIndexStyle(0. SetIndexStyle: . deinit(): This is the last function the program will call before it shutdown. In MQL4 there are three special functions init(): Every program will run this function before any of the other functions. we will study here the functions used in our program. But we will use them all in our next lessons with more details. So. you can put here any removals you want. IndicatorShortName(short_name).Here we have declared and array of double type. string short_name = "Your first indicator is running!". DRAW_LINE).void SetIndexStyle( int index. It can be any valid color type variable. int width=EMPTY. The clr parameter is the color of the line. In our line of code: SetIndexStyle(0. The index parameter of this function ranges from 1 to 7 (that’s because the array indexing start with 0 and we have limited 8 line). And it indicte which line we want to set its style. color clr=CLR_NONE) This function will set the style of the drawn line. The width parameter is the width of line and ranges from 1 to 5. The type parameter is the shape type of the line and can be one of the following shape type’s constants: DRAW_LINE (draw a line) DRAW_SECTION (draw section) DRAW_HISTOGRAM (draw histogram) DRAW_ARROW (draw arrow) DRAW_NONE (no draw) The style parameter is the pen style of drawing the line and can be one of the following styles’ constants: STYLE_SOLID (use solid pen) STYLE_DASH (use dash pen) STYLE_DOT (use dot pen) STYLE_DASHDOT (use dash and dot pen) STYLE_DASHDOTDOT (use dash and double dots) Or it can be EMPTY (default) which means it will be no changes in the line style. int type. Or it can be EMPTY (default) which means the width will not change. The default value is CLR_NONE which means empty state of colors. We have set the index to 0 which means we will work with the first (and the only) line. . int style=EMPTY. And we have only one indicator buffer (#property indicator_buffers 1). etc. And we have left the other parameters to their default values. Then it takes the name of the array. . double array[]) This function will set the array which we will assign to it our indicator value to the indicator buffer which will be drawn. IndicatorShortName(short_name). In our program we declared a string variable and assigned the value “You first indicator is running” to it. string short_name = "Your first indicator is running!". In our program the array which will hold our calculated values is ExtMapBuffer1. It returns true if the function succeeds and false otherwise. then we passed it to the IndicatorShortName function. So it will be the buffer assigned.And we have set the shape type of our line to DRAW_LINE because we want to draw a line in the chart. The function takes the index of the buffer where’s 0 is the first buffer and 2 is the second. SetIndexBuffer: bool SetIndexBuffer( int index. IndicatorShortName: void IndicatorShortName( string name) This function will set the text which will be showed on the upper left corner of the chart window (Figure 3) to the text we have inputted. See you Coders’ Guru 06-11-2005 . We will continue with remaining of the code in the next lesson. int deinit() { //---//---return(0). This is the return value of the init() function which terminate the function and pass the program to the execution of the next function start(). I hope you enjoyed the lesson and I welcome your questions. } Nothing new to say about deinit() function.The short name Figure 3 return(0). buffers double ExtMapBuffer1[]. IndicatorShortName(short_name).indicators SetIndexStyle(0. And –finally.com" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Red //---. I hope you’ve came from the previous lessons with a clear idea about what we have done.mq4 | //| Codersguru | //| http://www. SetIndexBuffer(0. Are you ready? Let’s hack the code line by line: Our Code: //+------------------------------------------------------------------+ //| My_First_Indicator.DRAW_LINE).MQL4 COURSE By Coders’ guru www.com -12- Your First Indicator Part 3 ------------------------------- Welcome to the third part of “Your First Indicator” lesson.forex-tsd. Today we are going to study start() function and its content. string short_name = "Your first indicator is running!".forex-tsd. //---- .forex-tsd. In the previous lesson we studied the code of our first indicator line by line and we reached the function dinit(). //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---.we will compile and run our first Indicator.ExtMapBuffer1).com | //+------------------------------------------------------------------+ #property copyright "Codersguru" #property link "http://www. dResult.check for possible errors if (counted_bars<0) return(-1). ExtMapBuffer1[pos]= dResult . Comment("Hi! I'm here on the main chart windows!"). pos--.last counted bar will be recounted if (counted_bars>0) counted_bars--. int pos=Bars-counted_bars.. } As I told you before. . } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { int counted_bars=IndicatorCounted(). That’s because it’s the most important MQL4 Special functions. double dHigh . dResult = dHigh . //---. //---. But every time a new quotation arrives to MetaTrader terminal client. start() will not be called (by the terminal client) only one time. return(0). dLow .main calculation loop while(pos>=0) { dHigh = High[pos]. //---. we will spend 90% of programming life inside the braces of start() function. } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0).. every time the start() function has been called.dLow.return(1). dLow = Low[pos]. } //+------------------------------------------------------------------+ int start() {. } //---return(0). On the contrary of the init() and deinit function. If it’s less than 0 that’s means we have an error and we have to terminate the start() function using the return statement. we have defined the variable counted_bars as an integer type. If that’s true we decrease this number by subtracting 1 from it. (Please see the function Bars below). In the first launch of your indicator this count will be 0 because the indicator didn’t calculate any bars yet. Here. int pos=Bars-counted_bars. we are declaring the variable pos to hold the number of times our calculation loop . int IndicatorCounted() This function will return an integer type value holds the count of the bars which our indicator has been calculated them. Note: We can write the expression counted_bars-. if (counted_bars>0) counted_bars--. This number must be 0 or greater if there’s no errors have been occurred.start() function returns an integer value like all of the MQL4 special function. That’s because we want to recount the last bar again. int counted_bars=IndicatorCounted(). We have got the number of counted_bars in the previous line of code by using IndicatorCounted() function.like this: c o u n te d _ b a rs = c o u n t e d _ b a r s -1 . And after that it will be the count of total bars on the chart -1.Operations & Expressions) for decreasing the value of counted_bars by 1. where 0 means no error and any number else means an error has been occurred. We use the decrement operator (please review Lesson 4 . and we have assigned to it the returned value of the function IndicatorCounted(). We are checking here if the counted_bars are greater than 0. if (counted_bars<0) return(-1). Here. unexpected token That’s because they are not variables hence you can’t assign a value to them. You will get this error: 'Bars' . Pre-defined MQL4 variables: Ask. That’s by subtracting the counted_bars from the count of total bars on the chart. It’s a good time to discuss Bars() function and its brother. is it a variable? Another example will proof for you that they are not variables: If you type and compile this line of code: Bars=1. Low. Bars. . double Bid This function (used in your Expert Advisor) returns a double type value holds the seller’s price of the currency pair.will work (see while loop later in this lesson). High. And I’ll proof to you why they are functions. Function means do something and return some value. we get the total bars count using Bars() function. You can’t pass parameter to a variable. int Bars This function returns an integer type value holds count of the total bars on the current chart. Close. double Ask This function (used in your Expert Advisors) returns a double type value holds the buyer’s price of the currency pair. let’s discuss every function. Another proof. the next line of code is a valid line and will not generate and error in compiling: Alert(Bars(1)). So. Bid. For example Bars collects and returns the number of the bars in chart. I’m so sorry for the lengthiness. Time and Volume are functions although MQL4 called them Pre-defined variables. Open. parameters passed only to the functions. Variable means a space in memory and data type you specify. For example: Low [0] will return the lowest price of the current bar. Where it’s the highest price from prices observed during a trade period. Where opening price is the price at the beginning of a trade period (year. Where closing price is the price at the end of a trade period For example: Close[0] will return the closing price of the current bar. week.32 the left part is called the bid price (that is a price at which the trader sells). double Close[] This function returns a double type value holds the closing price of the referenced bar. Where it’s the lowest price from prices observed during a trade period. For example: Volume [0] will return this average for the current bar. day. double Open[] This function returns a double type value holds the opening price of the referenced bar. double Low[] This function returns a double type value holds the lowest price of the referenced bar. the second (the right part) is called the ask price (the price at which the trader buys the currency).Note: For example. hour etc) For example: Open[0] will return the opening price of the current bar.0001. double Volume[] This function returns a double type value holds the average of the total amount of currency traded within a period of time. usually one day. double Point This function returns a double value holds point value of the current bar (usually 0. int Digits This function returns an integer value holds number of digits after the decimal point (usually 4).27/133. . USD/JPY = 133. double High[] This function returns a double type value holds the highest price of the referenced bar. For example: High [0] will return the highest price of the current bar. month. Notice the way we used to declare the three of them at the same line by separating them by coma. double dHigh .. For example: Time [0] will return the open time of the current bar. dResult. Comment("Hi! I'm here on the main chart windows!"). void Alert( .. void Print ( . ) This function takes the values passed to it (they can be any type) and display them in a dialog box (figure 3) Figure 1 – Comment .. ) This function takes the values passed to it (they can be any type) and print them to the expert log (figure 2). ) This function takes the values passed to it (they can be any type) and print them on the left top corner of the chart (figure 1). There are two similar functions: void Comment( . This line of code uses the Comment function to print the text “Hi! I'm here on the main chart windows!” on the left top corner of the main chart (figure1).. dLow . We declared three double type variables which we will use them later..datetime Time[] This function returns a datetime type value holds the open time of the referenced bar.. Expert log Figure 3 .dLow. Any value we assign to the array ExtMapBuffer1[] will be drawn on the chart (because we have assign this array to the drawn buffer using SetIndexBuffer function). dResult = dHigh . } Now. ExtMapBuffer1[pos]= dResult . In the loop body we assign to the variable dHigh the value of the highest price of the current loop variable. We use the loop variable as a current bar of the calculation for example High[pos] will return the highest price of the pos bar.Figure 2. dLow = Low[pos]. The number of times the loop will work called Loop variable which it’s pos variable in our example. pos--. . Before we enter the loop we have got the number of times the loop will work by subtracting the counted_bars from the total count of the bars on chart. it’s the time to enter the loop for calculating our indicator points to draw them.Alerts while(pos>=0) { dHigh = High[pos]. Figure 4 – My_First_Indicator I hope you enjoyed your first indicator. we can compile our indicator. but it believed that the subtraction of the highest and lowest of the price gives us the market's volatility. The last line of the loop is a decrement expression which will decrease the loop variable pos by 1 every time the loop runs. The result of subtracting dLow from dHigh will be assigned to the variable dResult. Coders’ Guru 13-11-2005 . Finally. To load your indicator click F4 to bring the terminal client. Then we using the dResult to draw or indicator line. I welcome very much your questions and suggestions. Note: The indicator will not do much. And when this variable reaches -1 the loop will be terminated. Then From the Navigator window find the My_First_indicator and attach it to the chart (figure4). That will generate the executable file “My_First_indicator. And be prepared to your first Expert Advisor in the next lesson(s). by assigning it to the drawn buffer array ExtMapBuffer1[].ex4” which you can load in your terminal client.And assign to the variable dLow the value of the lowest price of the current loop variable. Press F5 or choose Compile from file menu. The second solution is using a program to automate your trades.com -13Your First Expert Advisor Part 1 -------------------- In the previous lesson we created our first indicator. and keep your eyes widely open. . If you get tired. If this employee is an expert. First two steps: Step1: If you didn’t open your MetaEditor yet. buy and modify our orders manually. The Expert advisor is a program wrote in MQL4 (we are studying MQL4 huh?) uses your favorite indicators and trade methods to automate your orders.MQL4 COURSE By Coders’ guru www.forex-tsd. The indicators –in general. but it was very useful for us as programmers. want to drink a cup of tea or even take a short vacation. You have to set in front of your terminal.are very important for the technical analysis of the market in trying to predict the future prices. Today we are going to create our first expert advisor so let’s go. Although this indicator wasn’t useful for us as trader. he will cost you the pips you earn. It can buy. he will cost you your capital. But with the indicators we observe the chart then use our hands to sell. It enables you to drink a cup of tea and save the salary you gave out to your employee or the bunch of flowers you bring to your assistant wife. And if he is novice one. sell and modify the orders for you. That’s what the Expert Advisor is for. You have to consider one of these solutions: You may rent someone to observe the terminal for you and calling your mobile phone every five minutes to tell you what’s going on. I think it’s the time to run it. In this step you can set these properties: 1234Name of your expert advisor. This wizard enables you to set the properties of your expert advisor and to set the external variables you will use in your expert advisor. That will pop up the new program wizard which you have seen when you created your first indicator (Figure 1). you have got the general properties wizard (Figure 2). This time we will choose the first option “Expert Advisor program” then click Next button.From the MetaEditor File menu click New (you can use CTRL+N hotkey or click the New icon in the standard toolbar). in our sample we will use My_First_EA. type your name (I typed mine in the sample). Link to your web site. External variables list: This is the list of the external variables you allow the user of your expert advisor to change them from the Expert properties window. Figure 1 – the first step wizard Step2: When you clicked Next. . Author name of the program. Initial value: double click this field to give your variable initialization value. . Note: you have to put the expert advisors in MetaTrader 4\experts path and the indicators in MetaTrader 4\experts\indicators path. clicking it will add a new record to the external variables list. and MetaEditor will bring to you the code created by the wizard and saves the file My_First_EA. This field is optional which means you can leave it without setting In our sample we have added three variables: Varaible Type initial value --------------------------------------TakeProfit double 350 Lots double 0. otherwise they will not work. Every record has three fields: Name: double click this field to set the name (identifier) of the variable.mq4 in the MetaTrader 4 \experts path.1 TrailingStop double 35 Figure 2 – the second step wizard Now click the Finish button to close the wizard. Type: double click this field to set the data type of the variable.To add a new variable you click the Add button. 1.input parameters extern double TakeProfit=250. } //+------------------------------------------------------------------+ As you see above.com" //---. } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0). //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---//---return(0). } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---//---return(0).This is the code we have got from the wizard: //+------------------------------------------------------------------+ //| My_First_EA.mq4 | .0. the code generated by the wizard is a template for you to add your code without bothering you by typing the main functions from scratch. extern double TrailingStop=35.0.mq4 | //| Coders Guru | //| http://www. extern double Lots=0.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.forex-tsd. Now let’s add our own code: //+------------------------------------------------------------------+ //| My_First_EA.forex-tsd. com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www. extern double TrailingStop=35.1.//| Coders Guru | //| http://www.0.0. double line2) { static int last_direction = 0.forex-tsd. static int current_dirction = 0. if(line1>line2)current_dirction = 1. } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0). } } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---- .input parameters extern double TakeProfit=250. } else { return (0). } int Crossed (double line1 .forex-tsd. //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---//---return(0). extern double Lots=0. //up if(line1<line2)current_dirction = 2. return (last_direction). //down if(current_dirction != last_direction) //changed { last_direction = current_dirction.com" //---. GetLastError()). total = OrdersTotal().12345.OrderOpenPrice()).int cnt.0.cnt<total. } if(isCrossed == 2) { ticket=OrderSend(Symbol(). if(Bars<100) { Print("bars less than 100").cnt++) { OrderSelect(cnt.PRICE_CLOSE. total. MODE_TRADES).0.SELECT_BY_TICKET. "My EA".MODE_EMA.Red).0. double shortEma.Lots. return(0). int isCrossed = Crossed (shortEma. return(0).Green).Lots.0. longEma. } else Print("Error opening BUY order : ".Bid. if(ticket>0) { if(OrderSelect(ticket. if(total < 1) { if(isCrossed == 1) { ticket=OrderSend(Symbol(). } for(cnt=0.13.MODE_TRADES)) Print("BUY order opened : ".0.longEma).PRICE_CLOSE. longEma = iMA(NULL. } return(0).Ask.OP_SELL. SELECT_BY_POS.3. ticket. } if(TakeProfit<10) { Print("TakeProfit less than 10").3.GetLastError()).MODE_TRADES)) Print("SELL order opened : ". return(0). Bid-TakeProfit*Point. if(ticket>0) { if(OrderSelect(ticket."My EA".OrderOpenPrice()).0.8.MODE_EMA. } else Print("Error opening SELL order : ". // check TakeProfit } shortEma = iMA(NULL.0.Ask+TakeProfit*Point. return(0).0).0). .OP_BUY.0.12345.SELECT_BY_TICKET. Ask. // close position return(0).Bid. } //+------------------------------------------------------------------+ .Violet).OrderOpenPrice().0. return(0). } } } } else // go to short position { // should it be closed? if(isCrossed == 1) { OrderClose(OrderTicket().Red).Ask+Point*TrailingStop.Green). // close position return(0).3.if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(isCrossed == 2) { OrderClose(OrderTicket(). // exit } // check for trailing stop if(TrailingStop>0) { if((OrderOpenPrice()-Ask)>(Point*TrailingStop)) { if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) { OrderModify(OrderTicket(). } } } } } } return(0).0.OrderOpenPrice(). // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket().OrderLots(). return(0). OrderTakeProfit().BidPoint*TrailingStop.OrderLots().3.OrderTakeProfit().Violet). Live trading In live trading testing the results are more accurate but you have to spend days (and maybe months) to know is the expert advisor profitable or not. Test the Expert Advisor: Before studying our expert advisor code we have to be check is it profitable one or not. To enable it click Tools Option menu (or use CTRL+O hotkey). Note: Our expert advisor will work with EURUSD pairs in 4 Hours timeframe. we will know everything about this code line by line. that’s will bring the Options windows (figure 3). You have to enable the expert advisor to automate your trades. So compile the expert advisor by pressing F5 and load it in MetaTrader. click Expert Advisors tab and enable these options: Enable Expert Advisors Allow live trading And click Ok button . use the code provided with lesson in www.com .forex-tsd. Scared? Don’t be scared of the 160 lines you have seen above. I promise it’s an easy task.Note: don’t copy and paste the code above because it warped and will not work for you. You can test your expert advisor using two methods: 1. let’s now bring its window by pressing F6 (Figure 5).Figure 3 – Enabling expert advisor auto trade You will see the Smile symbol beside the expert advisor name which means your expert advisor is working and ready to trade for you (Figure 4). Period: H4 (4 Hours). .Strategy Tester: The second method of testing your expert advisor which is less accurate but will not take time is the Strategy tester. We will know everything about Strategy tester later. When you get the window enter these options: Symbol: EURUSD. Figure 4 – Expert advisor is enabled 2. Model: Open price only. I hope you are ready for the challenge. We interested in Report tab (Figure 6). See you Coders’ Guru 24-11-2005 . I welcome very much the questions and the suggestions.Figure 5 – Strategy tester window Now click Start button to start testing the expert advisor. click it to see your profit. We have a lot to say and to do in the next lesson. You will see a progress bar and the two tabs (Settings and Journal) became five tabs. 1. Did you wear your coding gloves? Let’s crack. The code we have: //+------------------------------------------------------------------+ //| My_First_EA. In the previous part we have taken the code generated by the new program wizard and added our own code which we are going to crack it today line by line. //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---//---return(0).input parameters extern double TakeProfit=250.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.0.com" //---.forex-tsd.forex-tsd.com -14Your First Expert Advisor Part 2 -------------------- Welcome to the second part of creating Your First Expert Advisor lesson. extern double TrailingStop=35. Note: I have to repeat that our expert advisor is for educational purpose only and will not (or aimed to) make profits.mq4 | //| Coders Guru | //| http://www.0. extern double Lots=0.MQL4 COURSE By Coders’ guru www. } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- . // check TakeProfit } shortEma = iMA(NULL. //down if(current_direction != last_direction) //changed { last_direction = current_direction. if(Bars<100) { Print("bars less than 100"). static int current_direction = 0.13. if(total < 1) { if(isCrossed == 1) . total. return(0).MODE_EMA.0. return(0).longEma). } else { return (0).0). double line2) { static int last_direction = 0.PRICE_CLOSE.0.0. ticket. return (last_direction).0.PRICE_CLOSE. //up if(line1<line2)current_direction = 2. double shortEma. total = OrdersTotal(). if(line1>line2)current_direction = 1. } } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---- int cnt. } int Crossed (double line1 . } if(TakeProfit<10) { Print("TakeProfit less than 10").//---return(0).8. longEma. longEma = iMA(NULL.MODE_EMA. int isCrossed = Crossed (shortEma.0). OrderOpenPrice()).cnt++) { OrderSelect(cnt.OP_SELL.GetLastError()).Green).12345.12345.OrderLots().OrderOpenPrice(). } for(cnt=0.0.BidPoint*TrailingStop.Bid. if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(isCrossed == 2) { OrderClose(OrderTicket().Green).3.MODE_TRADES)) Print("BUY order opened : ". if(ticket>0) { if(OrderSelect(ticket.Lots. "My EA".SELECT_BY_TICKET.0.SELECT_BY_TICKET. } return(0).cnt<total. if(ticket>0) { if(OrderSelect(ticket. } } } } else // go to short position { .{ ticket=OrderSend(Symbol().0. // close position return(0).GetLastError()). return(0). Bid-TakeProfit*Point.OrderOpenPrice()).MODE_TRADES)) Print("SELL order opened : ". return(0).3.Ask+TakeProfit*Point. } else Print("Error opening BUY order : ". } else Print("Error opening SELL order : ". } if(isCrossed == 2) { ticket=OrderSend(Symbol().0.Lots.OrderTakeProfit().Bid. return(0).Ask. // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket().Red).Violet).OP_BUY.0.3."My EA". MODE_TRADES). SELECT_BY_POS. Red). Before digging into cracking our code we have to explain the idea behind our expert advisor. they are for educational purpose only. the direction of each lines will determine the order type: If the short EMA is above the long EMA will buy (long). Any expert advisor has to decide when to enter the market and when to exit.Ask+Point*TrailingStop. let’s see it. Entering (Open): Our expert advisor will enter the market when the short EMA line crosses the long EMA line.0. the first one is the EMA of 8 days (sort EMA) and the second one is the EMA of 13 days (long EMA). return(0).// should it be closed? if(isCrossed == 1) { OrderClose(OrderTicket(). // close position return(0). // exit } // check for trailing stop if(TrailingStop>0) { if((OrderOpenPrice()-Ask)>(Point*TrailingStop)) { if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) { OrderModify(OrderTicket(). Note: using those EMAs or any thought in this lesson is not a recommendation of mine. . We use two EMA indicators. OrderTakeProfit(). If the short EMA is below the long EMA we will sell (short).Violet). And the idea behind any expert advisor is what the entering and exiting conditions are? Our expert advisor is a simple one and the idea behind it is a simple too. } } } } } } return(0).Ask. } //+------------------------------------------------------------------+ The idea behind our expert advisor.OrderOpenPrice().3.OrderLots(). Stop loss: It’s a limit point you set to your order when reached the order will be closed. . but it recommended to leave the defaults). this is useful to minimize your lose when the market going against you. Now let’s resume our code cracking. I have to pause again to tell you a little story about those variables. Our order (buy or sell) will automatically be closed too when the Take profit or the Stop loss points are reached. Stop losses points are always set below the current asking price on a buy or above the current bid price on a sell.1. And will close the sell order when the short EMA crosses the long EMA and the short EMA is above the long EMA. Modifying: Beside entering (opening) and exiting (closing) the market (positions) our expert advisor has the ability to modify existing positions based on the idea of Trailing stop point. double Lots=0.We will open only one order at the same time. We will talk about this very important concept later in this lesson.0. Trailing Stop It’s a kind of stop loss order that is set at a percentage level below (for a long position) or above (for a short position) the market price.0. double TrailingStop=35. We will know how we implemented the idea of Trialing stop later in this lesson. //---extern extern extern input parameters double TakeProfit=250. Exiting (Close): Our expert advisor will close the buy order when the short EMA crosses the long EMA and the short EMA is below the long EMA. The three variables are double data type. In the above lines we have asked the wizard to declare three external variables (which the user can set them from the properties window of our expert advisor). We have initialized them to default values (the user can change these values from the properties window. The price is adjusted as the price fluctuates. instead of below. return (last_direction). if(line1>line2)current_direction = 1. static int current_direction = 0. The exit point must be set above the current market price. } } . Figure 1 – Setting Stop loss and Take profit points int Crossed (double line1 . double line2) { static int last_direction = 0. //up if(line1<line2)current_direction = 2.Take profit: It’s similar to stop lose in that it’s a limit point you set to your order when reached the order will be closed There are. //down if(current_direction != last_direction) //changed { last_direction = current_direction. however. two differences: • • There is no “trailing” point. } else { return (0). The place of the function doesn't matter. For this goal we have created the Crossed function. double line2) The above line is the function declaration. We are going to use these variables (they are static variables which means they save their value between the repeated calls) to check if there’s a change in the direction of the lines or not. The first parameter is the value of the first line we want to monitor (the short EMA in our case) and the second parameter is the value of the second we want to (the long EMA). • • • It will return 0 if there’s no change happened in the last directions saved. Note: You can use this function in your coming expert advisor to monitor any two lines and get the crossing direction. I placed it above start() function. but you can place it anywhere else. it means we want to create Crossed function which takes two double data type parameters and returns an integer. The Crossed function takes two double values as parameters and returns an integer. And getting the direction of the crossing (which line is above and which line is below) which will determine the type of the order (buy. .As I told you before. Let’s see how did we write it? int Crossed (double line1 . the idea behind our expert advisor is monitor the crossing of the short EMA and the long EMA lines. It will return 2 if the direction has changed (the lines crossed each others) and the first line is below the second line. static int last_direction = 0. The function will monitor the two lines every time we call it by saving the direction of the two lines in static variables to remember their state between the repeated calls. You have to declare the function before using (calling) it. Here we declared two static integers to hold the current and the last direction of the two lines. sell. static int current_direction = 0. It will return 1 if the direction has changed (the lines crossed each others) and the first line is above the second line. When you call this function you have to pass to it two double parameters and it will return an integer to you. buy-close and sell-close). To that day I hope you the best luck. Our program will call this function in its start() function body and use the returned value to determine the appropriate action. This value will be 1 if the first line is above the second line and 2 if the first line is below the second line. return (last_direction). In the coming part of this lesson we will know how did we call the function. I welcome very much the questions and the suggestions. and we will know a lot about the very important trading functions. In this case (last_direction not equal current_direction) we have to reset our last_direction by assigning to it the value of the current_direction.we have initialized them to 0 because we don’t want them to work in the first call to the function (if they worked in the first call the expert advisor will open an order as soon as we load it in the terminal). And we will return the value of the last_direction. If last_direction not equal current_direction that’s mean there’s a change happened in the direction. else { return (0). last_direction = current_direction. } Else (last_direction is equal current_direction) there’s no change in the lines direction and we have to return 0. if(current_direction != last_direction) //changed In this line we compare the two static variables to check for changes between the last call of our function and the current call. See you Coders’ Guru 01-12-2005 . MetaQuotes Language 4 MQL4 quick reference Account Information Array Functions Common functions Conversion functions Custom Indicator functions Date & Time functions File functions Global Variables functions Math & Trig Object functions Pre-defined Variables Standard Constants String functions Technical Indicator calls Trading functions Window functions MQL4 quick reference About MetaQuotes Language 4 Syntax Data types Operations & Expressions Operators Functions Variables Preprocessor About MetaQuotes Language 4 MetaQuotes Language 4 (MQL4) is a new built-in language for programming trading strategies. There are also basic indicators built in and commands of order placement and control. the terminal supports testing strategies on historical data with displaying on the chart the spots where trades come in and out. they cannot make deals automatically and are aimed only at implementing analytical functions. The Advisor can not only inform you about a possibility to strike bargains. Programs written in MetaQuotes Language 4 have different features and purposes: • Expert Advisors is a mechanical trade system (MTS) linked up to a certain plot. A large number of functions necessary for the analysis of the current and past quotations. • Custom Indicators are an analogue of a technical indicator. but also can make deals on the trade account automatically and direct them right to the trade server. Also. operations. A brief guide contains functions divided into categories. The MetaEditor 4 text editor that highlights different constructions of MQL4 language is used for writing the program code. • Scripts are programs intended for single execution of some actions. Like most trade systems. the basic arithmetic and logic operations are included in MQL4 structure. • Libraries are user functions libraries where frequently used blocks of user programs are stored. As an information book for MQL4 language we use MetaQuotes Language Dictionary. Like built-in indicators. This language allows to create your own Expert Advisors that render the trade process management automatic and are perfectly suitable for implementing your own trade strategies. Scripts are not run tick wise and have no access to indicator functions. Unlike Expert Advisors. Syntax Format . and other language constructions and allows finding the description of every element we use. reserved words. with the help of MQL4 you can create your own Custom Indicators. It helps users to orient in the expert system text quite easily. Custom Indicators allow to create technical indicators in addition to those already integrated into client terminal. Scripts and Libraries of functions. In other words. A-Z (recognized as different symbols). Comments are allowed where blank spaces are possible and tolerate any number of spaces. Examples: NAME1 namel Total_5 Paper Reserved words The identifiers listed below are fixed reserved words.Comments Identifiers Reserved words Format Spaces. Symbols you can use: the numbers 0-9. The identifier must not coincide with any reserved word. Latin capital and small letters a-z. You should use tab symbols to enhance the readability of the text . and they cannot be used for other purposes: Data types bool color datetime double int string void Memory classes Operators extern static break case continue default else for if return switch while Other false true Data types Data types overview Integer constants . A certain action is assigned to each of them. Single comments start with // symbols. Examples: // single comment /* multiline // nested single comment comment */ Identifiers Identifiers are used as names of variables. The first symbol cannot be a number. You can use any amount of such symbols instead of one. functions. line feed/form feed symbols are used as separators. tabs. The length of an identifier cannot exceed 31 characters. the symbol of underlining (_). Such comments cannot be nested. and data types. Comments Multi line comments start with /* symbols and end with */ symbols. end with the symbol of a new line and can be nested into multi line comments. they start with 0x or 0X. the result will not be defined. The data of Color and Datetime types are represented as integer values. 0x12. a reverse slash (\) and control characters can be represented as a combination of characters starting with a reverse slash (\) according to the table below: line feed NL (LF) \n horizontal tab HT \t carriage return CR \r reverse slash \ \\ single quote ' \' double quote " \" hexadecimal ASCII-code hh \xhh If a character different from those listed above follows the reverse slash. We use implicit type transformation.color. the result will not be defined. letters a-f or A-F to represent the values 10-15. 0X7C7 Integer constants can assume values from -2147483648 to 2147483647. Before assignment operations are performed. Zero should not be the first number. If a constant exceeds this range. 0Xa3. Examples: 0x0A. double quote (") a question mark (?). double.Literal constants Boolean constants Floating-point number constants String constants Color constants Datetime constants Data types overview The main data types are: • • • • • • • Integer (int) Boolean (bool) Literals (char) String (string) Floating-point number (double) Color (color) Datetime (datetime) We need the Color and Datetime types only to facilitate visualization and entering those parameters that we set from expert advisor property tab or custom indicator "Input parameters" tab. the data have been transferred to the integer type.datetime). 0x2f. Before operations (except for the assignment ones) are performed. 0xA3. Literal constants Any single character enclosed in single quotes or a hexadecimal ASCII-code of a character looking like '\x10' is a character constant of integer type. -956 1007 Hexadecimal: numbers from 0 to 9. string. . 0X12. Integer constants Decimal: numbers from 0 to 9. 111. Examples: 12. the data have been transferred to the maximum precision type. The priority of types at a transformation in ascending order is the following: int (bool. Some characters like a single quote ('). An unimportant fractional part with the dot can be absent. the superfluous characters on the right are rejected.128. // code 0xA9 '\xAE'.of the green one and BB . False and FALSE. Floating-point number constants Floating-point constants consist of an integer part. double c = 0.2e-308 to 1. A hexadecimal number looks like 0x00BBGGRR where RR is the rate of the red color component. Integer-valued representation is written in a form of hexadecimal or a decimal number. Decimal constants are not directly reflected in RGB.1007.111. bool c = 1. double d = 16. is saved in a separate memory space. You can insert any special character constants into the line if they have a reverse slash (\) before them. The constant starts with the symbol C and is enclosed in single quotes. numeric representation of them is 1 or 0 respectively. the result will not be defined. It is of the string type. Each string constant. bool b = false. Examples: bool a = true. They represent the decimal value of the hexadecimal integer representation.8e308. Numerical rate values of a color component lie in the range from 0 to 255. We can also use synonyms True and TRUE.128' // gray .Examples: int a = int b = int c = int d = 'A'. Floating-point constants can assume values from 2. Examples: "This is a character string" "Copyright symbol \t\xA9" "this line with LF symbol \n" "A" "1234567890" "0" "$" Color constants Color constants can be represented in three ways: by character representation.0001. even if it is identical to another string constant. blue. you must place a reverse slash (\) before it. Specific colors reflect the so-called Web colors set. If a constant exceeds this range. double b = -956. by name (for concrete Web colors only).of the blue one. by integer representation. A string constant is an array of characters enclosed in quotes. The length of a string constant lies between 0 and 255 characters. green.) and a fractional part. a dot (. Character representation consists of four parts representing numerical rate values of three main color components red. '©'. Examples: double a = 12. String constants String constant is a succession of ASCII-code characters enclosed in double quotes: "Character constant". Examples: // symbol constants C'128. The integer and the fractional parts are a succession of decimal numbers. GG . If the string constant is longer. If you need to insert a double quote (") into the line. '$'. // symbol code ® Boolean constants Boolean constants may have the value of true or false. i = j . z = 3 * x.01 00:00' // New Year D'1980.19 12:00:00' D'01.07.3. .C'0x00. and seconds.2004 00:00:00' D'12:30:27' //equal to D'[compilation date] 12:30:27' D'' //equal to D'[compilation date] 00:00:00' Operations & Expressions Expressions Arithmetical operations The operation of assignment Operations of relation Boolean operations Bitwise operations Other operations Precedence rules Expressions An expression consists of one or more operands and operation characters. x = .19 12:30:27' D'19. Example: a++.01. b = 10. 1970 to Dec 31. The constant is enclosed in simple quotes and starts with a D character.x. k--. Examples: D'2004.0xFF' // named color Red Yellow Black // integer-valued 0xFFFFFF 16777215 0x008000 32768 // blue representation // white // white // green // green Datetime constants Datetime constants can be represented as a character line consisting of 6 parts for value of year. date. i++. x = (y*z)/w. hour. 2037.2004' //equal to D'01.1980 12:30:27' D'19. i = j / 5.07.07.07. Note: An expression that ends with a semicolon is an operator. minutes. month.0x00. Arithmetical operations Sum of values Difference of values Changing the operation sign Product of values Division quotient Division remainder Adding 1 to the variable value Subtracting 1 from the variable value i = j + 2.1980 12' //equal to D'1980.01. An expression can be written in several lines. minutes = time % 60.01. Datetime constant can vary from Jan 1. /= x. the value 1 is checked only if k value is false. True if a equals b a == b. True if a is less than or equals b a <= b. True if a is greater than or equals b a >= b. if(!a) Print("not 'a'"). and the normalized outcome needs to be compared to null. The logical shift operation uses values of x less than 5 binary digits. ^= x. *= x. The value of this expression is true if the value of k or 1 is true. By %= operation a result sign is equal to the sign of divided number. &= x. The greater digits are rejected. True if a is greater than b a > b. while the logical value true is represented with any value differing from zero. True if a is less than b a < b. so the shift is for the range of 0-31 bit. Example: int a=3. // invalid expression The operation of assignment Note: The value of the expression that includes this operation is the value of the left operand following the bind character. the result equals 0 if the operand differs from 0. += x. The logical operation OR (||) of values k and 1. You can implement bitwise operations with integer numbers only. Operations of relation The logical value false is represented with an integer zero value. The value of expressions containing operations of relation or logical operations is 0 (false) or 1 (true). Example: if(x<k || x>l) Print("out of range"). <<= x. Note: There can be only one operation of assignment in the expression. That is why it is necessary to subtract one from another. >>= x.The operations of adding/subtracting 1 cannot be implemented in expressions. The value x is checked first. Assigning the y value to the x variable Adding x to the y variable Subtracting x from the y variable Multiplying the y variable by x Dividing the y variable by x Module x value of y Logical shift of y representation to the right by x bit Logical shift of y representation to the left by x bit Bitwise operation AND Bitwise operation OR Bitwise operation exclusive OR y y y y y y y y y y y = x. The value k is checked first. -= x. the result equals 1 if the operand value is 0. the value y is checked only if k value . a++. Boolean operations The operand of negation NOT (!) must be of arithmetic type. // valid expression int b=(a++)*3. |= x. The logical operation AND (&&) of values x and y. True if a does not equal b a != b. Two unnormalized floating-point numbers cannot be linked by == or != operations. // True if a is false. %= x. SL. Example: x = x >> y..OP_BUY. The value of this expression is true if the values of both x and y are true. the value of the expression contains 0 in all other digits. If the returned value is of the void type. the free digits on the right will be filled with zeroes. Example: x = x << y. The "comma" operation is executed from left to right.x2. Example: b = x ^ y. int ticket=OrderSend(Symbol(). Example: b = x | y.. the value of the expression contains 0 (false) in all other digits. the value of the expression equals the value of the variable numbered as i. The call of function with x1. All side effects of left expression calculation can appear before we calculate the right expression. b = ~n. Bitwise operation OR of binary-coded x and y representations. the value of the expression contains 0 in all digits where n contains 1. //Assign the value of 3 to array element with index i.. Mind that the expressions x1. you cannot place such function call on the right in the assignment operation. At addressing to i element of array. double TP=Ask+25*Point. A pair of expressions separated by a comma is calculated from left to right with a subsequent deletion of the left expression value.3. .x2.123.xn arguments. Bitwise operation EXCLUSIVE OR of binary-coded x and y representations.Red).Ask.xn are surely executed in this order.1. The right shift is logical shift.is true. Example: if(p!=x && p>y) Print("true")... Note: Bitwise operations are executed with integers only. Binary-coded representation of x is shifted to the right by y digits. The value of the expression contains 1 (true) in all digits where both x and y are not equal to zero. The value of the expression contains 1 in all digits where n contains 0. Example: b = ((x & y) != 0).. //Mind that the first array element //is described with the expression array [0]. The expression contains 1 in all digits where x and y not equals 0. The result type and value coincide with the type and value of the right expression...0. Bitwise operations One's complement of values of variables.TP. The expression accepts the value returned by the function. n++. Bitwise operation AND of binary-coded x and y representations. that is the freed leftside bits will be filled with zeros. The binary-coded representation of x is shifted to the right by y digits. the value of the expression contains 0 in all other digits. Example: double SL=Ask-25*Point. The expression contains 1 in all digits where x and y have different binary values. "My comment". Other operations Indexing. Example: array[i] = 3. Comma From left to right Use parentheses to change the execution order of the operations. () Function call From left to right [] Array element selection ! Negation From left to right ~ Bitwise negation Sign changing operation * Multiplication From left to right / Division % Module division + Addition From left to right Subtraction << Left shift From left to right >> Right shift < Less than From left to right <= Less than or equals > Greater than >= Greater than or equals == Equals From left to right != Not equal & Bitwise AND operation From left to right ^ Bitwise exclusive OR From left to right | Bitwise OR operation From left to right && Logical AND From left to right || Logical OR From left to right = Assignment From right to left += Assignment addition -= Assignment subtraction *= Assignment multiplication /= Assignment division %= Assignment module >>= Assignment right shift <<= Assignment left shift &= Assignment bitwise AND |= Assignment bitwise OR ^= Assignment exclusive OR . The higher the priority is.Precedence rules Each group of operations in the table has the same priority. Operators Format and nesting Compound operator Expression operator Break operator Continue operator Return operator Conditional operator if Conditional operator if-else Switch operator Cycle operator while Cycle operator for . the higher the position of the group in the table is. The execution order determines the grouping of operations and operands. y=x=3. Example: fclose(file). The purpose of this operator is opposite to that of break. operator terminates the execution of the nearest nested outward operator switch. Example: x=3. Null operator It consists of a semicolon (. . Example: // searching first zero element for(i=0. operator gives control to the beginning of the nearest outward cycle operator while or for.) only. Example: if(x==0) { x=1. Nesting. The control is given to the operator that follows the terminated one.i<array_size. Break operator A break. Two or more operators can be located in the same line. We use it to denote a null body of a control operator. Identifier=expression. Continue operator A continue.i++) if((array[i]==0) break.Format and nesting Format. while or for. Example: // summary of nonzero elements of array int func(int array[]) { int array_size=ArraySize(array). if-else.). One operator can occupy one or several lines.) is an operator. while and for) can be nested into each other. Compound operator A compound operator (a block) consists of one or more operators of any type enclosed in braces {}. Execution order control operators (if. // error You can use an assignment operator in an expression only once. Function call operator Function_name(argument1.. Here are some examples of expression operators: Assignment operator. switch. One of the purposes of this operator is to finish the looping execution when a certain value is assigned to a variable... calling the next iteration. } Expression operator Any expression followed by a semicolon (. The closing brace should not be followed by a semicolon (. z=3.. y=2. argumentN). If the expression is false. Example: // The "else" part refers to the second "if" operator: if(x>1) if(y==2) z=5. If the expression is false. } else . The operator expression is enclosed in parentheses. Example: if(a==x) temp*=3. Example: return(x+y). The expression should not contain an assignment operator. If the expression is true. } Return operator A return. temp=MathAbs(temp).int sum=0. Conditional operator if if (expression) operator. for(int i=0. operator terminates the current function execution and returns the control to the calling program. operator terminates the current function execution and returns the control to the calling program together with the expression value. If it happens. "else" addresses to the nearest previous operator "if" in the block that has no "else" part. } return(sum). The "else" part of the "if" operator can be omitted. operator2 is executed. Thus. sum+=a[i]. the operator will be executed. Conditional operator if-else if (expression) operator1 else operator2 If the expression is true. i++) { if(a[i]==0) continue. the control will be given to the expression following the operator.i<array_size. A return(expression). else z=6. // The "else" part refers to the first "if" operator: if(x>l) { if(y==2) z=5. a divergence may appear in nested "if" operators with an omitted "else" part. operator1 is executed and the control is given to the operator that follows operator2 (operator2 is not executed). Example: case 3+4: //valid case X+Y: //invalid Operators connected with a default label are executed if none of the constants in case operators equals the expression value. break. .{ z=6. None of two constants in one switch operator can have the same values. default: operators. } else { Print("ERROR"). } else if(x=='b') { y=2. z=3. } // Nested operators if(x=='a') { y=1. } It compares the expression value with constants in all variants of case and gives control to the operator that resembles the expression value. break.. The default variant is not obligatory final. The keyword case and the constant are just labels and if operators are executed for some variant of case the program will further execute the operators of all following variants until it hits a break operator. break. case constant2: operators.. The constant expression must not include variables and function calls. } else if(x=='c') { y = 4. break. Each variant of the case can be marked with an integer or character constant or a constant expression. It allows linking one succession of operators with several variants. } Switch operator switch (expression) { case constant1: operators. A constant expression is calculated during compilation. If none of the constants resembles the expression value and the default variant is absent. break. no actions are executed. case 'B': case 'C': Print("CASE B or C\n"). . B or C\n"). Example: switch(x) { case 'A': Print("CASE A\n"). default: Print("NOT A. expression3. the cycle is terminated. k++.j=n-l. expression2. If the expression is true.'. If the expression is false. the operator is executed till the expression becomes false.j--) a[i]=a[j]. If it is not false. Example: for(x=1. it is considered constantly true.i++. The cycle is repeated until Expression2 becomes false. } Cycle operator while while (expression) operator. The FOR (. Functions Function definition Function call Special functions init(). Example: while(k<n) { y=y*x. If Expression2 is omitted. } Cycle operator for for (expression1. Each of the expressions 1 to 3 can consist of several expressions united by a comma operator '. while (expression2) { operator.i<n.break. the operator is not executed at all. Note: An expression value has been defined before the operator is executed. Expression2 is the cycle termination check. and the control is given to the next operator.) operator is a continuous cycle equivalent to the WHILE(l) operator. If it is true. The 'for' operator is equivalent to the following succession of operators: expression1. if the expression is false from the very beginning.x<=7. Therefore. Example: // for(i=0. the loop body operator will be executed. Expression3 is calculated after each iteration.) that separate them. Any of the three or all three expressions can be absent in the FOR operator. but you should not omit the semicolons (.x++) Print(MathPower(x. }. expression3) operator. deinit() and start() Function definition . Expression3 is executed.2)).. Expression1 describes the initialization of the cycle. the control will be given to the next operator. double a. when receiving new quotations.. the system checks the number and type of arguments given to the function.. Variables Definitions Defining local variables Static variables . double b) { return (a*x + b). } Special functions init(). Example: double // type linfunc (double x. deinit() and start() Any program begins its work with the "init()" function. Execution of scripts does not depend on quotations coming. and the value is passed to the function. the next calling "start()" function is executed only after "return()" instruction. A function call is an expression that assumes the value returned by the function..x2. The order of expressions calculation and the order of values loading are guaranteed. double a. Each expression x1. During the execution. 8). changing financial symbol and/or charts periodicity. When new quotations are received. changing financial symbol and/or charts periodicity. 10. Example: void errmesg(string s) { Print("error: "+s). charts closing and also client terminal exiting interrupts execution of program. Detaching of the program from charts. the "start()" function triggered on the previous quotations was performed.. double b) // function name and // parameters list { // nested operators return (a*x + b). If. There is also another way: call by link.A function is defined by return value type declaration. the "start()" function of attached expert advisors and custom indicator programs is executed..xn) Arguments (actual parameters) are transferred according to their value. chart window closing. } double linfunc(double x. "deinit()" function is launched also by client terminal shutdown.. The function can be declared or described in any part of the program: int somefunc() { double a=linfunc(0.3. "Init()" function attached to charts is launched also after client terminal has started and in case of changing financial symbol and/or charts periodicity..xn is calculated. the expression value assumes the type of function result. In case of a necessity. This function type must correspond with the type of the returned value. Such way of addressing to the function is called a value call. // returned value } The "return" operator can return the value of the expression included into this operator. All new quotations received during the program execution are ignored by the program. by formal parameters and a compound operator (block) that describes actions the function executes. } Function call function_name (x1.5.. Every program finishes its work with the "deinit()" function. A function that does not return a value must be of "void" type. the initializing value is considered as a default value. 1970.a boolean number "true" or "false".01. In the block of the function to the formal parameters some values can be assigned. Example: extern datetime tBegin_Data = D'2004. double . The additional data types make sense only at the declaration of input data for more convenient their representation in a property sheet.01 00:00'. //each of them consisting of 50 integers. Example: int a[50]. Example: string MessageBox. Scope is the block of the function. int Orders. Defining local variables The variable declared inside any function is local. Only constants can be used to initialize variables. //Two-dimensional array of seven arrays. color . double m[7][50]. unsigned integer. } Formal parameters are local. The additional types are: • • datetime is date and time. The parameters following the initialized parameter should be . double y. Formal parameters must have names differing from those of external variables and local variables defined within one function. A definition is not an operator. Arrays Array is the indexed sequence of the identical-type data. Every call of function execute the initialization of local variables. Local variables are stored in memory area of corresponding function. The scope of a local variable is limited to limits of the function inside which it is declared. bool .an integer. Formal parameters can be initialized by constants. 1. double SymbolPrice. Variables must be declared before being used. extern color cModify_Color = C'0x44. containing seconds since 0 o'clock on January.. Formal parameters Examples: void func(int x.a string of characters. No more than four-dimensional arrays can be declared. bool z) { .a floating-point number (double precision). Only an integer can be an array index.0xE6'. The local variable can be initialized by outcome of any expression.integer reflecting a collection of three color components. The basic types are: • • • • string . //A one-dimensional array of 50 integers. bool bLog. int . In this case..Defining global variables Defining extern variables Initializing variables External function definition Definitions Definitions are used to define variables and to declare types of variables and functions defined somewhere else.0xB9. cannot be initialized by default values. Parameters are passed by value.5). int init() . i.. modification of such parameters will be reflected on corresponded variables in the called function. can be defined as static. If there is no explicit initialization. for an array passed as parameter. double& z[]) { . The static variable can be initialized by corresponded type constant. The specifier "static" is declared before a data type. Example: int Global_flag. Defining extern variables The memory class "extern" defines an extern variable. Note: it is not necessary to confuse the variables declared at a global level. Example: extern double InputParameter1 = 1. that the parameter is passed by reference. to global variables of Client Terminal. int start() { . double& y.initialized. it is impossible to change the array elements.. } Scope of global variables is the whole program. as well. as against a simple local variable which can be initialized by any expression. after a data type... Static variables The memory class "static" defines a static variable. There is a possibility to pass parameters by reference. it is necessary to put the modifier &. access to which is carried out by GlobalVariable..() function. instead of them defaults will be substituted..e. Global variables are accessible from all functions defined in the program. Initialization of global variables is made only once before execution of "init()" function. That is at exit from the function inside which the static variable is declared. Example: { static int flag } Static variables are constant ones since their values are not lost when the function is exited. Defining global variables They are defined on the same level as functions. they are not local in any block. Static variables are initialized only once before calling "init()" function. The parameters that passed by reference. except the formal parameters of the function. It is possible to pass arrays as parameters. 0. the value of this variable being not lost. These are modifications of a corresponding local variable inside the called function will not be reflected in any way in the calling function. Example: void func(int& x. the static variable is initialized with zero. By calling this function the initialized parameters can be omitted. The specifier "extern" is declared before a data type. To point. However.0. Any variables in a block. all modifications will be reflected in the initial array. } Arrays also can be passed by reference. In this case. Example: func(123. The global variable can be initialized only by corresponded type constant. They are initialized with zero if no other initial value is explicitly defined. int nType).. #import Preprocessor Declaring of constant Controlling compilation Including files Importing functions and other modules Declaring of constant If the first character in a program line is #. Such a compiler command ends with a carriage-return character. The absence of such a definition may result in errors during the compilation.16. It is not meaningful to define extern variables in scripts.4.9. External function definition The type of external functions defined in another component of a program must be explicitly defined. Any permanently located variable is initialized with zero (0) if no other initial value is explicitly defined. they are accessible from a property program sheet.int Msg. Local variables can be initialized by any expression.25. the values being not explicitly defined equal 0. Initialization of global and static variables is made only once.dll" int MessageBoxA(int hWnd . Initializing variables Any variable can be initialized during its definition. use the key word #import with the reference to the module. assembling or execution of your program. string szCaption. The value can be of any type.ex4" double round(double value). } Extern variables define input data of the program. // string initialization string s = "hello". it means that this line is a compiler command. Example: #define ABC 100 . #define identifier_value The identifier of a constant obeys the same rules as variable names.{ ..MODE_POINT). The list of array elements must be enclosed by curly braces. int SendMessageA(int hWnd. #import "lib. Basic types Examples: int mt = 1. If the array size is defined. and not just a constant. While describing an external object.string szText.int lParam). Global and static variables can be initialized only by constant of corresponded type. Arrays cannot represent itself as extern variables. Initialization of local variables is made each time by call of corresponded functions. Examples: #import "user32. // integer initialization // initialization floating-point number (double precision) double p = MarketInfo(Symbol(). Arrays Example: int mta[6] = {1.int wParam.36}. If the file is not found in the current directory. Since this name is enclosed in quotes. Importing functions and other modules #import "file_name" func1(). Example: #property link "http://www. func2(). the error will be messaged. Angle brackets mean that the file win32. the search is performed in the current directory (where the main file of the source code is located). #include "file_name" Example: #include "mylib. Including files Note: The #include command line can be placed anywhere in the program.314 #define COMPANY_NAME "MetaQuotes Software Corp.metaquotes. The current directory is not searched.net" #property copyright "MetaQuotes Software Corp. Controlling compilation #property identifier_value The list of predefined constant identifiers. where N lies between 1 and 8 before script run message box with confirmation appears before script run its property sheet appears.#define PI 0. where N lies between 1 and 8 predefined level N for separate window custom indicator." The compiler will replace each occurrence of an identifier in your source code with the corresponding value. terminal_directory\experts\include).h will be taken from the default directory (usually. . #include <file_name> Example: #include <win32. up to 8 the bottom border for the chart the top border for the chart the color for displaying line N." #property stacksize 1024 Constant link copyright stacksize indicator_chart_window Type string string int void Description a link to the company website the company name stack size show the indicator in the chart window show the indicator in a separate window the number of buffers for calculation.h.h" The compiler replaces this line with the content of the file mylib.h> The preprocessor replaces this line with the content of the file win32. disables show_confirm property indicator_separate_window void indicator_buffers indicator_minimum indicator_maximum indicator_colorN indicator_levelN show_confirm show_inputs int int int color double void void The compiler will write the declared values to the settings of the executable module. but usually all inclusions are placed at the beginning of the source code.h. int ReleaseDC(int hWnd.string lpCaption. Sample Print("Account company name ".string lpText. AccountCompany()).#import Example: #import "user32.int hDC). In the latter case.dll" int GetDC(int hWnd). AccountCredit()). int MessageBoxExA(int hWnd. the imported functions are also declared. #import Functions are imported from MQL4 compiled modules (*.ex4 files) and from operating system modules (*. string AccountCurrency() Returns currency name of the current account. Sample Print("Account balance = ". Sample Print("Account number ".int wLanguageId).AccountBalance()). A new #import command (it can be without parameters) finishes the description of imported functions. double AccountCredit() Returns credit value of the current account.dll files).string lpCaption.ex4" #import "gdi32.dll" int MessageBoxA(int hWnd. string AccountCompany() Returns the current account company name. Account Information AccountBalance() AccountCredit() AccountCompany() AccountCurrency() AccountEquity() AccountFreeMargin() AccountLeverage() AccountMargin() AccountName() AccountNumber() AccountProfit() double AccountBalance() Returns balance value of the current account. int uType. Sample . int uType). #import "melib.string lpText. Sample Print("Account free margin = ".AccountEquity()).AccountNumber(). Sample Print("account number ". double AccountProfit() Returns profit value of the current account . " leverage is ".Print("account currency is ". Sample Print("Account equity = ". Sample Print("Account profit ". AccountLeverage()). int AccountNumber() Returns the number of the current account. Sample Print("Account #".AccountFreeMargin()). string AccountName() Returns the current account name. Sample Print("Account margin ". AccountCurrency()). Array Functions ArrayBsearch() ArrayCopy() ArrayCopyRates() ArrayCopySeries() ArrayDimension() ArrayGetAsSeries() . int AccountLeverage() Returns leverage of the current account. double AccountEquity() Returns equity value of the current account. AccountProfit()). AccountMargin()). Sample Print("Account name ". AccountName()). AccountNumber()). double AccountFreeMargin() Returns free margin value of the current account. double AccountMargin() Returns margin value of the current account. Returns the amount of copied elements. Search direction. Source array. if(Time[shift]>=daytimes[0]) dayshift=0. MODE_DESCEND searching in the backward direction. double array2[10][6]. int count=WHOLE_ARRAY. start index is 0. Sample datetime daytimes[]. Starting index for the source array. By default. double value." corresponds to ". and bool[] can be copied as arrays with same type. } Print(TimeToStr(Time[shift]). else { dayshift=ArrayBsearch(daytimes. int[].0. start index is 0. if the occurrence is not found. Arrays must be of the same type.ArrayInitialize() ArrayIsSeries() ArrayMaximum() ArrayMinimum() ArrayRange() ArrayResize() ArraySetAsSeries() ArraySize() ArraySort() int ArrayBsearch( double array[]. It can be any of the following values: MODE_ASCEND searching in forward direction. or the nearest one. int start=0. To sort numeric arrays use ArraySort() functions.0. but arrays with type double[]. The count of elements that should be copied. // now array2 has first 10 bars in the history . ArrayCopy(array2." day bar opened at ". Sample double array1[][6].Symbol(). By default.Bars-9. object source[]. it searches in the whole array. By default. The function cannot be used with string arrays and serial numeric arrays. // fill array with some data ArrayCopyRates(array1). color[]. By default. Parameters dest[] source[] start_dest start_source count Destination array. Note: Binary search processes only sorted arrays. The value to search for. int count=WHOLE_ARRAY) Copies an array to another one. the search starts on the first element. int direction=MODE_ASCEND) Returns the index of the first occurrence of a value in the first dimension of array if possible. // All the Time[] timeseries are sorted in descendant mode ArrayCopySeries(daytimes.10). Starting index for the destination array. TimeToStr(daytimes[dayshift])).WHOLE_ARRAY. it is WHOLE_ARRAY constant. Parameters array[] value count start direction The numeric array to search for. int ArrayCopy( object& dest[]. array1. int shift=10. By default.Time[shift].MODE_DESCEND).dayshift. int start_dest=0. int start_source=0.PERIOD_D1). Starting index to search for.MODE_TIME. datetime[]. Count of elements to search for.dayshift. if(Period()<PERIOD_D1) dayshift++. the current chart symbol name is used.Time[shift]. Sample datetime daytimes[]. int shift=10. Print("Current bar ". 5 . 1 .Symbol(). Sample int num_array[10][5]. } Print(TimeToStr(Time[shift])."EURUSD". 4 . Note: If series_index is MODE_TIME. It can be any of Time frame enumeration values. where second dimension has 6 elements: 0 .dayshift. 3 . the first parameter must be a datetime array.MODE_TIME. string symbol=NULL." corresponds to ". by default.int ArrayCopyRates(double& dest_array[].low. current chart symbol name is used. int timeframe=0) Copies rates to the two-dimensional array from chart RateInfo array.WHOLE_ARRAY.PERIOD_D1).MODE_DESCEND). by default.TimeToStr(array1[0][0]). Sample double array1[][6]. Series array identifier. Note: Usually retrieved array used to pass large blocks of data to the DLL functions. Parameters dest_array[] symbol timeframe Reference to the two-dimensional destination numeric array. It can be any of Series array identifiers enumeration values. 2 . // All the Time[] timeseries are sorted in descendant mode ArrayCopySeries(daytimes.high. // dim_size is 2 . by default.volume. the current chart time frame is used. int ArrayCopySeries( double& array[]. ArrayCopyRates(array1. TimeToStr(daytimes[dayshift])). Parameters array[] array to retrieve dimensions count. symbol name." day bar opened at ". int ArrayDimension(int array[]) Returns array rank (dimensions count). array1[0][1]). PERIOD_H1). Time frame. Time frame."Open". int series_index. else { dayshift=ArrayBsearch(daytimes.time.open. dim_size=ArrayDimension(num_array). if(Period()<PERIOD_D1) dayshift++. the current chart time frame is used. int dim_size.dayshift. string symbol=NULL. It can be any of Time frame enumeration values. Parameters array[] series_index symbol timeframe Reference to the destination one-dimensional numeric array. int timeframe=0) Copies a series array to another one and returns the count of copied elements. if(Time[shift]>=daytimes[0]) dayshift=0. by default. Symbol name.0.close. 0). ArrayInitialize(myarray.9.1).2.4. int maxValueIdx=ArrayMaximum(num_array).6. Parameters array[] count start The numeric array to search for. Returns the count of initialized element. or volume). Parameters array[] Array to check. int start=0) Searches for element with minimum value and returns its position.close. return(-1). Start searching on the start index. Sample if(ArrayIsSeries(array1)==false) ArrayInitialize(array1.bool ArrayGetAsSeries(object array[]) Returns true if array is organized as a series array (array elements indexed from last to first) otherwise return false.1.1. Note: It is useless to initialize index buffers in the custom indicator init() function. Parameters . bool ArrayIsSeries(object array[]) Returns true if the array checked is a series array (time.1 double myarray[10]. Sample if(ArrayGetAsSeries(array1)==true) Print("array1 is indexed as a series array"). Scans for the count of elements in the array.high. Print("Max value = ". Sample //---.3.6.4. Parameters array[] Array to check.open.setting all elements of array to 2. int count=WHOLE_ARRAY. int ArrayInitialize(double& array[].1. Parameters array[] value Numeric array to be initialized. Sample double num_array[15]={4. num_array[maxValueIdx]).low.9}. else Print("array1 is indexed normally (from left to right)"). int ArrayMinimum(double array[]. double value) Sets all elements of numeric array to the same value. int count=WHOLE_ARRAY.3. } int ArrayMaximum(double array[]. New value to be set.9. int start=0) Searches for elements with maximum value and returns its position. else { Print("Series array cannot be initialized!").6.3. i++) signal_buffer[i]=iMAOnArray(macd_buffer.MODE_EMA. i++) macd_buffer[i]=iMA(NULL.MODE_EMA. Parameters array[] set The numeric array to set.1. i<limit. int ArrayRange(object array[]. The Series flag to set (true) or drop (false).0.10. int ArrayResize(object& array[]. i. int i.6. num_array[minValueIdx]). int new_size) Sets new size to the first dimension. int ArraySize(object array[]) Returns the count of elements contained in the array.0.3.limit.1. Parameters array[] new_size Array to resize. otherwise.9}.10]. int element_count=ArrayResize(array.array[] count start - The numeric array to search for.0.9.6.MODE_SMA.i)iMA(NULL. Sample int dim_size.PRICE_CLOSE. Parameters array[] range_index Array to check Dimension index. the size of dimension is 1 greater than the largest index. New size for the first dimension. for(i=0. returns zero and array is not resized.6.true). for(i=0.0. i<limit. Sample double array1[][4].9. Start searching on the start index. .i). Sample double num_array[15]={4.0. Since indexes are zero-based.3.limit=ArraySize(macd_buffer). Print("Min value = ".26.e.4. dim_size=ArrayRange(num_array.4. ArraySetAsSeries(macd_buffer. double num_array[10.1. double signal_buffer[300].i). bool set) Sets indexing order of the array like a series arrays. If success returns count of all elements contained in the array after resizing. int range_index) Returns the count of elements in the indicated dimension of the array. // element count is 80 elements bool ArraySetAsSeries(double& array[]. 1).9. Returns previous state.3. last element has zero index. double minValueidx=ArrayMinimum(num_array). Scans for the count of elements in the array. Sample double macd_buffer[300].PRICE_CLOSE.12. 20). int sort_dir=MODE_ASCEND) Sorts numeric arrays by first dimension.9 ArraySort(num_array. // now array is sorted 1.Parameters array[] Array of any type. i<count. Starting index. Sample int count=ArraySize(array1).MODE_DESCEND). Array sorting direction. Series arrays cannot be sorted by ArraySort(). // now array contains values 4.6.9 ArraySort(num_array).3. i++) { // do some calculations.3.1. } int ArraySort( Parameters array[] count start sort_dir - double& array[].9}. // now array is sorted 9. for(int i=0.3.1 Common functions Alert() ClientTerminalName() CompanyName() Comment() GetLastError() GetTickCount() HideTestIndicators() IsConnected() IsDemo() IsDllsAllowed() IsLibrariesAllowed() IsStopped() IsTesting() IsTradeAllowed() MarketInfo() MessageBox() Period() PlaySound() Print() RefreshRates() SendMail() ServerAddress() Sleep() SpeechText() Symbol() UninitializeReason() . Sample double num_array[5]={4.6.3.sort ascending.6.4.sort descending. int start=0. Count of elements to sort. int count=WHOLE_ARRAY.4. The numeric array to sort. It can be any of the following values: MODE_ASCEND . MODE_DESCEND .1.6. ) Displays a dialog box containing the user-defined data. Print("error(".ClientTerminalName())."Current time is ". Sample Print("Terminal name is ". return(0)... Close[0].ErrorDescription(err)). int GetLastError() Returns last occurred error after an operation and sets internal last error value to zero. Parameters . datetime and color types will be printed as its numeric presentation. separated by commas. void Comment(. See also: Comment() and Print() functions. Comment("Account free margin is ". Sample if(Close[0]>SignalLevel) Alert("Close price coming ". ) Prints some message to the left top corner of the chart. separated by commas. Sample int err.. Data of double type printed with 4 decimal digits after point. Any values."): ".. See also: Alert() and Print() functions. To print with more precision use DoubleToStr() function.void Alert(.dat". To print values of datetime type as string convert it by TimeToStr() function.err. Data of double type printed with 4 decimal digits after point. string CompanyName() Returns Company name Sample Print("Company name is ". Data of bool. if(handle<1) { err=GetLastError(). string ClientTerminalName() Returns Client Terminal Name. Arrays should be output elementwise. } .DoubleToStr(free."!!!"). Arrays cannot be passed to the Alert function. int handle=FileOpen("somefile. To print values of datetime type as string convert it by TimeToStr() function. Sample double free=AccountFreeMargin().2)."\n".. Data of bool. Parameters can be of any type. Arrays cannot be passed to the Comment() function. Parameters .TimeToStr(CurTime())). datetime and color types will be printed as its numeric presentation. Any values.. Parameters can be of any type.CompanyName()). To print with more precision use DoubleToStr() function. FILE_READ|FILE_BIN)... .. Print("Calculation time is ". FALSE."). otherwise.. string szCaption.dll" int MessageBoxA(int hWnd . bool IsDllsAllowed() Returns true if DLL function call is allowed for the expert. GetTickCount()-start. Sample #import "user32. Sample HideTestIndicators(true).. otherwise returns false.int GetTickCount() The GetTickCount() function retrieves the number of milliseconds that have elapsed since the system was started. After the chart has been tested and opened the flagged indicators will not be drawn on the testing chart. " milliseconds..int nType). See also IsLibrariesAllowed(). . Parameters hide TRUE . } // Expert body that need opened connection // . // do some hard calculation.if indicators must be hidden. else Print("I am working on real account").. return(0). } // expert body that calls external DLL functions MessageBoxA(0. It is limited to the resolution of the system timer.string szText. if(IsDllsAllowed()==false) { Print("DLL call is not allowed. . Every indicator called will first be flagged with the current hiding flag.. Sample if(!IsConnected()) { Print("Connection is broken!"). Sample if(IsDemo()) Print("I am working on demo account"). IsTradeAllowed(). bool IsConnected() Returns true if client terminal has opened connection to the server."Message". return(0)..MB_OK). otherwise returns false."). Sample int start=GetTickCount(). Experts cannot run. ."an message". otherwise returns false. bool IsDemo() Returns true if expert runs on demo account. void HideTestIndicators(bool hide) The function sets a flag hiding indicators called by the Expert Advisor. Sample double var. return(0). } bool IsTesting() Returns true if expert runs in the testing mode. displays. // long time procesing cycle // . . otherwise returns false... This function can be used in the cycles to determine expert unloading. See also IsDllsAllowed(). int MessageBox(string text=NULL. var=MarketInfo("EURUSD". bool IsStopped() Returns true if expert in the stopping state. Experts cannot run. IsLibrariesAllowed().. bool IsTradeAllowed() Returns true if trade is allowed for the expert. Sample if(IsTesting()) Print("I am testing now"). } // expert body that calls external DLL functions somefunc(). otherwise returns false. It can be any of Market information identifiers value. int type) Returns value from Market watch window. . Parameters symbol type Instrument symbol.ex4" int somefunc(). otherwise returns false.bool IsLibrariesAllowed() Returns true if expert can call library function. Sample if(IsTradeAllowed()) Print("Trade allowed"). IsTradeAllowed(). int flags=EMPTY) The MessageBox function creates. Sample while(expr!=false) { if(IsStopped()==true) return(0). otherwise returns false. if(IsLibrariesAllowed()==false) { Print("Library call is not allowed.").. Sample #import "somelibrary. See also IsDllsAllowed(). The message box contains an application-defined . Returning data type index. double MarketInfo(string symbol..MODE_BID).. string caption=NULL. and operates a message box. message and title, plus any combination of predefined If the function succeeds, the return value is one of the MessageBox return code values. icons and push buttons. Parameters text caption flags Optional text that contains the message to be displayed. Optional text that contains the dialog box title.If this parameter is NULL, the title will be name of expert. Specifies the contents and behavior of the dialog box.This optional parameter can be a combination of flags from the following groups of flags. Sample #include <WinUser32.mqh> if(ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045)==false) { int ret=MessageBox("ObjectCreate() fails with code "+GetLastError()+"\nContinue?", "Question", MB_YESNO|MB_ICONQUESTION); if(ret==IDNO) return(false); } // continue int Period() Returns the number of minutes defining the used period (chart timeframe). Sample Print("Period is ", Period()); void PlaySound(string filename) Function plays sound file. File must be located at the terminal_dir\sounds directory or its subdirectory. Parameters filename Sound file name. Sample if(IsDemo()) PlaySound("alert.wav"); void Print(... ) Prints some message to the experts log. Parameters can be of any type. Arrays cannot be passed to the Print() function. Arrays should be printed elementwise. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. See also: Alert() and Comment() functions. Parameters ... Any values, separated by commas. Sample Print("Account free margin is ", AccountFreeMargin()); Print("Current time is ", TimeToStr(CurTime())); double pi=3.141592653589793; Print("PI number is ", DoubleToStr(pi,8)); // Output: PI number is 3.14159265 // Array printing for(int i=0;i<10;i++) Print(Close[i]); bool RefreshRates() Refreshing data in the built-in variables and series arrays. This function is used when expert advisor calculates for a long time and needs refreshing data. Returns true if data are refreshed, otherwise false. Sample int ticket; while(true) { ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE); if(ticket<=0) { int error=GetLastError(); if(error==134) break; // not enough money if(error==135) RefreshRates(); // prices changed break; } else { OrderPrint(); break; } //---- 10 seconds wait Sleep(10000); } void SendMail(string subject, string some_text) Sends mail to address set in the Tools->Options->EMail tab if enabled. Note: Posting e-mail can be denied or address can be empty. Parameters subject some_text Subject text. Mail body. Sample double lastclose=Close[0]; if(lastclose<my_signal) SendMail("from your expert", "Price dropped down to "+DoubleToStr(lastclose)); string ServerAddress() Returns connected server address in form of a text string. Sample Print("Server address is ", ServerAddress()); void Sleep(int milliseconds) The Sleep function suspends the execution of the current expert for a specified interval. Parameters milliseconds Sleeping interval in milliseconds. Sample Sleep(5); void SpeechText(string text, int lang_mode=SPEECH_ENGLISH) Computer speaks some text. Parameters text lang_mode Speaking text. SPEECH_ENGLISH (by default) or SPEECH_NATIVE values. Sample double lastclose=Close[0]; SpeechText("Price dropped down to "+DoubleToStr(lastclose)); string Symbol() Returns a text string with the name of the current financial instrument. Sample int total=OrdersTotal(); for(int pos=0;pos<total;pos++) { // check selection result becouse order may be closed or deleted at this time! if(OrderSelect(pos, SELECT_BY_POS)==false) continue; if(OrderType()>OP_SELL || OrderSymbol()!=Symbol()) continue; // do some orders processing... } int UninitializeReason() Returns the code of the uninitialization reason for the experts, custom indicators, and scripts. Return values can be one of Uninitialize reason codes. Sample // this is example int deinit() { switch(UninitializeReason()) { case REASON_CHARTCLOSE: case REASON_REMOVE: CleanUp(); break; // clean up and free all expert's resources. case REASON_RECOMPILE: case REASON_CHARTCHANGE: case REASON_PARAMETERS: case REASON_ACCOUNT: StoreData(); break; // prepare to restart } //... } Conversion functions CharToStr() DoubleToStr() NormalizeDouble() StrToDouble() StrToInteger() StrToTime() TimeToStr() string CharToStr(int char_code) Returns string with one symbol that have specified code Parameters char_code ASCII char code. Sample string str="WORL" + CharToStr(44); // 44 is code for 'D' // resulting string will be WORLD string DoubleToStr(double value, int digits) Returns text string with the specified numerical value transformed into the specified precision format. Parameters value digits Numerical value. Precision format, number of digits after decimal point (0-8). Sample string value=DoubleToStr(1.28473418, 5); // value is 1.28473 double NormalizeDouble(double value, int digits) Rounds floating point number to specified decimal places. Parameters value digits Floating point value. Precision format, number of digits after decimal point (0-8). Sample double var1=0.123456789; Print(NormalizeDouble(var1,5)); // output: 0.12346 double StrToDouble(string value) Converts string representation of number to type double. Parameters value String containing value in fixed number format. Sample double var=StrToDouble("103.2812"); int StrToInteger(string value) Converts string representation of number to type integer. Parameters value String containing integer number. Sample int var1=StrToInteger("1024"); datetime StrToTime(string value) Converts string in the format "yyyy.mm.dd hh:mi" to type datetime. Parameters value String value of date/time format such as "yyyy.mm.dd hh:mi". Sample datetime var1; var1=StrToTime("2003.8.12 17:35"); var1=StrToTime("17:35"); // returns with current date var1=StrToTime("2003.8.12"); // returns with midnight time "00:00" string TimeToStr(datetime value, int mode=TIME_DATE|TIME_MINUTES) Returns time as string in the format "yyyy.mm.dd hh:mi". Parameters value mode - Positive number of seconds from 00:00 January 1, 1970. Optional data output mode can be one or combination of: TIME_DATE get result in form "yyyy.mm.dd", TIME_MINUTES get result in form "hh:mi", TIME_SECONDS get result in form "hh:mi:ss". Sample strign var1=TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS); Custom Indicator functions IndicatorBuffers() IndicatorCounted() IndicatorDigits() IndicatorShortName() SetIndexArrow() SetIndexBuffer() SetIndexDrawBegin() SetIndexEmptyValue() SetIndexLabel() SetIndexShift() SetIndexStyle() SetLevelStyle() SetLevelValue() void IndicatorBuffers(int count) Allocates memory for buffers used for custom indicator calculations. Cannot be greater than 8 and less than indicator_buffers property. If custom indicator requires additional buffers for counting then use this function for pointing common buffers count. Parameters count Buffers count to allocate. Should be up to 8 buffers. Sample #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- indicator parameters extern int FastEMA=12; extern int SlowEMA=26; extern int SignalSMA=9; //---- indicator buffers double ind_buffer1[]; double ind_buffer2[]; double ind_buffer3[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- 2 additional buffers are used for counting. IndicatorBuffers(3); //---- drawing settings SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3); SetIndexDrawBegin(0,SignalSMA); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2); //---- 3 indicator buffers mapping SetIndexBuffer(0,ind_buffer1); SetIndexBuffer(1,ind_buffer2); SetIndexBuffer(2,ind_buffer3); } //---.i).0.PRICE_MEDIAN. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---. double ind_buffer2[]. } int IndicatorCounted() Returns bars count that does not changed after last indicator launch. extern int SlowEMA=26. ExtLimeBuffer[i]=iMA(NULL.//---. number of digits after decimal point. Sample #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---.ma_shift set to 0 because SetIndexShift called abowe ExtBlueBuffer[i]=iMA(NULL. Parameters digits Precision format. In most cases same count of index values do not need for recalculation. int counted_bars=IndicatorCounted(). Sample int start() { int limit.PRICE_MEDIAN. double ind_buffer3[].initialization done return(0). limit=Bars-counted_bars.MODE_SMMA. //---.indicator parameters extern int FastEMA=12. } void IndicatorDigits(int digits) Sets default precision format for indicators visualization.indicator buffers double ind_buffer1[].2 additional buffers are used for counting. ExtRedBuffer[i]=iMA(NULL. Used for optimizing calculations. i<limit.MODE_SMMA."+SlowEMA+".main loop for(int i=0.done return(0). //---.JawsPeriod. //---.name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+".TeethPeriod.0.PRICE_MEDIAN.MODE_SMMA.0.LipsPeriod.last counted bar will be recounted if(counted_bars>0) counted_bars--. i++) { //---.i).0."+SignalSMA+")").check for possible errors if(counted_bars<0) return(-1).0. //---.i). extern int SignalSMA=9.0. //---. . extern int SlowEMA=26.initialization done return(0)."+SignalSMA+")"). //---. //---. extern int SignalSMA=9. //---. //---.ind_buffer1).STYLE_SOLID.DRAW_HISTOGRAM. double ind_buffer2[].SignalSMA). SetIndexBuffer(1.ind_buffer1). } void SetIndexArrow(int index.name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+".ind_buffer3).MODE_DIGITS)+2). //---.ind_buffer2).MODE_DIGITS)+2). IndicatorDigits(MarketInfo(Symbol()."+SlowEMA+". IndicatorDigits(MarketInfo(Symbol(). //---.DRAW_HISTOGRAM.drawing settings SetIndexStyle(0. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---. SetIndexDrawBegin(0. SetIndexBuffer(2. //---. SetIndexBuffer(2. int code) .3).3). //---.3 indicator buffers mapping SetIndexBuffer(0."+SlowEMA+".2 additional buffers are used for counting. double ind_buffer3[]. IndicatorBuffers(3).indicator parameters extern int FastEMA=12.name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+".STYLE_SOLID. //---. SetIndexDrawBegin(0.ind_buffer3). } void IndicatorShortName(string name) Sets indicator short name for showing on the chart subwindow.drawing settings SetIndexStyle(0.IndicatorBuffers(3).3 indicator buffers mapping SetIndexBuffer(0. Parameters name New short name.SignalSMA)."+SignalSMA+")").initialization done return(0).indicator buffers double ind_buffer1[]. SetIndexBuffer(1.ind_buffer2). Sample #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---. int init() { SetIndexBuffer(0.2 additional buffers are used for counting. } void SetIndexDrawBegin(int index. Should be from 0 to 7. Index values before draw begin are not significant and does not drawn and not show in the DataWindow. Sample #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---. bool SetIndexBuffer(int index. Array that stores calculated indicator values.drawing settings SetIndexStyle(0. SetIndexDrawBegin(0. int begin) Sets first bar from what index will be drawn. extern int SignalSMA=9. //---. Parameters index begin Line index. If the function succeeds. //---. First drawing bar position number. Parameters index code Line index. . double array[]) Sets buffer for calculating line.DRAW_HISTOGRAM. extern int SlowEMA=26.indicator parameters extern int FastEMA=12. //---. Symbol code from Wingdings font or Array constants. the return value is true. Sample double ExtBufferSilver[]. Should be from 0 to 7.ind_buffer1). The indicated array bound with previously allocated custom indicator buffer. 217).STYLE_SOLID. If the function fails.3 indicator buffers mapping SetIndexBuffer(0. the return value is false.. double ind_buffer2[]. ExtBufferSilver). double ind_buffer3[].indicator buffers double ind_buffer1[].. IndicatorBuffers(3).SignalSMA).MODE_DIGITS)+2).3). call GetLastError().Sets arrow symbol for indicators that draws some lines as arrow. To get the detailed error information. Parameters index array[] Line index. // set buffer for first line // . IndicatorDigits(MarketInfo(Symbol(). Sample SetIndexArrow(0. Should be from 0 to 7. SetIndexBuffer(1.Kijun+a_begin-1). empty value line is EMPTY_VALUE.DRAW_HISTOGRAM. New empty value. //---.Kijun). Sample SetIndexEmptyValue(6. double value) Sets drawing line empty value. Empty values are not drawn and not show in the DataWindow.ind_buffer2).0. SetIndexLabel(5. //---SetIndexStyle(3. SetIndexStyle(5.STYLE_DOT). //---. .STYLE_DOT). SetIndexBuffer(1."Senkou Span A"). Label text. NULL means that index value does not show in the DataWindow.name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+".ind_buffer3). Should be from 0 to 7.0001).Kijun_Buffer). SetIndexBuffer(5. //---a_begin=Kijun."Tenkan Sen").DRAW_LINE). SetIndexLabel(0. SetIndexShift(2.SpanA2_Buffer). Sample //+------------------------------------------------------------------+ //| Ichimoku Kinko Hyo initialization function | //+------------------------------------------------------------------+ int init() { //---SetIndexStyle(0.initialization done return(0). SetIndexDrawBegin(1.STYLE_DOT)."Kijun Sen"). SetIndexLabel(1. if(a_begin<Tenkan) a_begin=Tenkan. } void SetIndexEmptyValue(int index.Up Kumo bounding line does not show in the DataWindow SetIndexLabel(2.Kijun).DRAW_HISTOGRAM. string text) Sets drawing line description for showing in the DataWindow. SetIndexDrawBegin(0. Should be from 0 to 7. SetIndexDrawBegin(5. SetIndexShift(5. //---SetIndexStyle(1.DRAW_LINE). Parameters index value Line index.SpanA_Buffer)."+SlowEMA+". void SetIndexLabel(int index. SetIndexDrawBegin(2. SetIndexBuffer(2. SetIndexStyle(2. By default.Tenkan_Buffer)."+SignalSMA+")"). //---.DRAW_LINE.NULL).Tenkan-1). SetIndexBuffer(0.Kijun+a_begin-1).Kijun-1). Parameters index text Line index. SetIndexBuffer(2. //---."Gator Jaws").3 indicator buffers mapping SetIndexBuffer(0.initialization done return(0).TeethShift). SetIndexStyle(1."Gator Lips").ExtRedBuffer). SetIndexStyle(2.drawing settings SetIndexStyle(0. //---SetIndexStyle(4.Kijun+Senkou-1).NULL). SetIndexLabel(4.LipsShift).JawsShift+JawsPeriod).STYLE_DOT).Kijun+Senkou-1).index labels SetIndexLabel(0. //---return(0).DRAW_LINE). //---. //---.-Kijun).DRAW_LINE.JawsShift). SetIndexShift(1. Line will be counted on the current bar. SetIndexDrawBegin(1. //---. SetIndexShift(6. SetIndexShift(3.SpanB_Buffer).Kijun). Sample //+------------------------------------------------------------------+ //| Alligator initialization function | //+------------------------------------------------------------------+ int init() { //---.TeethShift+TeethPeriod). int shift) Sets offset for drawing line.DRAW_LINE)."Chinkou Span"). SetIndexDrawBegin(2. } . Should be from 0 to 7.LipsShift+LipsPeriod). SetIndexBuffer(6.SetIndexBuffer(3. SetIndexDrawBegin(3. SetIndexLabel(1.Kijun). but will be drawn shifted. Shitf value in bars.ExtLimeBuffer). SetIndexBuffer(1. SetIndexBuffer(4."Senkou Span B")."Gator Teeth"). } void SetIndexShift(int index.DRAW_LINE).line shifts when drawing SetIndexShift(0.Chinkou_Buffer).DRAW_LINE).ExtBlueBuffer). //---. SetIndexLabel(2. SetIndexDrawBegin(6.SpanB2_Buffer). SetIndexShift(4.Down Kumo bounding line does not show in the DataWindow SetIndexLabel(3. //---. SetIndexBuffer(2.first positions skipped when drawing SetIndexDrawBegin(0. //---SetIndexStyle(6. SetIndexShift(2. Parameters index shift Line index. SetIndexLabel(6. EMPTY. EMPTY value indicates that style does not changed. Line color.Can be one of Shape style constants. Sample SetLevelValue(1. int style=EMPTY.2.4. int line_width.5.4.Can be one of Drawing shape style enumeration.2. Line color. Date & Time functions CurTime() Day() DayOfWeek() DayOfYear() Hour() LocalTime() Minute() Month() Seconds() TimeDay() TimeDayOfWeek() TimeDayOfYear() TimeHour() TimeMinute() TimeMonth() TimeSeconds() TimeYear() Year() . Shape style. void SetLevelStyle(int draw_style.5. 2.3. Line width.Can be one of Shape style enumeration. color clr=CLR_NONE) Function sets new style. width and color for a given indicator line. Except for STYLE_SOLID.1. int width=EMPTY. Parameters level value Level index (0-31). color clr=CLR_NONE) Sets new type. Line index.Red) int SetLevelValue(int level.show levels as thick red lines SetLevelStyle(STYLE_SOLID.14). Sample //---.void SetIndexStyle( Parameters index type style width clr - int index. Line width. Valid values are 1.2. style.3. Value for the given indicator level.EMPTY value indicates that style will not be changed. width and color of indicator levels. valid values . Red). Except STYLE_SOLID style all other styles valid when width is 1 pixel.3. EMPTY value indicates that width will not be changed. EMPTY value indicates that width does not changed. Parameters draw_style line_width clr Drawing style. Drawing style. DRAW_LINE. Sample SetIndexStyle(3. int type. all other styles are valid if the width is 1 pixel. Should be from 0 to 7. double value) Function sets a new value for the given indicator level. .8.23) Sample bool is_siesta=false.2.4. Sample if(Day()<5) return(0).5. Sample if(CurTime()-OrderOpenTime()<360) return(0).11. 1970. Sample if(LocalTime()-OrderOpenTime()<360) return(0).4.2.1.31 december). 1970. int Minute() Returns current minute (0. Sample if(DayOfYear()==245) return(true)..12).1. int Day() Returns the current day of the month.1. int DayOfWeek() Returns the current zero based day of the week (0-Sunday. datetime LocalTime() Returns local computer time.10. int Month() Returns current month as number (1-January.5.2.7.. if(DayOfWeek()==0 || DayOfWeek()==6) return(0)... number of seconds elapsed from 00:00 January 1.3.6).6. Sample // do not work on holidays. number of seconds elapsed from 00:00 January 1.3..9. int Hour() Returns current hour (0.59). if(Hour()>=12 || Hour()<17) is_siesta=true.. int DayOfYear() Returns the current day of the year (1-1 january.datetime CurTime() Returns the last known server time.2. Sample if(Minute()<=15) return("first quarter"). Sample .365(6) . 11.4. 1970. 1970. Sample int weekday=TimeDayOfWeek(D'2004.. January 1.3. Parameters date Datetime is the number of seconds elapsed since midnight (00:00:00). // day is 2 . 1970. . int Seconds() Returns current second (0.2').1. Parameters date Datetime is the number of seconds elapsed since midnight (00:00:00).12.tuesday int TimeDayOfYear(datetime date) Returns day (1-1 january.5. Sample int day=TimeDay(D'2003.6) for specified date. January 1. int TimeHour(datetime time) Returns hour for specified time.. Sample int m=TimeMinute(CurTime()).1.31 december) of year for specified date. int TimeDay(datetime date) Returns day of month (1 . Sample int h=TimeHour(CurTime()). // day is 31 int TimeDayOfWeek(datetime date) Returns zero based day of week (0-Sunday. January 1. Parameters time Datetime is the number of seconds elapsed since midnight (00:00:00).if(Month()<=5) return("first half of year"). Parameters date Datetime is the number of seconds elapsed since midnight (00:00:00). 1970. Sample int day=TimeDayOfYear(CurTime()).. January 1. 1970.59)..365(6) .31) for specified date.31'). Parameters time Datetime is the number of seconds elapsed since midnight (00:00:00). January 1. int TimeMinute(datetime time) Returns minute for specified time.. Sample if(Seconds()<=15) return(0).2.2. int TimeSeconds(datetime time) Returns seconds after minute (0 – 59) for specified time. January 1. File functions FileClose() FileDelete() FileFlush() FileIsEnding() FileIsLineEnding() FileOpen() FileOpenHistory() FileReadArray() FileReadDouble() FileReadInteger() FileReadNumber() FileReadString() FileSeek() FileSize() FileTell() FileWrite() FileWriteArray() FileWriteDouble() FileWriteInteger() . 1970. int TimeYear(datetime time) Returns year for specified date. Sample int y=TimeYear(CurTime()). Parameters time Datetime is the number of seconds elapsed since midnight (00:00:00). Parameters time Datetime is the number of seconds elapsed since midnight (00:00:00). 1970. Sample int m=TimeMonth(CurTime()). January 1. int Year() Returns current year.int TimeMonth(datetime time) Returns month for specified time. Sample int m=TimeSeconds(CurTime()). 1970. January 1. Return values can be in range 1970-2037. Sample // return if date before 1 May 2002 if(Year()==2002 && Month()<5) return(0). Parameters time Datetime is the number of seconds elapsed since midnight (00:00:00). "#". returned by FileOpen() functions Sample int handle=FileOpen("filename". FileClose(handle). int handle=FileOpen("mydat. returned by FileOpen() functions Sample int handle=FileOpen("filename".FileWriteString() void FileClose(int handle) Closes file previously opened by FileOpen() functions. returned by FileOpen() functions.i<bars_count.High[i]. otherwise returns false. if(handle>0) { FileWrite(handle. FILE_CSV|FILE_READ). for(int i=0. ."CLOSE". To get the detailed error information.i++) FileWrite(handle.Open[i]. } bool FileIsEnding(int handle) Returns logical true if file pointer is at the end of the file.Close[i]."HIGH".i<bars_count. for(int i=0. FileClose(handle)."LOW"). i+1. Parameters handle File handle.i++) FileWrite(handle.csv". Parameters handle File handle. Low[i]). FileClose(handle).. FileFlush(handle)..High[i].. Low[i]). if(handle>0) { // working with file .Open[i].. Parameters . } void FileClose(int handle) Closes file previously opened by FileOpen() functions. Parameters handle File handle. i+1. } void FileFlush(int handle) Flushes all data stored in the file buffer to disk. Sample int bars_count=Bars. FILE_CSV|FILE_READ)...Close[i].FILE_CSV|FILE_WRITE). call GetLastError() function."OPEN". if(handle>0) { // working with file . FILE_CSV. can be one or combination of values: FILE_BIN.handle - File handle. the return value less than 1.FILE_CSV|FILE_READ. Open mode. } bool FileIsLineEnding(int handle) For CSV file returns logical true if file pointer is at the end of the line. can be one or combination of values: FILE_BIN. returned by FileOpen() functions. Open mode. Sample int handle=FileOpenHistory("USDX240. If the function fails. If the function fails. int delimiter='. To get the detailed error information. return(false).HST"). handle=FileOpen("my_data. file may be with any extensions. if(handle<1) { Print("File my_data. return(false).'. GetLastError()). Sample int handle. To get the detailed error information. the last error is ". FILE_WRITE. otherwise returns false. int mode. Parameters filename mode delimiter File name. By default passed '. int mode. Parameters filename mode delimiter File name.csv".' symbol. FILE_CSV. FILE_READ. Sample if(FileIsLineEnding(h1)) { FileClose(h1). if(handle<1) { Print("Cannot create file USDX240.'). return(false). Note: Files can be opened only from terminal_dir\experts\files directory and its subdirectories. call GetLastError() function. int delimiter='. Delimiter character for csv files. Sample if(FileIsEnding(h1)) { FileClose(h1). } int FileOpen(string filename. call GetLastError() function. FILE_READ. Parameters handle File handle. the return value less than 1. } . Delimiter character for csv files. returned by FileOpen() function. file may be with any extensions.') Opens file in the current history directory for input and/or output.') Opens file for input and/or output.FILE_BIN|FILE_WRITE). } int FileOpenHistory(string filename.' symbol. call GetLastError(). By default passed '. Returns a file handle for the opened file.dat not found. return(false). Returns a file handle for the opened file. To get the detailed error information. FILE_WRITE.HST". int value. array must be resized to a sufficient size. varray. varray. if(handle>0) { FileReadArray(handle. Integer format size can be 1. } int FileReadArray(int handle. SHORT_VALUE(2 bytes) or LONG_VALUE(4 bytes). FileClose(handle). Storing start position into array. FileClose(handle). Note: Before reading the data. Sample int handle. To get the detailed error information. Array where data will be stored. . int count) Reads the indicated count of elements from the binary file to array. handle=FileOpen("filename. Format size. } int FileReadInteger(int handle. call GetLastError() function. object& array[]. Sample int handle. To get the detailed error information. Sample int handle. Storing start position into array. Count of elements to read. Returns actual read elements count. handle=FileOpen("filename. object& array[]. 10). array must be resized to a sufficient size. int count) Reads the indicated count of elements from the binary file to array. double varray[10]. returned by FileOpen() function. 0. FileClose(handle). call GetLastError() function. If the format size is not specified system attempts to read 4 bytes length value.. FILE_BIN|FILE_READ). Parameters handle array[] start count File handle.dat". int FileReadArray(int handle. returned by FileOpen() function. int start.. Returns actual read elements count. Count of elements to read. returned by FileOpen() function. int start. call GetLastError() function. if(handle>0) { FileReadArray(handle.dat". To get the detailed error information. Note: Before reading the data. Parameters handle array[] start count File handle. 0.// work with file // . Parameters handle size File handle. Array where data will be stored. 2 or 4 bytes length. FILE_BIN|FILE_READ). Can be CHAR_VALUE(1 byte). double varray[10]. 10). int size=LONG_VALUE) Read the integer from binary files from the current file position. '. Sample int handle. Otherwise. The FileSeek() function moves the file pointer associated with handle to a new location that is offset bytes from origin.2). To get the detailed error information. To get the detailed error information. Offset in bytes from origin. The next operation on the file occurs at the new location. } double FileReadNumber(int handle) Read the number from the current file position to the delimiter. FILE_CSV. string str. Parameters handle length File handle. if(handle>0) { value=FileReadNumber(handle). Applied to both CSV and binary files. FileClose(handle). returned by FileOpen() function. Value can be one of this constants: SEEK_CUR .csv".from end of file. if(handle>0) . call GetLastError() function. call GetLastError() function. Parameters handle File handle.dat". FileClose(handle). it returns FALSE.'). int value.handle=FileOpen("mydata. If successful. int length=0) Read the string from the current file position. call GetLastError() function. if(handle>0) { value=FileReadInteger(h1. Parameters handle offset origin File handle.'). handle=FileOpen("filename. FILE_BIN|FILE_READ). SEEK_SET . SEEK_END .from current position. Only for CSV files.csv". Sample int handle. Sample int handle=FileOpen("filename. '. For text files string will be read to the delimiter and for binary file string will be read for the count of characters indicated. returned by FileOpen() function. int offset.from begin. if(handle>0) { str=FileReadString(handle). FILE_CSV|FILE_READ. int origin) Moves the file pointer to a specified location. To get the detailed error information. returned by FileOpen() functions. } bool FileSeek(int handle. FileClose(handle). } string FileReadString(int handle. Reading characters count. FILE_CSV|FILE_READ). handle=FileOpen("filename.csv". function returns TRUE. Initial position. handle=0. FILE_BIN|FILE_READ). delimiter inserted automatically.but color. 10.'). int size. '. handle=FileOpen("filename". Parameters handle .dat". call GetLastError() function.. Parameters handle File handle. } int FileSize(int handle) Returns file size in bytes. To get the detailed error information. To get the detailed error information. Returns the number of characters written. size. " bytes").dat size is ".. FILE_BIN|FILE_READ). " bytes"). if(handle>0) { size=FileSize(handle).dat". } int FileSize(int handle) Returns file size in bytes. handle=FileOpen("my_table. FileReadInteger(handle). Sample int handle. SEEK_SET). Sample int handle. call GetLastError() function. call GetLastError() function.. To get the detailed error information. . or a negative value if an error occurs. returned by FileOpen() function. FILE_CSV|FILE_WRITE. User data to write. datetime and bool types does not automatically converted and will be writen to file in it's as integers. Parameters handle File handle. separated with commas. if(handle>0) { . FileClose(handle). handle=FileOpen("my_table. returned by FileOpen() function. Sample int handle.dat size is ". datetime orderOpen=OrderOpenTime(). ) Writes to the CSV file some values.{ FileSeek(handle. Print("my_table.. FileClose(handle). returned by FileOpen() function. } int FileWrite(int handle. int size. File handle. if(handle>0) { size=FileSize(handle). Print("my_table. Note: int and double types automatically converted to string. size. FileClose(handle). FileWrite(handle, Close[0], Open[0], High[0], Low[0], TimeToStr(orderOpen)); FileClose(handle); } int FileWriteArray(int handle, object array[], int start, int count) Writes array to the binary file. Arrays of type int, bool, datetime and color will be written as 4 bytes integers. Arrays of type double will be written as 8 bytes floating point numbers. Arrays of string will be written as one string where elements will be divided by Carriage return and Line feed symbols (0D 0A). Returns the number of elements wrote, or a negative value if an error occurs. To get the detailed error information, call GetLastError() function. Parameters handle array[] start count File handle, returned by FileOpen() function. Array to write. Starting index into array to write. Count of elements to write. Sample int handle; double BarOpenValues[10]; // copy first ten bars to the array for(int i=0;i<10; i++) BarOpenValues[i]=Open[i]; // writing array to the file handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE); if(handle>0) { FileWriteArray(handle, BarOpenValues, 3, 7); // writing last 7 elements FileClose(handle); } int FileWriteDouble(int handle, double value, int size=DOUBLE_VALUE) Writes double value to the binary file. If size is FLOAT_VALUE, value will be written as 4 bytes floating point format, else will be written in 8 bytes floating point format. Returns actual written bytes count. To get the detailed error information, call GetLastError() function. Parameters handle value size File handle, returned by FileOpen() function. Value to write. Optional format flag. It can be any of the following values: DOUBLE_VALUE (8 bytes, default) FLOAT_VALUE (4 bytes). Sample int handle; double var1=0.345; handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE); if(handle<1) { Print("can't open file error-",GetLastError()); return(0); } FileWriteDouble(h1, var1, DOUBLE_VALUE); //... FileClose(handle); int FileWriteInteger(int handle, int value, int size=LONG_VALUE) Writes integer value to the binary file. If size is SHORT_VALUE, value will be written as 2 bytes integer, if size is CHAR_VALUE, value will be written as 1 bytes integer and if size is LONG_VALUE, value will be written as 4 bytes integer. Returns actual written bytes count. To get the detailed error information, call GetLastError() function. Parameters handle value size File handle, returned by FileOpen() function. Value to write. Optional format flag. It can be any of the following values: CHAR_VALUE (1 byte), SHORT_VALUE (2 bytes), LONG_VALUE (4 bytes, default). Sample int handle; int value=10; handle=FileOpen("filename.dat", FILE_BIN|FILE_WRITE); if(handle<1) { Print("can't open file error-",GetLastError()); return(0); } FileWriteInteger(handle, value, SHORT_VALUE); //... FileClose(handle); int FileWriteString(int handle, string value, int length) Writes string to the binary file from current file To get the detailed error information, call GetLastError() function. position. Returns actual written bytes count. Parameters handle value length File handle, returned by FileOpen() function. Text to write. Counts of characters to write. Sample int handle; string str="some string"; handle=FileOpen("filename.bin", FILE_BIN|FILE_WRITE); if(handle<1) { Print("can't open file error-",GetLastError()); return(0); } FileWriteString(h1, str, 8); FileClose(handle); Global Variables functions GlobalVariableCheck() GlobalVariableDel() GlobalVariableGet() GlobalVariableSet() GlobalVariableSetOnCondition() GlobalVariablesDeleteAll() bool GlobalVariableCheck(string name) Return logical true if global variable exists, otherwise returns false. To get the detailed error information, call GetLastError() function. Parameters name Global variable name. Sample // check variable before use if(!GlobalVariableCheck("g1")) GlobalVariableSet("g1",1); bool GlobalVariableDel(string name) Deletes global variable. If the function succeeds, the return value will be true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). Parameters name Global variable name. Sample // deleting global variable with name "gvar_1" GlobalVariableDel("gvar_1"); double GlobalVariableGet(string name) Returns global variable value. To check function failure, check error information by calling GetLastError(). Parameters name Global variable name. Sample double v1=GlobalVariableGet("g1"); //---- check function call result if(GetLastError()!=0) return(false); //---- continue processing datetime GlobalVariableSet(string name, double value) Sets global variable value. If it does not exist, the system creates a new variable. If the function succeeds, the return value is last access time. If the function fails, the return value is 0. To get the detailed error information, call GetLastError(). Parameters name value Global variable name. Numeric value to set. Sample //---- try to set new value if(GlobalVariableSet("BarsTotal",Bars)==0) return(false); //---- continue processing bool GlobalVariableSetOnCondition(string name, double value, double check_value) Sets the new value of the global variable if the current value equals to the third parameter check_value. If there is no variable at all, the function will return false and set the value of ERR_GLOBAL_VARIABLE_NOT_FOUND constant to LastError. When successfully executed, the function returns true, otherwise it does false. To receive the information about the error, call GetLastError() function. The function can be used as a semaphore for the access to common resources. Parameters name value check_value Global variable name. Numeric value to set. Value to compare with the current global variable value. Sample int init() { //---- create global variable GlobalVariableSet("DATAFILE_SEM",0); //... } int start() { //---- try to lock common resource while(!IsStopped()) { //---- locking if(GlobalVariableSetOnCondition("DATAFILE_SEM",1,0)==true) break; //---- may be variable deleted? if(GetLastError()==ERR_GLOBAL_VARIABLE_NOT_FOUND) return(0); //---- sleeping Sleep(500); } //---- resource locked // ... do some work //---- unlock resource GlobalVariableSet("DATAFILE_SEM",0); } void GlobalVariablesDeleteAll() Deletes all global variables. This function never fails. Sample GlobalVariablesDeleteAll(); Math & Trig MathAbs() MathArccos() MathArcsin() MathArctan() MathCeil() MathCos() MathExp() MathFloor() MathLog() MathMax() MathMin() MathMod() MathPow() MathRand() MathRound() MathSin() MathSqrt() MathSrand() MathTan() double MathAbs(double value) Returns the absolute value (modulus) of the specified numeric value. Parameters value Numeric value. Sample double dx=-3.141593, dy; // calc MathAbs dy=MathAbs(dx); Print("The absolute value of ",dx," is ",dy); // Output: The absolute value of -3.141593 is 3.141593 double MathArccos(double x) The MathArccos function returns the arccosine of x in the range 0 to π radians. If x is less than -1 or greater than 1, MathArccos returns an indefinite (same as a quiet NaN). Parameters x Value between -1 and 1 arc cosine of which should be calculated. Sample double x=0.32696, y; y=asin(x); Print("Arcsine of ",x," = ",y); y=acos(x); Print("Arccosine of ",x," = ",y); //Output: Arcsine of 0.326960=0.333085 //Output: Arccosine of 0.326960=1.237711 double MathArcsin(double x) The MathArcsin function returns the arcsine of x in the range -π/2 to π/2 radians. If x is less than -1 or greater than 1, arcsine returns an indefinite (same as a quiet NaN). Parameters x Value the arcsine of which should be calculated Sample double x=0.32696, y; y=MathArcsin(x); Print("Arcsine of ",x," = ",y); y=acos(x); Print("Arccosine of ",x," = ",y); //Output: Arcsine of 0.326960=0.333085 //Output: Arccosine of 0.326960=1.237711 double MathArctan(double x) The MathArctan returns the arctangent of x. If x is 0, MathArctan returns 0. MathArctan returns a value in the range -π/2 to π/2 radians. Parameters x A number representing a tangent. Sample double x=-862.42, y; y=MathArctan(x); Print("Arctangent of ",x," is ",y); //Output: Arctangent of -862.42 is -1.5696 double MathCeil(double x) The MathCeil function returns a numeric value representing the smallest integer that is greater than or equal to x. Parameters x Numeric value. Sample double y; /*Output: The floor of 2. y=MathFloor(2. these functions return an indefinite (same as a . MathExp returns 0.y=MathCeil(2. double x. Sample double pi=3. Print("MathCos(".8 is -2*/ double MathCos(double value) Returns the cosine of the specified angle.5708)=0 double MathExp(double d) Returns value the number e raised to the power d.8 is 2 The floor of -2. y=MathExp(x). y=MathSin(x). y.8). If x is negative. //Output: MathSin(1. measured in radians. Print("The floor of -2.8). y=MathCeil(-2.8 is ".y).8 is 3 The ceil of -2. //Output: MathExp(2. y=MathFloor(-2.8 is ". Print("MathSin(".") = ".8 is ".1415926535. Parameters x Numeric value. Sample double y. Print("MathExp(".x. Print("The ceil of 2. the function returns INF (infinite) and on underflow. Parameters d A number specifying a power.302585093.8).y).") = ".x.") = ".8 is -3*/ double MathLog(double x) The MathLog functions return the logarithm of x if successful.y).8). Parameters value An angle.3026)=10 double MathFloor(double x) The MathFloor function returns a numeric value representing the largest integer that is less than or equal to x.8 is ". Sample double x=2.y). Print("The ceil of -2. /*Output: The ceil of 2.y). x=pi/2. y=MathCos(x). On overflow.5708)=1 // MathCos(1.x.y).y.y). Print("The floor of 2. x.0. Parameters base exponent Base value.y. Parameters x Value whose logarithm is to be found. Parameters value value2 Dividend value.quiet NaN). y). Sample double x=9000. y=MathLog(x).z). Divider value. Exponent value. double exponent) Returns the value of a base expression taken to a specified power.y=3. //Output: 2 to the power of 3 is 8 .y=3.Ask)." is ". Sample double x=2. Print("MathLog(".") = ".y). double value2) Divides two numbers and returns only the remainder." / ". //Output: MathLog(9000)=9. Print("The remainder of ". Sample double result=MathMax(1.x. double value2) Returns minimum value of two numeric values.Bid). z=MathPow(x. Sample double x=-10." is ". Parameters value1 value2 First numeric value. Second numeric value. Second numeric value.0. z=MathMod(x.0.0.08. Sample double result=MathMin(1.z. double MathMod(double value.0.z.y. z). Printf(x. double MathMin(double value1. If x is 0.08.y." to the power of ". Parameters value1 value2 First numeric value. they return INF (infinite). double value2) Returns maximum value of two numeric values.10498 double MathMax(double value1.y). //Output: The remainder of -10 / 3 is -1 double MathPow(double base. 1415926535. Parameters value Numeric value to round.5708)=0 double MathSqrt(double x) The MathSqrt function returns the square-root of x.4). use 1 as the seed argument. Sample MathSrand(LocalTime()). //Output: The square root of 45. x=pi/2. //Output: MathSin(1. MathSqrt returns an indefinite (same as a quiet NaN). MathRand retrieves the .8). Print("The round of 2. Any other value for seed sets the generator to a random starting point. Parameters value An angle.4 is ". double MathRound(double value) Returns value rounded to the nearest integer of the specified numeric value.x. Sample double question=45. // Display 10 numbers.5708)=1 // MathCos(1. MathRand()). Sample double pi=3.35. Print("The round of -2. y=MathSin(x). answer). Print("MathSin(". Use the MathSrand function to seed the pseudorandom-number generator before calling rand. Print("MathCos(".8 is 3 // The round of -2. y.73 void MathSrand(int seed) The MathSrand() function sets the starting point for generating a series of pseudorandom integers. Sample double y=MathRound(2.4 is -2 double MathSin(double value) Returns the sine of the specified angle. To reinitialize the generator. answer.answer.question." is ".") = ".y). if(question<0) Print("Error: MathSqrt returns ". for(int i=0.8 is ".y).i<10. measured in radians. y=MathCos(x).int MathRand() The MathRand function returns a pseudorandom integer in the range 0 to 0x7fff (32767).y). If x is negative. y=MathRound(2.") = ". answer=MathSqrt(question).35 is 6.y). else Print("The square root of "." answer"). Parameters x Positive numeric value. double x. //Output: The round of 2.x.i++ ) Print("random value ". in which case the function returns an indefinite (same as a quiet NaN). Note: Coordinates must be passed with both part .i<10. double price1. Sample MathSrand(LocalTime()). MathRand())." = ".i++ ) Print("random value ".7856)=1 Object functions ObjectCreate() ObjectDelete() ObjectDescription() ObjectFind() ObjectGet() ObjectGetFiboDescription() ObjectGetShiftByValue() ObjectGetValueByShift() ObjectGetVisibility() ObjectMove() ObjectName() ObjectsDeleteAll() ObjectSet() ObjectSetFiboDescription() ObjectSetText() ObjectSetVisibility() ObjectsRedraw ObjectsTotal() ObjectType() bool ObjectCreate( string name. Calling MathRand before any call to MathSrand generates the same sequence as calling MathSrand with seed passed as 1. For objects with type OBJ_LABEL first coordinate ignored. call GetLastError(). If the function succeeds. If the function succeeds. x=MathTan(pi/4).pi/4. double price2=0. double price3=0) Create object with specified name. But function wants also the seconds part of coordinate price. type and initial coordinates in the specified window. int type.x). datetime time2=0. the return value will be true. a loss of significance in the result occurs. Parameters seed Seed for random-number generation.pseudorandom numbers that are generated. datetime time3=0. the return value is true. // Display 10 numbers. datetime time1. Count of coordinates related from object type (1-3). Print("MathTan(". For example: Object OBJ_VLINE required 1 coordinate part time. Parameters . for(int i=0.y. double x. int window. //Output: MathTan(0. To get the detailed error information.time and price. Sample double pi=3. Parameters x Angle in radians.1415926535. If the function fails. To set coordinate for label use ObjectSet() function to set OBJPROP_XDISTANCE and OBJPROP_YDISTANCE properties. double MathTan(double x) MathTan returns the tangent of x. or less than or equal to -263. the return value is false. If x is greater than or equal to 263. 0.fname. call GetLastError(). Parameters name Deleting object name. handle=FileOpen(fname. the return value is false.FILE_CSV|FILE_WRITE). if(handle!=false) { total=ObjectsTotal(). bool ObjectDelete(string name) Deletes object with specified name.GetLastError()). return(0).02. OBJ_TEXT. Window index must be greater or equal to 0 and less than WindowsTotal(). 0)) { Print("error: can't create label_object! code #". Sample ObjectDelete("text_object"). string obj_name. Time part of third point. Time part of second point. string ObjectDescription(string name) Return object description. return(0).20 12:30'. 0. 100). Object type.name type window time1 price1 time2 price2 time3 price3 - Unique object name. Window index where object will be added. Sample // writing chart's object list to the file int handle. To get the detailed error information. Parameters name Object name. If the function succeeds. OBJPROP_YDISTANCE. 0."Object "+obj_name+" description= "+ObjectDescription(obj_name)). D'2004. the return value is true. Time part of first point.0045)) { Print("error: can't create text_object! code #". OBJPROP_XDISTANCE. It can be any of the Object type enumeration values. } ObjectSet("label_object". Price part of first point. Price part of third point. for(int i=-. If the function succeeds.GetLastError()). OBJ_LABEL. FileWrite(handle. call GetLastError() function. Sample // new text object if(!ObjectCreate("text_object".i<total. Price part of second point. } . } // new label object if(!ObjectCreate("label_object". ObjectSet("label_object". To get error information. 1. total. If the function fails.i++) { obj_name=ObjectName(i). the return value will be true. 200). // file name fname="objlist_"+Symbol(). . call GetLastError() function.i<32. To get the detailed error information.34). } int ObjectFind(string name) Return object owner's window index. Parameters name index Object name.text).i. OBJPROP_COLOR). Sample color oldColor=ObjectGet("hline12".i). may be objects's level count less than 32 if(GetLastError()!=ERR_NO_ERROR) break.. Applied to trendlines. call GetLastError() function." description: ". double ObjectGetValueByShift(string name. Object property index. call GetLastError() function. Print(MyObjectName. Sample if(ObjectFind("line_object2")!=win_idx) return(0). double ObjectGet(string name. call GetLastError() function. Price value. } int ObjectGetShiftByValue(string name. To get the detailed error information. Applied to trendlines. To check errors. To get the detailed error information. Calculated by first and second coordinate. Parameters name Object name to check. 1. Sample #include <stdlib. double value) Calculates and returns bar index for the indicated price. int index) Function returns description of Fibonacci level. Parameters name index Object name. Sample int shift=ObjectGetShiftByValue("MyTrendLine#123".i++) { text=ObjectGetFiboDescription(MyObjectName. If the function fails. int index) Returns objects property value by index. The amount of Fibonacci levels depends on the object type. Calculated by first and second coordinate. Parameters name value Object name.check.FileClose(handle). string text. call GetLastError() function. The maximum amount of Fibonacci levels never exceeds 32. string ObjectGetFiboDescription(string name. int shift) Calculates and returns price value for the indicated bar. To get the detailed error information. for(int i=0. ."level: ". It can be any of the Object properties enumeration values. Index of the Fibonacci level.mqh> . //---. the return value will be -1. double price1) Moves objects point on the chart. for(int i=0. string ObjectName(int index) Returns object name by index. Parameters window type Window index from objects will be deleted.2345). 1. datetime time1. 1. New price value."Object name is " + name). Sample // is object visible on the chart? if((ObjectGetVisibility()&OBJ_PERIOD_M5)!=0 && Period()==PERIOD_M5) { // working with object } bool ObjectMove(string name. Parameters name Object name. Parameters name point time1 price1 Object name.02. Parameters index Object index on the chart. Sample ObjectMove("MyTrend". int type=EMPTY) Removes all objects with specified type and on the specified subwindow of the chart. Print(i. If the function succeeds. Sample . Window index must be greater or equal to 0 and less than WindowsTotal(). Objects can have from one to three points related to its type. Sample int obj_total=ObjectsTotal().i<obj_total. Value can be single or combined (bitwise addition) of object visibility constants. 11). int ObjectGetVisibility(string name) Function returns flags of the object visibility on the chart. To get the detailed error information.25 12:30'.i++) { name=ObjectName(i). int point. Optional object type to delete. D'2005. New time value. the return value will be true. call GetLastError(). } int ObjectsDeleteAll(int window. the return value will be false. Returns removed objects count. Sample double price=ObjectGetValueByShift("MyTrendLine#123". If the function fails.Parameters name shift Object name Bar index.It can be any of the Object type enumeration values or EMPTY constant to delete all objects with any types. Coordinate index. Object index must be greater or equal to 0 and less than ObjectsTotal(). string name. Sample ObjectSetFiboDescription("MyFiboObject. call GetLastError(). New description to be assigned to the Fibonacci level. the return value will be true. Sample // moving first coord to last bar time ObjectSet("MyTrend". // removes all horizontal line objects from window 3 (index 2). 1. bool ObjectSet(string name. Some text. 10. Green).ObjectsDeleteAll(2. Sample // The object will be shown on 1-hour charts only. If the function fails. call GetLastError() function. "Hello world!". call GetLastError() function. Text color. string text. To get the detailed error information. Parameters name index value Object name. int ObjectSetVisibility(string name. New value of the object visibility property. // setting second fibo level ObjectSet("MyFibo". the return value will be false. the return value will be true. OBJPROP_TIME1. the return value will be false. OBJ_HLINE). int index. Time[0]). Parameters name flag Object name.234). The amount of Fibonacci levels depends on the object type. OBJPROP_TIMEFRAMES. bool ObjectSetText( string name. If the function fails. int font_size. To get the detailed error information."Second line"). Font name. It can be any of Object properties enumeration values. Sample ObjectSetText("text_object". string text) Function assigns a new description to a Fibonacci level. int flag) Function sets new value to the object visibility property. "Times New Roman". Object value index.2. double value) Changes named objects property with new value. If the function succeeds. Parameters name index text Object name. OBJPROP_FIRSTLEVEL+1. Index of the Fibonacci level (0-31). New value for property. bool ObjectSetFiboDescription(string name. string font=NULL. To get the detailed error information. // setting object visibility. Font size in points. OBJ_PERIOD_M15 | OBJ_PERIOD_H1). . object will be shown only on 15 minute and 1 hour charts ObjectSet("MyObject". If the function succeeds. Function returns previous value. Parameters name text font_size font text_color Object name. color text_color=CLR_NONE) Sets object description. int index. Value can be single or combined (bitwise addition) of object visibility constants. The maximum amount of Fibonacci levels never exceeds 32. "My order #2".3. Pre-defined Variables Ask Bars Bid Close Digits High Low Open Point Time Volume double Ask Ask price (the Buyer's price). void ObjectsRedraw() Redraws all objects on the char.ObjectSetVisibility("MyObj1". return.Ask.D'2005.3. if(iRSI(NULL.Red).0)<25) { OrderSend(Symbol().i.i++) { name=ObjectName(i).10. Sample ObjectsRedraw().PRICE_CLOSE. Parameters name Object name." is " + name).OP_BUY."Object name is for object #".OBJ_PERIOD_H1).Ask-StopLoss*Point. int ObjectsTotal() Returns total count of objects on the chart.10 12:30'.0. } . Print(i.Ask+TakeProfit*Point. Sample int obj_total=ObjectsTotal().Lots. Sample if(ObjectType("line_object2")!=OBJ_HLINE) return(0).14. string name. } int ObjectType(string name) Returns Object type enumeration value.i<obj_total. for(int i=0. if(handle>0) { // write table columns headers FileWrite(handle. for(int i=1. "My order #2". Print(DoubleToStr(Close[i-1].Open. FileClose(handle). int counter=1.Red). int handle.10. Volume[i]).FILE_CSV|FILE_WRITE. if(iRSI(NULL.D'2005. "Time. i++) FileWrite(handle. // write data for(int i=0.0)>75) { OrderSend("EURUSD".i++) { Print(Close[i-1]).10 12:30'. Open[i].csv". bars=Bars. handle=FileOpen("file.3. } double Bid Bid price (the Seller's price).Bid+StopLoss*Point.'). Time[i].Lots.Close.OP_SELL.0. } double Close[] Returns the closing price of the bar being referenced.14. High[i]. Close[i].Volume").'.3. i<bars.Low.int Bars Number of bars on the chart. double High[] .High. return(0).i<=Bars. Low[i].Bid-TakeProfit*Point. Digits)). } int Digits Number of digits after decimal point for the current symbol.Bid.PRICE_CLOSE. Close[i]. handle=FileOpen("file. Low[i]. } double Low[] Returns the lowest price of the bar referenced. Open[i].Open. // write data for(int i=0.Volume"). Close[i]. handle=FileOpen("file. i++) FileWrite(handle. .Volume"). FILE_CSV|FILE_WRITE. if(handle>0) { // write table columns headers FileWrite(handle.Close. ". bars=Bars. High[i]. int handle. Volume[i]).Open. "Time.csv".Returns the highest price of the bar referenced. int handle. } double Open[] Returns the opening price of the bar referenced. '.Volume"). i++) FileWrite(handle. Time[i]. // write data for(int i=0. FileClose(handle).'). Time[i]."). i<bars.Close.Low. Open[i]. i<bars. bars=Bars. // write data for(int i=0.Open. "Time. bars=Bars.High.csv". i++) FileWrite(handle. Open[i]. High[i]. FileClose(handle). i<bars. } double Point Point value for the current chart. FileClose(handle).Close.High. Low[i]. Time[i]. handle=FileOpen("file. if(handle>0) { // write table columns headers FileWrite(handle.csv". Volume[i]).High.'). Low[i]. Volume[i]). High[i]. FILE_CSV|FILE_WRITE. "Time. if(handle>0) { // write table columns headers FileWrite(handle. '. int handle. Close[i].Low.Low. FILE_CSV|FILE_WRITE. i++) FileWrite(handle. Low[i]. "Time. "Time. Volume[i]). if(handle>0) { // write table columns headers FileWrite(handle. Close[i]. bars=Bars.OP_BUY. 1970.Ask.Low.Volume"). // erite data for(int i=0. i<bars. Time[i]. handle=FileOpen("file. int handle. Open[i].Ask+TakeProfit*Point. } double Volume[] Returns the ticks count for the referenced bar. FileClose(handle).'). Time[i]. High[i]. datetime Time[] Open time of the bars.OrderSend(Symbol().csv".Red).High. FILE_CSV|FILE_WRITE. Open[i]. i<bars. FileClose(handle). FILE_CSV|FILE_WRITE. // write data for(int i=0. '. } Standard Constants Applied price enumeration Drawing shape style enumeration Error codes Ichimoku Kinko Hyo modes enumeration Indicators line identifiers Market information identifiers MessageBox return codes MessageBox behavior flags Moving Average method enumeration Object properties enumeration Object type enumeration Object visibility enumeration Predefined Arrow codes enumeration Series array identifier Special constants Time frame enumeration Trade operation enumeration .csv". Low[i].Low. Close[i].Close.Close. handle=FileOpen("file.0.Lots.Open. int handle. High[i]. Volume[i]). '. Datetime is the number of seconds elapsed from 00:00 January 1. i++) FileWrite(handle.').Volume").3. bars=Bars. if(handle>0) { // write table columns headers FileWrite(handle.High.Open. No drawing. Valid when width=1. . Description Drawing shape style enumeration Drawing shape style enumeration for SetIndexStyle() function. It can be any of the following values: Constant DRAW_LINE DRAW_SECTION DRAW_HISTOGRAM DRAW_ARROW DRAW_NONE Value 0 1 2 3 12 Value 0 1 2 3 The pen is solid. Typical price. The pen has alternating dashes and dots. It can be any of the Description following values: Constant STYLE_SOLID STYLE_DASH STYLE_DOT STYLE_DASHDOT STYLE_DASHDOTDOT 4 Error codes The GetLastError() function return codes. Open price. Drawing style. The pen is dashed.Uninitialize reason codes Wingdings symbols Web colors table Applied price enumeration Applied price constants. Error code constants defined at stderror. It can be any of the following values: Constant PRICE_CLOSE PRICE_OPEN PRICE_HIGH PRICE_LOW PRICE_MEDIAN PRICE_TYPICAL PRICE_WEIGHTED Value 0 1 2 3 4 5 6 Close price. Description Drawing line.mqh file. Drawing arrows (symbols).ErrorDescription(check)). check=GetLastError(). text).mqh file. The pen has alternating dashes and double dots. High price. Drawing histogram. To print text messages use ErrorDescription() function defined at stdlib. #include <stdlib. } Error codes returned from trade server. (high+low)/2. The pen is dotted. if(check!=ERR_NO_MQLERROR) Print("Cannot send message. Low price.mqh> void SendMyMessage(string text) { int check. SendMail("some subject". (high+low+close+close)/4. Weighted close price. (high+low+close)/3. error: ". Drawing sections. Median price. Market is closed. Invalid trade parameters. Invalid account. Malfunctional trade operation. Trade timeout. Invalid stops. Not enough rights. Not enough money. Trade server is busy. Too frequent requests. Trade is disabled. Old version of the client terminal. Off quotes. but the result is unknown. Modification denied because order too close to market. Description No error returned. Invalid trade volume. Order is locked. Common error.Constant ERR_NO_ERROR ERR_NO_RESULT ERR_COMMON_ERROR ERR_INVALID_TRADE_PARAMETERS ERR_SERVER_BUSY ERR_OLD_VERSION ERR_NO_CONNECTION ERR_NOT_ENOUGH_RIGHTS ERR_TOO_FREQUENT_REQUESTS ERR_MALFUNCTIONAL_TRADE ERR_ACCOUNT_DISABLED ERR_INVALID_ACCOUNT ERR_TRADE_TIMEOUT ERR_INVALID_PRICE ERR_INVALID_STOPS ERR_INVALID_TRADE_VOLUME ERR_MARKET_CLOSED ERR_TRADE_DISABLED ERR_NOT_ENOUGH_MONEY ERR_PRICE_CHANGED ERR_OFF_QUOTES ERR_BROKER_BUSY ERR_REQUOTE ERR_ORDER_LOCKED Value 0 1 2 3 4 5 6 7 8 9 64 65 128 129 130 131 132 133 134 135 136 137 138 139 No error returned. Long positions only allowed. ERR_LONG_POSITIONS_ONLY_ALLOWED 140 ERR_TOO_MANY_REQUESTS ERR_TRADE_MODIFY_DENIED ERR_TRADE_CONTEXT_BUSY 141 145 146 MQL4 run time error codes . Too many requests. Account disabled. Invalid price. Price changed. Broker is busy. Trade context is busy. Requote. No connection with trade server. Custom indicator error. Incorrect series array using. Wrong jump (never generated error). Some array error. Arrays are incompatible. Not initialized array. Cannot load library. Too long string. DLL calls are not allowed. Requested history data in updating state. No memory for array string. ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING 4021 ERR_SYSTEM_BUSY ERR_INVALID_FUNCTION_PARAMETERS_COUNT ERR_INVALID_FUNCTION_PARAMETER_VALUE ERR_STRING_FUNCTION_INTERNAL_ERROR ERR_SOME_ARRAY_ERROR ERR_INCORRECT_SERIES_ARRAY_USING ERR_CUSTOM_INDICATOR_ERROR ERR_INCOMPATIBLE_ARRAYS ERR_GLOBAL_VARIABLES_PROCESSING_ERROR ERR_GLOBAL_VARIABLE_NOT_FOUND ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE ERR_FUNCTION_NOT_CONFIRMED ERR_SEND_MAIL_ERROR ERR_STRING_PARAMETER_EXPECTED ERR_INTEGER_PARAMETER_EXPECTED ERR_DOUBLE_PARAMETER_EXPECTED ERR_ARRAY_AS_PARAMETER_EXPECTED ERR_HISTORY_WILL_UPDATED ERR_END_OF_FILE ERR_SOME_FILE_ERROR ERR_WRONG_FILE_NAME ERR_TOO_MANY_OPENED_FILES ERR_CANNOT_OPEN_FILE 4022 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4099 4100 4101 4102 4103 . Send mail error. Invalid function parameter value. No memory for parameter string. Double parameter expected. Not initialized string in array. String function internal error. Cannot open file. String parameter expected. Not enough memory for temp string returned from function.Constant ERR_NO_MQLERROR ERR_WRONG_FUNCTION_POINTER ERR_ARRAY_INDEX_OUT_OF_RANGE ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK ERR_RECURSIVE_STACK_OVERFLOW ERR_NOT_ENOUGH_STACK_FOR_PARAMETER ERR_NO_MEMORY_FOR_PARAMETER_STRING ERR_NO_MEMORY_FOR_TEMP_STRING ERR_NOT_INITIALIZED_STRING ERR_NOT_INITIALIZED_ARRAYSTRING ERR_NO_MEMORY_FOR_ARRAYSTRING ERR_TOO_LONG_STRING ERR_REMAINDER_FROM_ZERO_DIVIDE ERR_ZERO_DIVIDE ERR_UNKNOWN_COMMAND ERR_WRONG_JUMP ERR_NOT_INITIALIZED_ARRAY ERR_DLL_CALLS_NOT_ALLOWED ERR_CANNOT_LOAD_LIBRARY ERR_CANNOT_CALL_FUNCTION ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED Value 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 No error. Not enough stack for parameter. Zero divide. Integer parameter expected. No memory for temp string. Array index is out of range. Too many opened files. Invalid function parameters count. Cannot call function. Some file error. System is busy (never generated error). Unknown command. Global variables processing error. No memory for function call stack. Function is not confirmed. Function is not allowed in testing mode. Recursive stack overflow. Remainder from zero divide. Expert function calls are not allowed. Wrong file name. End of file. Description Wrong function pointer. Array as parameter expected. Global variable not found. Not initialized string. Indicator line identifiers used in iADX() indicator. Market information identifiers Market information identifiers. MODE_SENKOUSPANA 3 MODE_SENKOUSPANB 4 MODE_CHINKOUSPAN 5 Indicators line identifiers Indicator line identifiers used It can be one of the following values: Constant MODE_MAIN MODE_SIGNAL Constant MODE_MAIN MODE_PLUSDI MODE_MINUSDI Constant MODE_UPPER MODE_LOWER Value 0 1 Value 0 1 2 Description Base indicator line. +DI indicator line. Kijun-sen. Signal line. Senkou Span A. Indicator iEnvelopesOnArray(). Value 1 2 Description Upper line. Used in iIchimoku() indicators. Lower line. iEnvelopes(). Description Base indicator line. Senkou Span B. line identifiers used in iBands(). Chinkou Span. . iRVI() and iStochastic() indicators. It can be any of the following values: used with MarketInfo() function. in iMACD(). iFractals() and iGator() indicators. -DI indicator line.Ichimoku Kinko Hyo modes enumeration Ichimoku Kinko Hyo source It can be one of the following values: Constant MODE_TENKANSEN MODE_KIJUNSEN Value 1 2 Description Tenkan-sen. of data. Last incoming ask price. Note: MessageBox return codes defined in the WinUser32.Constant MODE_LOW MODE_HIGH MODE_TIME MODE_BID MODE_ASK MODE_POINT MODE_DIGITS MODE_SPREAD MODE_STOPLEVEL MODE_LOTSIZE MODE_TICKVALUE MODE_TICKSIZE MODE_SWAPLONG MODE_SWAPSHORT MODE_STARTING MODE_EXPIRATION Value 1 2 5 9 10 11 12 13 14 15 16 17 18 19 20 21 Low day price. If the message box has no Cancel button. Description The last incoming quotation time. Last incoming bid price. No button was selected. Trade is allowed for the symbol. the function returns the IDCANCEL value if either the ESC key is pressed or the Cancel button is selected. Cancel button was selected. If a message box has a Cancel button. Note: MessageBox return codes defined in the WinUser32. Spread value in points. specify one of the following values. Try Again button was selected. Continue button was selected.mqh file Constant IDOK IDCANCEL IDABORT IDRETRY IDIGNORE IDYES IDNO IDTRYAGAIN IDCONTINUE Value 1 2 3 4 5 6 7 10 11 Description OK button was selected. The minimum lot size in points. Ignore button was selected. Market starting date (usually used for future markets). Tick value. . Yes button was selected. Stop level in points. Retry button was selected. Abort button was selected. Step for changing lots in points. Swap of the short position. Point size.mqh file To indicate the buttons displayed in the message box. Swap of the long position. Lot size in the base currency. pressing ESC has no effect. High day price. This value can be a combination of flags from the following groups of flags. MODE_TRADEALLOWED 22 MODE_MINLOT MODE_LOTSTEP 22 22 MessageBox return codes The MessageBox() function return codes. Digits after decimal point. Tick size. MessageBox behavior flags The MessageBox function flags specify the contents and behavior of the dialog box. Market expiration date (usually used for future markets). MB_ICONASTERISK 0x00000020 A question-mark icon appears in the message box. Object properties enumeration Object value index used with ObjectGet() and ObjectSet() functions. iStdDev(). It can be any of the following values: Constant MODE_SMA MODE_EMA MODE_SMMA MODE_LWMA Value 0 1 2 3 Description Simple moving average. iMAOnArray(). and Ignore. No. Use this message box type instead of MB_ABORTRETRYIGNORE. specify one of the following values. MB_ICONQUESTION MB_ICONEXCLAMATION. Windows 2000: The message box contains three push buttons: Cancel. MB_DEFBUTTON3. iEnvelopesOnArray. MB_ICONWARNING MB_ICONINFORMATION. Exponential moving average. used with iAlligator(). MB_ICONERROR. 0x00000001 The message box contains two push buttons: OK and Cancel. MB_DEFBUTTON1 is the default unless MB_DEFBUTTON2. iForce(). To indicate the default button. 0x00000100 The second button is the default button. 0x00000003 The message box contains three push buttons: Yes. MB_CANCELTRYCONTINUE 0x00000006 To display an icon in the message box. 0x00000002 The message box contains three push buttons: Abort. Linear weighted moving average. Constant Value Description MB_ICONSTOP. 0x00000200 The third button is the default button. MB_ICONHAND 0x00000010 A stop-sign icon appears in the message box. This is the default. 0x00000030 An exclamation-point icon appears in the message box. iEnvelopes(). iGator(). 0x00000300 The fourth button is the default button.Constant MB_OK MB_OKCANCEL MB_ABORTRETRYIGNORE MB_YESNOCANCEL MB_YESNO MB_RETRYCANCEL Value Description 0x00000000 The message box contains one push button: OK. It can be any of the following values: . or MB_DEFBUTTON4 is specified. Continue. Moving Average method enumeration Moving Average calculation method. iStdDevOnArray(). iMA(). specify one of the following values. Retry. 0x00000040 An icon consisting of a lowercase letter i in a circle appears in the message box. iStochastic() indicators. 0x00000004 The message box contains two push buttons: Yes and No. 0x00000005 The message box contains two push buttons: Retry and Cancel. Constant MB_DEFBUTTON1 MB_DEFBUTTON2 MB_DEFBUTTON3 MB_DEFBUTTON4 Value 0x00000000 Description The first button is the default button. and Cancel. Try Again. Smoothed moving average. . Double value to set/get third coordinate price part. Datetime value to set/get second coordinate time part. Datetime value to set/get third coordinate time part. Double value to set/get scale object property. Can be from 0 to 32. ObjectsDeleteAll() and ObjectType() functions. STYLE_DASHDOT. Can be from 0 to 31. Value can be one or combination (bitwise addition) of object visibility constants to set/get timeframe object property. Integer value to set/get object line width. Integer value or arrow enumeration to set/get arrow code object property. Double value to set/get deviation property for Standard deviation objects. Object type enumeration Object type identifier constants used with ObjectCreate().Constant OBJPROP_TIME1 OBJPROP_PRICE1 OBJPROP_TIME2 OBJPROP_PRICE2 OBJPROP_TIME3 OBJPROP_PRICE3 OBJPROP_COLOR OBJPROP_STYLE OBJPROP_WIDTH OBJPROP_BACK OBJPROP_RAY OBJPROP_ELLIPSE OBJPROP_SCALE OBJPROP_ANGLE OBJPROP_ARROWCODE OBJPROP_TIMEFRAMES OBJPROP_DEVIATION OBJPROP_FONTSIZE OBJPROP_CORNER OBJPROP_XDISTANCE OBJPROP_YDISTANCE OBJPROP_FIBOLEVELS OBJPROP_FIRSTLEVEL+n Value 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 100 101 102 103 200 210 Description Datetime value to set/get first coordinate time part. Integer value to set/get font size for text objects. Color value to set/get object color. Must be from 0-3. Fibonacci object level index. Integer value to set/get anchor corner property for label objects. Value is one of STYLE_SOLID. Double value to set/get second coordinate price part. where n is level index to set/get. It can be any of the following values: Objects can have 1-3 coordinates related to type. Can be from 1 to 5. STYLE_DASH. Integer value is to set/get anchor Y distance object property in pixels. Boolean value to set/get background drawing flag for object. Double value to set/get first coordinate price part. Boolean value to set/get ellipse flag for fibo arcs. STYLE_DOT. Boolean value to set/get ray flag of object. STYLE_DASHDOTDOT constants to set/get object line style. Double value to set/get angle object property in degrees. Integer value to set/get anchor X distance object property in pixels. Integer value to set/get Fibonacci object level count. Object visibility enumeration Time frames where object may be shown. Uses 3 coordinates. Uses 3 coordinates. Ellipse. Uses 1 coordinate. Channel. Hidden object on all timeframes. Uses 3 coordinates. Uses 2 coordinates. Object shown is only on 30-minute charts. Trend line. Object shown is only on 1-hour charts. To set angle of line use ObjectSet() function. Trend by angle. Gann line. Uses time part of first coordinate. Constant OBJ_PERIOD_M1 OBJ_PERIOD_M5 OBJ_PERIOD_M15 OBJ_PERIOD_M30 OBJ_PERIOD_H1 OBJ_PERIOD_H4 OBJ_PERIOD_D1 OBJ_PERIOD_W1 OBJ_PERIOD_MN1 OBJ_ALL_PERIODS NULL EMPTY Value 0x0001 0x0002 0x0004 0x0008 0x0010 0x0020 0x0040 0x0080 0x0100 0x01FF 0 -1 Description Object shown is only on 1-minute charts. Triangle. Cycles. Arrows code constants. It can be one of the following values: . Object shown is only on 5-minute charts. Gann fan. Arrows. Uses 1 coordinate. Object shown is only on 4-hour charts. Uses time parts of first two coordinates. Fibonacci arcs. Uses 2 coordinates. Uses 2 coordinates. Fibonacci expansions. Object shown is only on 15-minute charts. Text label. Gann grid.Constant OBJ_VLINE OBJ_HLINE OBJ_TREND OBJ_TRENDBYANGLE OBJ_REGRESSION OBJ_CHANNEL OBJ_STDDEVCHANNEL OBJ_GANNLINE OBJ_GANNFAN OBJ_GANNGRID OBJ_FIBO OBJ_FIBOTIMES OBJ_FIBOFAN OBJ_FIBOARC OBJ_EXPANSION OBJ_FIBOCHANNEL OBJ_RECTANGLE OBJ_TRIANGLE OBJ_ELLIPSE OBJ_PITCHFORK OBJ_CYCLES OBJ_TEXT OBJ_ARROW OBJ_LABEL Value 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Description Vertical line. Uses 1 coordinate. Uses 2 coordinates. Uses 2 coordinates. Text. Uses 1 coordinate in pixels. Uses 3 coordinates. Uses 2 coordinates. Object shown is on all timeframes. Fibonacci retracement. Object shown is only on daily charts. Uses 2 coordinates. Uses price part of first coordinate. Rectangle. Object shown is on all timeframes. Uses 3 coordinates. Regression. but price part of second coordinate ignored. Uses 2 coordinate. Andrews pitchfork. but price part of second coordinate ignored. Predefined Arrow codes enumeration Predefined Arrow codes enumeration. Uses 2 coordinate. Standard deviation channel. Uses time parts of first two coordinates. Used in ObjectSet() function to set OBJPROP_TIMEFRAMES property. Fibonacci channel. Uses 2 coordinate. Object shown is only on monthly charts. Uses 2 coordinates. Fibonacci fan. but price part of second coordinate ignored. Horizontal line. Fibonacci time zones. Object shown is only on weekly charts. Description Highest() and Lowest() functions. Arrow down symbol (). Stop sign symbol (). Low price. Special constants Special constants used to indicate parameters and variables states. Series array identifier Series array identifier used It can be any of the following values: Constant MODE_OPEN MODE_LOW MODE_HIGH MODE_CLOSE MODE_VOLUME MODE_TIME Value 0 1 2 3 4 5 Open price. used in Lowest() and Highest() functions. Left sided price label. Right sided price label. used in ArrayCopySeries() function. 0xFFFFFFFF Indicates empty state of colors.Constant SYMBOL_THUMBSUP SYMBOL_THUMBSDOWN SYMBOL_ARROWUP SYMBOL_ARROWDOWN SYMBOL_STOPSIGN SYMBOL_CHECKSIGN Value 67 68 241 242 251 252 Description Thumb up symbol (). Left pointing triangle (◄). Downwards arrow with tip rightwards (↳). En Dash symbol (–). Indicates that all array elements will be processed. 0 Used with array functions. 0x7FFFFFFF Default custom indicator empty value. Special Arrow codes that exactly points to price and time. with ArrayCopySeries(). It can be one of the following values: Constant NULL EMPTY EMPTY_VALUE CLR_NONE WHOLE_ARRAY 0 -1 value Description Indicates empty state of the string. High price. Arrow up symbol (). Close price. Time frame enumeration Time frame on the chart. Indicates empty state of the parameter. It can be one of the following values: Constant Value 1 2 3 4 SYMBOL_LEFTPRICE SYMBOL_RIGHTPRICE 5 6 Description Upwards arrow with tip rightwards (↱). It can be any of the following values: . Check sign symbol (). Thumb down symbol (). Bar open time. Volume. Time frame used on the chart. 30 minutes. 15 minutes. Other account activated. Weekly. Sell limit pending position. Buy limit pending position. Daily. Monthly. 15 30 60 240 1440 10080 43200 0 Trade operation enumeration Operation type for the OrderSend() function. It can be any one of the following values: Constant REASON_REMOVE REASON_RECOMPILE 1 2 Value Description Expert removed from chart. . 1 hour. It can be any of the following values: Constant OP_BUY OP_SELL OP_BUYLIMIT OP_SELLLIMIT OP_BUYSTOP OP_SELLSTOP 0 1 2 3 4 5 Value Description Buying position. Buy stop pending position.Constant PERIOD_M1 PERIOD_M5 PERIOD_M15 PERIOD_M30 PERIOD_H1 PERIOD_H4 PERIOD_D1 PERIOD_W1 PERIOD_MN1 0 (zero) 1 5 Value Description 1 minute. 5 minutes. symbol or timeframe changed on the chart. Uninitialize reason codes Uninitialize reason codes returned by UninitializeReason() function. 4 hour. REASON_CHARTCHANGE 3 REASON_CHARTCLOSE REASON_PARAMETERS REASON_ACCOUNT 4 5 6 Wingdings symbols Wingdings font symbols used with Arrow objects. Sell stop pending position. Chart closed. Inputs parameters was changed by user. Expert recompiled. Selling position. Arrays cannot be passed to the StringConcatenate() function.32  48  64  80        96 11 2 12 8 14 4 16 0 17 6 19 2  33  49  65  81    ‘    97 11 3 12 9 14 5 16 1 17 7 19 3 20 9 22 5 24 1  34  50  66  82    ’       98 11 4 13 0 14 6 16 2 17 8 19 4 21 0 22 6 24 2  35  51  67  83    “       99 11 5 13 1 14 7 16 3 17 9 19 5 21 1 22 7 24 3  36  52  68  84    ”       10 0 11 6 13 2 14 8 16 4 18 0 19 6 21 2 22 8 24 4       …     37 53 69 85 10 1 11 7 13 3 14 9 16 5 18 1 19 7  38  54  70  86    –    10 2 11 8 13 4 15 0 16 6 18 2 19 8  39  55  71  87  10 3   —   11 9 13 5 15 1 16 7 18 3  40  56  72  88  10 4  41  57  73  89  10 5  42  58  74  90  10 6 12 2 13 8 15 4 17 0 18 6          43 59 75 91  44  60  76  92 10 8 12 4 14 0 15 6 17 2 18 8 20 4 22 0 23 6 25 2  45  61  77  93     10 9 12 5 14 1 15 7  46  62  78  94     11 0 12 6 14 2 15 8 17 4 19 0 20 6 22 2 23 8 25 4  47  63  79  95           11 1 12 7 14 3 15 9 17 5 19 1 20 7 22 3 23 9 25 5  10  7 12 3 13 9 15 5 17 1 18 7 20 3 21 9 23 5 25 1  12  12  0 1  13 6          ‰13  7   16 9 18 5  15  15  2 3   16 8 18 4   . datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. Arrays should be printed elementwise. To print with more precision use DoubleToStr() function. Parameters can be of any type. See also: Print(). Data of double type printed with 4 decimal digits after point. Alert() and Comment() functions. StringConcatenate() function work faster than concatenating strings by + operator.. . ) Writes data to the string and returns it. Data of bool..17  3      18 9 20 5 22 1 23 7 25 3       19  20  20  20  9 0 1 2 21 5  20  8   22 4 24 0  21  21  3 4   22 9 24 5  21 6  21 7 23 3 24 9    21 8 23 4 25 0        23 0 24 6  23  23  1 2  24 7  24 8  Web colors table Black Maroon SeaGreen LightSeaGreen Goldenrod DarkOrange DeepSkyBlue LightSlateGray IndianRed MediumPurple DarkSalmon Plum PaleGreen Moccasin LemonChiffon Lavender LavenderBlush DarkGreen Indigo DarkGoldenrod DarkViolet MediumSpringGreen Orange Blue DeepPink MediumOrchid PaleVioletRed BurlyWood Khaki Thistle LightPink Beige MistyRose MintCream DarkSlateGray MidnightBlue DarkSlateBlue FireBrick LawnGreen Gold Magenta MediumTurquoise GreenYellow Coral HotPink LightGreen PowderBlue Gainsboro AntiqueWhite OldLace Snow Olive DarkBlue Sienna MediumVioletRed CadetBlue Yellow Red DodgerBlue MediumAquamarine CornflowerBlue Salmon Aquamarine PaleGoldenrod PeachPuff PapayaWhip WhiteSmoke White Green DarkOliveGreen MediumBlue MediumSeaGreen DarkOrchid Chartreuse Gray Turquoise DarkSeaGreen DarkGray Violet Silver PaleTurquoise Pink Cornsilk Seashell Teal SaddleBrown Brown Chocolate YellowGreen Lime SlateGray RoyalBlue Tomato LightCoral LightSkyBlue LightGray Bisque LightYellow Ivory Navy ForestGreen DarkTurquoise Crimson LimeGreen SpringGreen Peru SlateBlue RosyBrown SkyBlue LightSteelBlue Wheat LightCyan Honeydew Purple OliveDrab DimGray SteelBlue OrangeRed Aqua BlueViolet DarkKhaki Orchid Tan LightSalmon LightBlue NavajoWhite Linen AliceBlue SandyBrown MediumSlateBlue LightGoldenRod BlanchedAlmond String functions StringConcatenate() StringFind() StringGetChar() StringLen() StringSetChar() StringSubstr() StringTrimLeft() StringTrimRight() string StringConcatenate(. Char zero based position in the string. if(index!=16) Print("oops!"). Sample string str="some text". Parameters text pos value String where character will be changed. int start=0) Scans this string for the first match of a substring.. Parameters text String to calculate length. string StringSetChar(string text.Parameters . TimeToStr(CurTime())). Parameters text matched_text start String to search for. // slow text="Account free margin is " + AccountFreeMargin() + "Current time is " + TimeToStr(CurTime()) Print(text). Sample string text. Parameters text pos String where character will be retrieved. int StringGetChar(string text. Any values. String to search for. Sample int char_code=StringGetChar("abcdefgh". 3). "Current time is ". int value) Returns string copy with changed character at the indicated position with new value. Sample string text="The quick brown dog jumps over the lazy fox". separated by commas. 3. 0). Sample string str="abcdefgh". int StringFind(string text. New char ASCII code. Starting index in the string. // str1 is "abcDefgh" . "dog jumps". text=StringConcatenate("Account free margin is ". int pos) Returns character (code) from specified position in the string. Zero based character position in the string. // char code 'c' is 99 int StringLen(string text) Returns character count of a string. Can be from 0 to StringLen()-1.. AccountFreeMargin(). int index=StringFind(text. if(StringLen(str)<5) return(0). 'D'). string matched_text. int pos. string str1=StringSetChar(str. StringTrimLeft removes new line. int start. Sample string str1=" Hello world ". Parameters text String to trim left. string str2=StringTrimRight(str). The function returns a copy of the trimmed string if possible. StringTrimRight removes new line. and tab characters. // after trimming the str2 variable will be "Hello World " string StringTrimRight(string text) Call the function to trim leading white space characters from the string.iBearsPower() Bollinger Bands . starting at The function returns a copy of the extracted substring if possible.iBandsOnArray() Bulls Power .iAD() Alligator .iBullsPower() Commodity Channel Index .iAC() Accumulation/Distribution . space.iAO() Bears Power .iForce() . Returns new string with changes. position (zero-based).iEnvelopes() Envelopes on buffer .string StringSubstr(string text. space. 5). Substring starting index Character count.iADX() Average True Range . otherwise returns empty string.iCustom() DeMarker . Sample string text="The quick brown dog jumps over the lazy fox". Sample string str1=" Hello world ".iCCI() Commodity Channel Index on buffer . int count=EMPTY) Extracts a substring from text string.iDeMarker() Envelopes .iATR() Awesome Oscillator . otherwise returns empty string.iEnvelopesOnArray() Force Index . Parameters text String to trim right. string substr=StringSubstr(text.iBands() Bollinger Bands on buffer . string str2=StringTrimLeft(str). Parameters text start count String from substring will be extracted. otherwise return empty string. // subtracted string is "quick" word string StringTrimLeft(string text) Call the function to trim leading white space characters from the string. The function returns a copy of the trimmed string if possible. and tab characters. 4. // after trimming the str2 variable will be " Hello World" Technical Indicator calls Accelerator Oscillator .iAlligator() Average Directional Movement Index .iCCIOnArray() Custom Indicator . iRVI() Standard Deviation .iMA() Moving Average on buffer . Parameters .iOsMA() Moving Averages Convergence/Divergence . int timeframe.iGator() Ichimoku Kinko Hyo .Fractals . double iAD(string symbol.iMACD() On Balance Volume . 1). int timeframe. double iAlligator( string symbol. int lips_period.iMomentum() Momentum on buffer . 1). int shift) Calculates the Bill Williams' Alligator and returns its value.iFractals() Gator Oscillator . Shift relative to the current bar (number of periods back).iRSI() Relative Strength Index on buffer .iStdDevOnArray() Stochastic Oscillator .iMAOnArray() Moving Average of Oscillator . int ma_method. int mode. It can be any of Time frame enumeration values. int jaw_period. Shift relative to the current bar (number of periods back). int lips_shift. Parameters symbol timeframe shift Symbol the data of which should be used to calculate indicator.iOBV() Parabolic SAR . NULL means the current symbol. where the data should be taken from. NULL means the current symbol. Time frame. Sample double result=iAD(NULL.iWPR() iBars() iBarShift() iClose() iHigh() iLow() iOpen() iTime() iVolume() Highest() Lowest() double iAC(string symbol. Sample double result=iAC(NULL. int shift) Calculates the Accumulation/Distribution indicator and returns its value.iBWMFI() Momentum . int teeth_shift. Time frame. int timeframe.iStdDev() Standard Deviation on buffer . int teeth_period.iMomentumOnArray() Money Flow Index . int shift) Calculates the Bill Williams' Accelerator/Decelerator oscillator and returns its value. It can be any of Time frame enumeration values. 0.iStochastic() William's Percent Range .iMFI() Moving Average . 0. Parameters symbol timeframe shift Symbol the data of which should be used to calculate indicator. int jaw_shift.iSAR() Relative Strength Index . int applied_price. where the data should be taken from.iIchimoku() Market Facilitation Index (Bill Williams) .iRSIOnArray() Relative Vigor Index . int timeframe.14. 5. where the data should be taken from. 1). It can be any of Time frame enumeration values. Parameters symbol timeframe shift Symbol the data of which should be used to calculate indicator. 13.0. Source of data. int mode. Jaw period. Number of periods for calculation. Jaw line shift. Time frame. Shift relative to the current bar (number of periods back). It can be any of Time frame enumeration values.0)) return(0). MODE_GATORJAW. NULL means the current symbol. int shift) Calculates the Indicator of the average true range and returns its value. PRICE_MEDIAN. int shift) Calculates the Bill Williams' Awesome oscillator and returns its value. NULL means the current symbol. Shift relative to the current bar (number of periods back). 0.0)) return(0). int period.0)>iATR(NULL. It can be any of the Indicators line identifiers enumeration value. int timeframe. 8. 3. . It can be any of Applied price enumeration values. double iADX( Parameters symbol timeframe period string symbol. 5.20. MODE_SMMA. Teeth period.MODE_MAIN.PRICE_HIGH. int timeframe.12. It can be any of the following values: MODE_GATORJAW . Parameters symbol timeframe period shift Symbol the data of which should be used to calculate indicator. int shift) Calculates the Movement directional index and returns its value. Applied price. 2).symbol timeframe jaw_period jaw_shift teeth_period teeth_shift lips_period lips_shift ma_method applied_price mode - Symbol the data of which should be used to calculate indicator. MODE_GATORTEETH . double iATR(string symbol. MODE_GATORLIPS . where the data should be taken from. MA method. 0.0.0.14. int period. int applied_price. Time frame. 8. NULL means the current symbol. applied_price mode shift Sample if(iADX(NULL. Lips period. NULL means the current symbol.PRICE_HIGH. where the data should be taken from. double iAO(string symbol. It can be any of Time frame enumeration values. shift - Sample double jaw_val=iAlligator(NULl. Time frame.MODE_PLUSDI. It can be any of Applied price enumeration values. Indicator line array index. Time frame. Number of periods for calculation.Gator Teeth (red) balance line.Gator Lips (green) balance line. where the data should be taken from. It can be any of Time frame enumeration values.0. Sample double val=iAO(NULL. Teeth line shift. Applied price.0)>iADX(NULL. Symbol the data of which should be used to calculate indicator. Shift relative to the current bar (number of periods back).Gator Jaw (blue) balance line. It can be any of Moving Average method enumeration value. Sample if(iATR(NULL. Lips line shift. Shift relative to the current bar (number of periods back). int shift) Calculates the Bollinger bands indicator and returns its value. It can be any of Applied price enumeration values. Sample if(iBands(NULL. Series array identifier. double iBands( string symbol.0)>Low[0]) return(0). NULL means the current symbol. Array with data. Number of periods for calculation. Symbol the data of which should be used to calculate indicator. where the data should be taken from.PRICE_LOW. It can be any of Applied price enumeration values. int shift) Calculates the Bollinger bands indicator and returns its value. It can be any of Applied price enumeration values. int period.0)>Low[0]) return(0). int applied_price. int shift) Calculates the Bulls Power indicator and returns its value. int total. Parameters symbol timeframe period deviation bands_shift applied_price mode shift Symbol the data of which should be used to calculate indicator. 13. Shift relative to the current bar (number of periods back). NULL means the current symbol. where the data should be taken from. Indicator line array index.2. NULL means the current symbol. double iBandsOnArray( Parameters array[] total period deviation bands_shift mode shift - double array[]. Time frame. Shift relative to the current bar (number of periods back). . Applied price. 0. Applied price. double deviation. The number of items to be counted.0. It can be any of Time frame enumeration values. int timeframe. 0. int mode. int mode. Time frame. Symbol the data of which should be used to calculate indicator. double iBullsPower( Parameters symbol timeframe period applied_price shift - string symbol. int period. Sample if(iBands(ExtBuffer. int period. Deviation.PRICE_CLOSE. Deviation.total.PRICE_CLOSE.0. int timeframe. Number of periods for calculation.0).0). where the data should be taken from. Applied price. where the data should be taken from. Bands shift.double iBearsPower( Parameters symbol timeframe period applied_price shift - string symbol. Time frame. Number of periods for calculation. int applied_price. It can be any of the Indicators line identifiers enumeration value. int deviation.0. Sample double val=iBullsPower(NULL. int timeframe. int bands_shift. Sample double val=iBearsPower(NULL. Bands shift. int shift) Calculates the Bears Power indicator and returns its value. Shift relative to the current bar (number of periods back).MODE_LOWER.MODE_LOWER.2. 13. It can be any of Time frame enumeration values. It can be any of the Series array identifier enumeration values. Shift relative to the current bar (number of periods back).20. int bands_shift. int applied_price. int period. It can be any of Time frame enumeration values. Number of periods for calculation. where the data should be taken from. . Time frame.0. Sample double val=iDeMarker(NULL. Time frame. int shift) Calculates the Commodity channel index and returns its value. int timeframe. Time frame.. double iCustom(string symbol. where the data should be taken from. int mode.double iCCI(string symbol. Parameters symbol timeframe name . "SampleInd".20.1. int shift) Calculates the Commodity channel index and returns its value. int ma_period. .PRICE_OPEN. string name. where the data should be taken from. Shift relative to the current bar (number of periods back). It can be any of Time frame enumeration values. int shift) Calculates the Custom indicator and returns its value. 0. .total. double deviation.. 0. Line index. Shift relative to the current bar (number of periods back).. Parameters symbol timeframe period shift Symbol the data of which should be used to calculate indicator. It can be any of Time frame enumeration values. Can be from 0 to 7.0. int timeframe. int shift) Calculates the DeMarker indicator and returns its value. int mode.0)>iCCI(NULL. double iDeMarker(string symbol. Custom indicator compiled program name.12. The number of items to be counted. int applied_price.0. int timeframe. Sample double val=iCustom(NULL. Sample if(iCCIOnArray(ExtBuffer. NULL means current symbol. 1). int shift) Calculates the Envelopes indicator and returns its value. int timeframe. int ma_method. Parameters array[] total period shift Array with data.13. Shift relative to the current bar (number of periods back). Applied price. NULL means the current symbol. double iCCIOnArray(double array[]. NULL means the current symbol. where the data should be taken from. int period. int period. Number of periods for calculation.0)>iCCI(NULL. 13.20.0)) return(0). mode shift Symbol the data of which should be used to calculate indicator. It can be any of Time frame enumeration values. int applied_price. int ma_shift.. Shift relative to the current bar (number of periods back). Parameters set (if needed). Number of periods for calculation. 0)) return(0). Number of periods for calculation. Sample if(iCCI(NULL. double iEnvelopes( Parameters string symbol. int total.0). Parameters symbol timeframe period applied_price shift Symbol the data of which should be used to calculate indicator. int period.12. It can be any of Applied price enumeration values. int timeframe. Applied price. Number of periods for calculation. int ma_period. int shift) Calculates the Envelopes indicator counted on buffer and returns its value.PRICE_CLOSE. double array[].symbol timeframe ma_period ma_method ma_shift applied_price deviation mode shift - Symbol the data of which should be used to calculate indicator. MA shift. MODE_SMA. 13. MA method. Indicator line array index. double iEnvelopesOnArray( Parameters array[] total ma_period ma_method ma_shift deviation mode shift Array with data. int mode. It can be any of Moving Average method enumeration value. The number of items to be counted. int shift) Calculates the Force index and returns its value. double deviation. Sample double val=iEnvelopes(NULL. where the data should be taken from. Time frame. int lips_shift. int teeth_period. NULL means current symbol. It can be any of Applied price enumeration values. int teeth_shift. MA method. NULL means the current symbol.2. where the data should be taken from. Applied price. int ma_method. MA method. int period. Indicator line offset relate to the chart by timeframe. It can be any of Time frame enumeration values.PRICE_CLOSE. int jaw_period. Deviation. It can be any of Indicators line identifiers enumeration value. Sample double val=iFractals(NULL. 0.2. int timeframe.0. 13. int applied_price. MODE_UPPER. NULL means the current symbol. 0. Sample double val=iForce(NULL. It can be any of Indicators line identifiers enumeration value. int shift) . double iFractals(string symbol.MODE_UPPER.10. Deviation. int lips_period. It can be any of Moving Average method enumeration value. where the data should be taken from. Indicator line array index. double iForce( Parameters symbol timeframe period ma_method applied_price shift string symbol. Shift relative to the current bar (number of periods back). Time frame. Number of periods for calculation. 0. Shift relative to the current bar (number of periods back). 13. It can be any of Time frame enumeration values. int applied_price.MODE_SMA. Parameters symbol timeframe mode shift Symbol the data of which should be used to calculate indicator. Shift relative to the current bar (number of periods back). Sample double val=iEnvelopesOnArray(ExtBuffer. Symbol the data of which should be used to calculate indicator. Indicator line array index. int shift) Calculates the Fractals and returns its value. int mode. double iGator( string symbol. Shift relative to the current bar (number of periods back). int total. where the data should be taken from. It can be any of Applied price enumeration values. int ma_method. Time frame. Number of periods for calculation. It can be any of the Indicators line identifiers enumeration value. int timeframe.0). int jaw_shift. It can be any of Time frame enumeration values. int ma_shift. MA shift.MODE_SMA.0). It can be any of Moving Average method enumeration value.0). 0.0 ). int mode. Indicator line offset relate to the chart by timeframe. MODE_UPPER. int ma_method. 0. where the data should be taken from. Parameters symbol timeframe shift Symbol the data of which should be used to calculate indicator. Indicator line array index.PRICE_CLOSE. Sample double jaw_val=iGator(NULL.0)>iMomentum(NULL.20. 1).Calculates the Gator Oscillator and returns its value. Jaw line shift. where the data should be taken from. Time frame. Parameters symbol timeframe jaw_period jaw_shift teeth_period teeth_shift lips_period lips_shift ma_method applied_price mode shift Symbol the data of which should be used to calculate indicator. Kijun Sen. 52. int applied_price. int timeframe. Time frame. Shift relative to the current bar (number of periods back). int shift) Calculates the Ichimoku Kinko Hyo and returns its value. int senkou_span_b. Shift relative to the current bar (number of periods back). MODE_TENKANSEN. 0. Applied price. It can be any of Time frame enumeration values.PRICE_CLOSE. Applied price. 26.0. It can be any of Indicators line identifiers enumeration value. Tenkan Sen. 5. int shift) Calculates the Bill Williams Market Facilitation index and returns its value. MA method. Sample if(iMomentum(NULL. int shift) Calculates the Momentum indicator and returns its value.0)) . It can be any of Moving Average method enumeration value. Shift relative to the current bar (number of periods back). 8. 8. Shift relative to the current bar (number of periods back).0. 0. double iMomentum( Parameters symbol timeframe period applied_price shift - string symbol. Jaw period. int period. It can be any of Time frame enumeration values. 13. Lips period.NULL means the current symbol. MODE_SMMA. Lips line shift. int timeframe. Symbol the data of which should be used to calculate indicator. 0). where the data should be taken from. int kijun_sen. Source of data. int mode. PRICE_MEDIAN. NULL means the current symbol. NULL means the current symbol. Teeth period. 5. double iBWMFI(string symbol. 9. Number of periods for calculation. Teeth line shift. int tenkan_sen. double iIchimoku( Parameters symbol timeframe tenkan_sen kijun_sen senkou_span_b mode shift string symbol. int timeframe. Sample double val=iBWMFI(NULL. Time frame. It can be any of Applied price enumeration values. Symbol the data of which should be used to calculate indicator. 1). where the data should be taken from. Time frame. It can be any of Applied price enumeration values. 3.12. Senkou SpanB. It can be any of Time frame enumeration values. It can be any of Time frame enumeration values. It can be one of the Ichimoku Kinko Hyo mode enumeration. MODE_UPPER. NULL means the current symbol. Sample double tenkan_sen=iIchimoku(NULL. 0. int period. int shift) Calculates the Momentum indicator counted on buffer and returns its value. It can be any of the Moving Average method enumeration value. Shift relative to the current bar (number of periods back). It can be any of the Moving Average method enumeration value. int period.14. int timeframe. Number of periods for calculation. int period. Sample AlligatorJawsBuffer[i]=iMA(NULL.20. It can be any of Time frame enumeration values. It can be any of Time frame enumeration values.0. int shift) Calculates the Money flow index and returns its value. int total.0. double iMFI(string symbol.0). MA shift MA method.5. int ma_shift.10. int timeframe. Parameters array[] total period shift Array with data.MODE_LWMA.0.0. Parameters symbol timeframe period ma_shift ma_method applied_price shift Symbol the data of which should be used to calculate indicator. Number of periods for calculation. Number of periods for calculation. int total. Time frame. double iMAOnArray( Parameters array[] total period ma_shift ma_method shift - double array[]. Sample if(iMomentumOnArray(mybuffer.0). Parameters symbol timeframe period shift Symbol the data of which should be used to calculate indicator. where the data should be taken from. The number of items to be counted. NULL means the current symbol.12.100. Number of periods for calculation. 0 means whole array.14. Sample if(iMFI(NULL. Shift relative to the current bar (number of periods back). int ma_method.return(0). MA shift.PRICE_MEDIAN.0. The number of items to be counted. int shift) Calculates the Moving average counted on buffer and returns its value. NULL means the current symbol. int applied_price. double iMomentumOnArray(double array[].i). Indicators line offset relate to the chart by timeframe. It can be any of Applied price enumeration values. MA method.1)) return(0). int ma_method.MODE_SMMA. Time frame.MODE_LWMA. int ma_shift.8. double macurrentslow=iMAOnArray(ExtBuffer. Applied price. Sample double macurrent=iMAOnArray(ExtBuffer. where the data should be taken from. Shift relative to the current bar (number of periods back).100.0)>iMomentumOnArray(mubuffer.0.0. where the data should be taken from. int period. int shift) Calculates the Moving average indicator and returns its value. double iMA( string symbol. Shift relative to the current bar (number of periods back).0)>iMFI(NULL.0)) return(0). Array with data.13. where the data should be taken from. . 0. NULL means the current symbol. Shift relative to the current bar (number of periods back).9. Sample if(iOsMA(NULL.12. It can be any of Time frame enumeration values. double iMACD( string symbol. Shift relative to the current bar (number of periods back).PRICE_CLOSE. It can be any of Time frame enumeration values.0.M ODE_SIGNAL. Number of periods for fast moving average calculation. It can be any of Applied price enumeration values. int timeframe.0. Nmber of periods for slow moving average calculation.PRICE_CLOSE. Parameters symbol timeframe fast_ema_period slow_ema_period signal_period applied_price shift Symbol the data of which should be used to calculate indicator. int timeframe.10. Applied price.1). Indicator line array index. It can be any of Time frame enumeration values. Time frame.12.PRICE_OPEN. double step.12. int timeframe.9.26.26.0. PRICE_CLOSE. double maprevslow=iMAOnArray(ExtBuffer. Number of periods for fast moving average calculation. Sample double val=iOBV(NULL.26. Number of periods for signal moving average calculation. Number of periods for signal moving average calculation. int mode. It can be any of the Indicators line identifiers enumeration value. 0. int slow_ema_period.26. Applied price. int timeframe.9. int shift) Calculates the Moving averages convergence/divergence and returns its value. int signal_period.1)>iOsMA(NULL. int shift) Calculates the Parabolic Sell and Reverse system and returns its value. Parameters symbol timeframe fast_ema_period slow_ema_period signal_period applied_price mode shift Symbol the data of which should be used to calculate indicator. Applied price. where the data should be taken from.double maprev=iMAOnArray(ExtBuffer. int shift) Calculates the Moving Average of Oscillator and returns its value.0. double iSAR(string symbol. 1). int applied_price.0)>iMACD(NULL. Number of periods for slow moving average calculation. int fast_ema_period. int applied_price. Parameters . NULL means the current symbol.MODE_LWMA. where the data should be taken from.0.0.0)) return(0).1).9. int fast_ema_period. double iOsMA( string symbol. Shift relative to the current bar (number of periods back). Time frame. It can be any of Applied price enumeration values. NULL means the current symbol. Sample if(iMACD(NULL. Time frame.0. int applied_price. Parameters symbol timeframe applied_price shift Symbol the data of which should be used to calculate indicator.MODE_MAIN. int signal_period.PRICE_OPEN.5.0)) return(0). where the data should be taken from.12. //---if(maprev<maprevslow && macurrent>=macurrentslow) Alert("crossing up"). double iOBV(string symbol. It can be any of Applied price enumeration values. int shift) Calculates the On Balance Volume indicator and returns its value.MODE_LWMA. double maximum. int slow_ema_period. where the data should be taken from. Increment. It can be any of Time frame enumeration values. double iStdDev( Parameters string symbol. Shift relative to the current bar (number of periods back). It can be any of Indicators line identifiers enumeration value.1)) return(0). int applied_price. Sample double val=iRVI(NULL. int shift) Calculates the Relative strength index counted on buffer and returns its value.MODE_MAIN. Time frame. Time frame. It can be any of Time frame enumeration values. Shift relative to the current bar (number of periods back). int timeframe. . double iRVI(string symbol.14. Indicator line array index.PRICE_CLOSE. NULL means the current symbol.symbol timeframe step maximum shift - Symbol the data of which should be used to calculate indicator.0)>Close[0]) return(0).0). Number of periods for calculation. where the data should be taken from. void timeframe.PRICE_CLOSE.1000. int period. The number of items to be counted.0)>iRSI(NULL. Sample if(iRSIOnBuffer(ExtBuffer. int period.0. where the data should be taken from.0.02.2. NULL means the current symbol.14. int ma_period.14.0)>iRSI(NULL. Shift relative to the current bar (number of periods back). 0. Time frame. Parameters symbol timeframe period mode shift Symbol the data of which should be used to calculate indicator. usually 0. int shift) Calculates the Standard Deviation indicator and returns its value. usually 0.02.2.0. int mode. where the data should be taken from. It can be any of Time frame enumeration values. Parameters array[] total period shift Array with data. Parameters symbol timeframe period applied_price shift Symbol the data of which should be used to calculate indicator. Sample if(iRSI(NULL. It can be any of Applied price enumeration values. int ma_shift. Sample if(iSAR(NULL. int timeframe. Number of periods for calculation. double iRSIOnArray(double array[].0. NULL means the current symbol. int shift) Calculates the Relative strength index and returns its value. 10. int period. int ma_method.PRICE_CLOSE.0.14. int applied_price. Shift relative to the current bar (number of periods back).0. Applied price. double iRSI(string symbol. int shift) Calculates the Relative Vigor index and returns its value. Number of periods for calculation. int total. Maximum value.1)) return(0). int shift) Calculates the Stochastic oscillator and returns its value.1)) return(0).0).0. int timeframe.3. NULL means the current symbol. iMA shift. where the data should be taken from.MODE_EMA. Can be one of this values: 0 .0. Shift relative to the current bar (number of periods back). Symbol the data of which should be used to calculate indicator. where the data should be taken from.0.0. int %Kperiod.Close/Close. It can be any of Time frame enumeration values. Sample if(iStochastic(NULL. Time frame. double iWPR(string symbol. where the data should be taken from.Low/High or 1 . Shift relative to the current bar (number of periods back).0. Sample double val=iStdDev(NULL. MA period. Sample double val=iStdDevOnArray(ExtBuffer.MODE_MAIN. MA period. It can be any of Time frame enumeration values.MODE_SIGNAL. int mode. NULL means the current symbol. Shift relative to the current bar (number of periods back).0. NULL means the current symbol.0.MODE_SMA.5. It can be any of Applied price enumeration values. It can be any of Time frame enumeration values. int %Dperiod. int total. %D line period. MA method. double iStdDevOnArray( Parameters array[] total ma_period ma_method ma_shift shift - double array[]. It can be any of Moving Average method enumeration value. Number of periods for calculation. int ma_period. Price field parameter. It can be any ofMoving Average method enumeration value. Applied price.3. Sample if(iWPR(NULL.14. Indicator line array index. where the data should be taken from. It can be any of the Indicators line identifiers enumeration value. int method.0. double iStochastic( Parameters symbol timeframe %Kperiod %Dperiod slowing method price_field mode shift - string symbol.0)) return(0). int slowing. int price_field. It can be any of Moving Average method enumeration value.MODE_S MA.3. The number of items to be counted. MA shift. Slowing value.symbol timeframe ma_period ma_method ma_shift applied_price shift - Symbol the data of which should be used to calculate indicator. int ma_method. MA method. MA method.PRICE_CLOSE.10.MODE_EMA. Time frame.0)>iStochastic(NULL. int shift) Calculates the Larry William's percent range indicator and returns its value. int period.100.0)>iWPR(NULL.10. Shift relative to the current bar (number of periods back).3. int shift) Calculates the Standard Deviation counted on buffer and returns its value. %K line period.5. Array with data. .0. Parameters symbol timeframe period shift Symbol the data of which should be used to calculate indicator.14. int timeframe.0). int ma_shift. Time frame. iOpen("USDCHF". where the data should be taken from.PERIOD_M1. If the bar having the specified open time is absent the function will return. int shift=iBarShift("EUROUSD". int timeframe. bool exact=false) Search for bar by open time.".i).". int timeframe.iTime("USDCHF". ". Sample datetime some_time=D'2004. int shift) Returns Close value for the bar of indicated symbol with timeframe and shift.iTime("USDCHF". iLow("USDCHF".iBarShift returns nearest. If local history is empty (not loaded). NULL means the current symbol. Sample Print("Bar count on the 'EUROUSD' symbol with PERIOD_H1 is".". where the data should be taken from. iClose("USDCHF". Time frame.i). Shift relative to the current bar (number of periods back). iVolume("USDCHF". int timeframe. Shift relative to the current bar (number of periods back).int iBars(string symbol. Time frame.PERIOD_H1. It can be any of Time frame enumeration values. value to find (bar's open time).some_time). It can be any of Time frame enumeration values.i). It can be any of Time frame enumeration values.".PERIOD_H1. iOpen("USDCHF".i)).".i)).TimeToStr(some_time).iBars("EUROUSD".PERIOD_H1. NULL means the current symbol.i).i).PERIOD_H1. iHigh("USDCHF". If local history is empty (not loaded).". Sample Print("Current bar for USDCHF H1: ".iBarShift returns -1. iClose("USDCHF". ". ". double iClose(string symbol. ".PERIOD_H1. -1 or the nearest bar shift.shift).PERIOD_H1)).i).".PERIOD_H1.i). iHigh("USDCHF".PERIOD_H1. ".i). ". Sample Print("Current bar for USDCHF H1: ". ". NULL means the current symbol. Return mode when bar not found. function returns 0.PERIOD_H1. int iBarShift(string symbol.PERIOD_H1. iVolume("USDCHF". Parameters symbol timeframe Symbol the data of which should be used to calculate indicator. It can be any of Time frame enumeration values. double iHigh(string symbol. true .21 12:00'.i)." is ".i). depending on the exact parameter.". ". Parameters symbol timeframe shift Symbol the data of which should be used to calculate indicator.". int shift) Returns High value for the bar of indicated symbol with timeframe and shift. Time frame. Parameters symbol timeframe shift Symbol on that data need to calculate indicator. int timeframe) Returns the number of bars on the specified chart. function returns 0.PERIOD_H1. ". ". Time frame. datetime time.03.". NULL means current symbol. Print("shift of bar with open time ". false . iLow("USDCHF".PERIOD_H1.PERIOD_H1. The function returns bar shift with the open time specified. . Parameters symbol timeframe time exact Symbol the data of which should be used to calculate indicator. i).PERIOD_H1. ". Time frame. Shift relative to the current bar (number of periods back). int timeframe. iLow("USDCHF".i).".i). Sample Print("Current bar for USDCHF H1: ". It can be any of Time frame enumeration values.PERIOD_H1.iTime("USDCHF". Sample Print("Current bar for USDCHF H1: ".PERIOD_H1. ". iVolume("USDCHF".PERIOD_H1.". Shift relative to the current bar (number of periods back).i)).". where the data should be taken from. int timeframe. ".PERIOD_H1. ". iVolume("USDCHF". Time frame. Shift relative to the current bar (number of periods back). ". int shift) Returns Time value for the bar of indicated symbol with timeframe and shift. ". where the data should be taken from. double iVolume(string symbol. int shift) Returns Low value for the bar of indicated symbol with timeframe and shift.i)).i). iClose("USDCHF". Time frame. iClose("USDCHF".i). NULL means the current symbol.".i).i). int shift) Returns Open value for the bar of indicated symbol with timeframe and shift.i)). int timeframe.". function returns 0. int shift) Returns Volume value for the bar of indicated symbol with timeframe and shift. ".". NULL means the current symbol.PERIOD_H1. function returns 0.iTime("USDCHF". iVolume("USDCHF".".PERIOD_H1.PERIOD_H1. . ".i). Parameters symbol timeframe shift Symbol the data of which should be used to calculate indicator.". where the data should be taken from.PERIOD_H1. iClose("USDCHF". Parameters symbol timeframe shift Symbol the data of which should be used to calculate indicator.PERIOD_H1.i). iHigh("USDCHF".i). ".i). ".".". iOpen("USDCHF". int timeframe. Parameters symbol timeframe shift Symbol the data of which should be used to calculate indicator. It can be any of Time frame enumeration values.PERIOD_H1.". ".PERIOD_H1. where the data should be taken from. It can be any of Time frame enumeration values. iOpen("USDCHF". iLow("USDCHF".PERIOD_H1. Shift relative to the current bar (number of periods back). iHigh("USDCHF".iTime("USDCHF". function returns 0. ". If local history is empty (not loaded).PERIOD_H1. If local history is empty (not loaded). ". ". iLow("USDCHF".PERIOD_H1.". iHigh("USDCHF". datetime iTime(string symbol. Time frame. function returns 0. iOpen("USDCHF". If local history is empty (not loaded).i).i).".".PERIOD_H1.double iLow(string symbol. double iOpen(string symbol.PERIOD_H1.PERIOD_H1. It can be any of Time frame enumeration values. If local history is empty (not loaded). NULL means the current symbol. Parameters symbol timeframe shift Symbol the data of which should be used to calculate indicator.". ".i). Sample Print("Current bar for USDCHF H1: ". NULL means the current symbol.i). i)). int type. iHigh("USDCHF". int count=WHOLE_ARRAY.PERIOD_H1.0. Shift showing the bar.0.PERIOD_H1. Series array identifier.Sample Print("Current bar for USDCHF H1: ". It can be any of Series array identifier enumeration values. Trading functions HistoryTotal() OrderClose() OrderCloseBy() OrderClosePrice() OrderCloseTime() OrderComment() OrderCommission() OrderDelete() OrderExpiration() OrderLots() OrderMagicNumber() OrderModify() OrderOpenPrice() OrderOpenTime() OrderPrint() OrderProfit() OrderSelect() OrderSend() OrderStopLoss() . It can be any of the Series array identifier enumeration values.i).PERIOD_H1. Time frame. It can be any of Time frame enumeration values. ". that the data should be taken from.MODE_HIGH.i). Sample double val. int count=WHOLE_ARRAY. Number of periods (in direction from the start bar to the back one) on which the calculation is carried out. int Lowest(string symbol.20. iOpen("USDCHF".PERIOD_H1.". ".10.". int start=0) Returns the shift of the maximum value over a specific number of periods depending on type. relative to the current bar. int start=0) Returns the shift of the least value over a specific number of periods depending on type.10)]. Number of periods (in direction from the start bar to the back one) on which the calculation is carried out. that the data should be taken from.". NULL means the current symbol. Time frame. iClose("USDCHF". int timeframe.PERIOD_H1.MODE_LOW. iVolume("USDCHF". Parameters symbol timeframe type count start Symbol the data of which should be used to calculate indicator. ".". NULL means the current symbol. relative to the current bar. iLow("USDCHF". It can be any of Time frame enumeration values. Parameters symbol timeframe type count start Symbol the data of which should be used to calculate indicator. int timeframe. Series array identifier. Sample double val=Low[Lowest(NULL. // calculating the highest value in the range from 5 element to 25 element // indicator charts symbol and indicator charts time frame val=High[Highest(NULL. Shift showing the bar.PERIOD_H1.i). ". int Highest(string symbol.iTime("USDCHF".". ".i).4)].i). int type. MODE_HISTORY)==false) { Print("Access to history failed with error (". If the function succeeds. To get the detailed error information.0.Red). break. If the function fails.0)>75) { .OrdersTotal() OrderSwap() OrderSymbol() OrderTakeProfit() OrderTicket() OrderType() int HistoryTotal() Returns the number of closed orders in the account history loaded into the terminal. Parameters ticket lots price slippage Color Unique number of the order ticket. Sample if(iRSI(NULL. Sample // retrieving info from trade history int i.check selection result if(OrderSelect(i. color Color=CLR_NONE) Closes opened order by another opposite opened order.Ask.3. Color of the closing arrow on the chart. double lots.")"). To get the detailed error information. the return value is false.PRICE_CLOSE. Preferred closing price. } bool OrderCloseBy(int ticket.If the parameter is absent or has CLR_NONE value closing arrow will not be drawn on the chart.SELECT_BY_POS. return(0).14.i<hstTotal. Value of the maximum price slippage in points. color Color=CLR_NONE) Closes opened order.i++) { //---. the return value is true. int opposite. To get the detailed error information.0)>75) { OrderClose(order_id. call GetLastError() function. Color of the closing arrow on the chart.If the parameter is absent or has CLR_NONE value closing arrow will not be drawn on the chart. for(i=0. Sample if(iRSI(NULL. Parameters ticket opposite Color Unique number of the order ticket. the return value is true. } // some work with order } bool OrderClose( int ticket. Unique number of the opposite order ticket. call GetLastError().1. If the function succeeds.14. Number of lots.PRICE_CLOSE. the return value is false.0.GetLastError(). double price.hstTotal=HistoryTotal(). int slippage. call GetLastError(). If the function fails. SELECT_BY_TICKET)==false) { Print("OrderSelect failed error code is".ticket. string OrderComment() Returns comment for Note: Order must be selected by OrderSelect() function.OrderClosePrice()).SELECT_BY_POS)==true) Print("Close price for the order ". the currently selected order. ctm). if(ctm>0) Print("Close time for the order 10 ". . datetime OrderCloseTime() Returns close time for the currently selected order. Sample string comment." = ". } double OrderClosePrice() Returns close price for Note: Order must be selected by OrderSelect() function.. Sample if(OrderSelect(10.MODE_HISTORY)==true) { datetime ctm=OrderOpenTime(). for the currently selected order. ctm).SELECT_BY_POS)==true) Print("Commission for the order 10 ". if(ctm>0) Print("Open time for the order 10 ".GetLastError()). // .OrderCloseBy(order_id. ctm=OrderCloseTime(). return(0). } else Print("OrderSelect failed error code is".. return(0).GetLastError()). double OrderCommission() Returns calculated commission Note: Order must be selected by OrderSelect() function. } comment = OrderComment().OrderCommission()). Sample if(OrderSelect(10. the selected order. else Print("OrderSelect failed error code is". Note: Order must be selected by OrderSelect() function.SELECT_BY_POS.opposite_id). else Print("OrderSelect failed error code is". If order close time is not 0 then the order selected and has been closed and retrieved from the account history. if(OrderSelect(10.GetLastError()). Sample if(OrderSelect(ticket.GetLastError()). SELECT_BY_POS)==true) Print("lots for the order 10 ".OrderExpiration()). the return value is false. call GetLastError(). the currently selected order. double stoploss.GetLastError()). the selected pending order. int OrderMagicNumber() Returns magic number for Note: Order must be selected by OrderSelect() function. To get the detailed error information. SELECT_BY_TICKET)==true) Print("Order expiration for the order #10 is ". datetime expiration. the return value is true. Parameters .GetLastError()).SELECT_BY_POS)==true) Print("Magic number for the order 10 ".GetLastError()). Parameters ticket Unique number of the order ticket. return(0). OrderMagicNumber()). } datetime OrderExpiration() Returns expiration date for Note: Order must be selected by OrderSelect() function. the return value is false. else Print("OrderSelect failed error code is". If the function fails. Sample if(Ask>var1) { OrderDelete(order_ticket). If the function succeeds. If the function fails. call GetLastError(). else Print("OrderSelect failed error code is".OrderLots()). for the selected order. bool OrderModify( int ticket. Sample if(OrderSelect(10. If the function succeeds. Sample if(OrderSelect(10. color arrow_color=CLR_NONE) Modification of characteristics for the previously opened position or a pending order.bool OrderDelete(int ticket) Deletes previously opened pending order. double OrderLots() Returns lots value Note: Order must be selected by OrderSelect() function. To get the detailed error information. double takeprofit. the return value is true. else Print("OrderSelect failed error code is". Sample if(OrderSelect(10. double price. if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(). void OrderPrint() Prints selected order data to Note: Order must be selected by OrderSelect() function. SELECT_BY_TICKET)==true) OrderPrint().Ask-10*Point. Sample if(TrailingStop>0) { SelectOrder(12345. the log for the selected order. datetime OrderOpenTime() Returns open time for Note: Order must be selected by OrderSelect() function.Blue). Sample if(OrderSelect(10. Sample if(OrderSelect(10. Order expiration server date/time (for pending orders only).ticket price stoploss takeprofit expiration arrow_color - Unique number of the order ticket. New price (for pending orders only).If the parameter is absent or has CLR_NONE value arrow will not be drawn on the chart. double OrderProfit() Returns profit for the currently selected order. else Print("OrderSelect failed error code is". else Print("OrderSelect failed error code is".OrderTakeProfit(). New profit-taking level. else Print("OrderSelect failed error code is". .GetLastError()). SELECT_BY_POS)==true) Print("open time for the order 10 ".OrderOpenPrice()). return(0). } } } double OrderOpenPrice() Returns open price for Note: Order must be selected by OrderSelect() function. the currently selected order. the currently selected order.0.SELECT_BY_TICKET). SELECT_BY_POS)==true) Print("open price for the order 10 ". New stoploss level.GetLastError()). Arrow color of the pictogram on the chart. Sample if(OrderSelect(10.Ask35*Point.OrderOpenTime()).GetLastError()). Note: Order must be selected by OrderSelect() function. Returns ticket of the placed order or -1 if failed. If the function fails."My order #2".order selected from trading pool(opened and pending orders). if(iRSI(NULL. Color of the opening arrow on the chart.Green). Operation type.index is order ticket.order selected from history pool (closed and canceled order). else Print("OrderSelect failed error code is". int string symbol.Ask-25*Point.Ask. Preferred price of the trade. if(ticket<0) { Print("OrderSend failed with error #". Optional order pool index. To get the extended error information. Order magic number. If parameter is absent or has CLR_NONE value opening arrow is not drawn on the chart. pool - Sample if(OrderSelect(12470. int magic=0.1.16384. call GetLastError(). OrderOpenPrice()). double volume. int cmd. SELECT_BY_TICKET .0)<25) { ticket=OrderSend(Symbol(). SELECT_BY_POS)==true) Print("Profit for the order 10 ". It can be any of the Trade operation enumeration. double price.Ask+25*Point. color arrow_color=CLR_NONE) Main function used to open a position or set a pending order. Parameters index select Order index or order ticket depending from second parameter. Print("order #12470 close price is ". } else Print("OrderSelect failed error code is". datetime expiration=0. . Order comment text.PRICE_CLOSE.3.0. Maximum price slippage for buy or sell orders. int pool=MODE_TRADES) Selects order by index or ticket to further processing. int slippage. Sample int ticket. Take profit level. bool OrderSelect(int index. MODE_HISTORY .GetLastError()). string comment=NULL. Last part of the comment may be changed by server.14. Sample if(OrderSelect(10. Used when select parameter is SELECT_BY_POS. Number of lots. Parameters symbol cmd volume price slippage stoploss takeprofit comment magic expiration arrow_color Symbol for trading.GetLastError()). Selecting flags.GetLastError()).OrderProfit()). Order expiration time (for pending orders only). return(0). OrderClosePrice()).index in the order pool.OP_BUY. To check error code use GetLastError() function.0. It can be any of the following values: SELECT_BY_POS .It can be any of the following values: MODE_TRADES (default). SELECT_BY_TICKET)==true) { Print("order #12470 open price is ". May be used as user defined identifier. the return value will be false. Stop loss level. int select. double takeprofit. OrderSend( double stoploss. } } double OrderStopLoss() Returns stop loss value Note: Order must be selected by OrderSelect() function. FileWrite(handle. SELECT_BY_TICKET)==true) Print("Swap for the order #".GetLastError()).GetLastError()). int total=OrdersTotal()."open price". " is ".pos<total. } FileClose(handle).OrderOpenTime().SELECT_BY_POS)==false) continue."#". for the currently selected order. else Print("OrderSelect failed error code is".GetLastError())."symbol". SELECT_BY_POS)==true) Print("symbol of order #". else Print("OrderSelect failed error code is". OrderStopLoss()). Sample if(OrderSelect(12. Sample if(OrderSelect(order_id.Or derLots()).pos++) { if(OrderSelect(pos. Sample int handle=FileOpen("OrdersReport. // write header FileWrite(handle. double OrderTakeProfit() Returns take profit value for the currently selected order.FILE_WRITE|FILE_CSV. the currently selected order. string OrderSymbol() Returns the order symbol Note: Order must be selected by OrderSelect() function. // write open orders for(int pos=0. else Print("OrderSelect failed error code is".csv".SELECT_BY_POS)==true) Print("Stop loss value for the order 10 ".OrderSwap()). OrderTicket(). OrderSymbol()). int OrdersTotal() Returns market and pending orders count. order_id. " "."open time"."lots"). Sample if(OrderSelect(ticket. if(handle<0) return(0). . double OrderSwap() Returns swap value for Note: Order must be selected by OrderSelect() function.OrderOpenPrice()."\t").OrderTicket().OrderSymbol(). value for selected order. the currently selected order. SELECT_BY_POS)==true) { order_type=OrderType().Note: Order must be selected by OrderSelect() function.".. SELECT_BY_POS)==true) order=OrderTicket().. Sample if(OrderSelect(12. position. pending pending pending pending Sample int order_type.GetLastError()). position. SELECT_BY_POS)==true) Print("Order #".OrderTicket(). Sample . else Print("OrderSelect failed error code is". position. } else Print("OrderSelect() returned error . selected order. Sample if(OrderSelect(12." profit: ". else Print("OrderSelect() 忮痦箅 铠栳牦 . // . position.GetLastError()). int OrderType() Returns order operation type for the currently OP_BUY OP_SELL OP_BUYLIMIT buy OP_BUYSTOP buy OP_SELLLIMIT sell OP_SELLSTOP sell Note: Order must be selected by OrderSelect() function. if(OrderSelect(12.".GetLastError()). OrderTakeProfit()). Window functions BarsPerWindow() FirstVisibleBar() PriceOnDropped() TimeOnDropped() WindowFind() WindowHandle() WindowIsVisible WindowOnDropped() WindowsTotal() WindowXOnDropped() WindowYOnDropped() int BarsPerWindow() Function returns the amount of bars visible on the chart. int OrderTicket() Returns ticket number for Note: Order must be selected by OrderSelect() function. position. limit stop limit stop It can buying selling be any of the following values: position. i<bars_count. for(int i=0. 0. i<bars_count.. Parameters name Indicator short name. Sample double drop_price=PriceOnDropped(). Sample // work with visible bars..bar--) { // . } datetime TimeOnDropped() Returns time part of dropped point where expert or script was dropped. } int WindowFind(string name) If indicator with name found returns the window index containing specified indicator. OBJ_VLINE.. otherwise returns -1. Sample . This value is valid when expert or script dropped by mouse. i++. OBJ_HLINE. datetime drop_time=TimeOnDropped().may be undefined (zero) if(drop_time>0) { ObjectCreate("Dropped price line". Note: WindowFind() returns -1 if ñustom indicator searches itself when init() function works. } int FirstVisibleBar() Function returns index of the first visible bar. Note: For custom indicators this value is undefined. i<bars_count. int bar=FirstVisibleBar(). } int FirstVisibleBar() Function returns index of the first visible bar.// work with visible bars. Sample // work with visible bars. 0.. int bars_count=BarsPerWindow(). int bar=FirstVisibleBar(). int bars_count=BarsPerWindow(). drop_price). //---.bar--) { // . i++. for(int i=0. int bars_count=BarsPerWindow(). ObjectCreate("Dropped time line". drop_time). i++. for(int i=0..bar--) { // . int bar=FirstVisibleBar().. otherwise returns 0. Parameters symbol timeframe symbol name.H1 detected. Time frame. Rates array will be copied immediately. It can be any of Time frame enumeration values. WindowOnDropped() Sample Print("Expert dropped point x=". See also WindowYOnDropped(). else Print("window of MyMACD not found or is not visible"). } int WindowsTotal() Returns count of indicator windows on the chart (including main chart). Sample Print("Windows count = ". because custom indicator can create its own new window). Note: For custom indicators this index is undefined when init() function works and returning index is window index where custom indicator works (may be different from dropping window index. return(false). custom indicator or script dropped by mouse.26. See also WindowXOnDropped().WindowXOnDropped(). int WindowXOnDropped() Returns x-axis coordinate in pixels were expert or script dropped to the chart. WindowYOnDropped() Sample if(WindowOnDropped()!=0) { Print("Indicator 'MyIndicator' must be applied to main chart window!"). bool WindowIsVisible(int index) Returns true if the chart subwindow is visible. Sample int maywin=WindowFind("MyMACD"). Sample int win_handle=WindowHandle("USDX". int timeframe) If chart of symbol and timeframe is currently opened returns the window handle." y=".PERIOD_H1). Parameters index Chart subwindow index. int WindowHandle(string symbol. otherwise returns false. custom indicator or script was dropped. This value is valid when expert. WindowsTotal()). int WindowOnDropped() Returns window index where expert. if(maywin>-1 && WindowIsVisible(maywin)==true) Print("window of MyMACD is visible").int win_idx=WindowFind("MACD(12. . if(win_handle!=0) Print("Window with USDX.").WindowYOnDropped()).9)"). MetaQuotes Software Corp.mqh | //| Copyright © 2004-2005. See also WindowYOnDropped().metaquotes." y=".errors returned from trade server #define ERR_NO_ERROR 0 #define ERR_NO_RESULT 1 #define ERR_COMMON_ERROR 2 #define ERR_INVALID_TRADE_PARAMETERS 3 #define ERR_SERVER_BUSY 4 #define ERR_OLD_VERSION 5 #define ERR_NO_CONNECTION 6 #define ERR_NOT_ENOUGH_RIGHTS 7 #define ERR_TOO_FREQUENT_REQUESTS 8 #define ERR_MALFUNCTIONAL_TRADE 9 #define ERR_ACCOUNT_DISABLED 64 #define ERR_INVALID_ACCOUNT 65 #define ERR_TRADE_TIMEOUT 128 #define ERR_INVALID_PRICE 129 #define ERR_INVALID_STOPS 130 #define ERR_INVALID_TRADE_VOLUME 131 #define ERR_MARKET_CLOSED 132 #define ERR_TRADE_DISABLED 133 #define ERR_NOT_ENOUGH_MONEY 134 #define ERR_PRICE_CHANGED 135 #define ERR_OFF_QUOTES 136 #define ERR_BROKER_BUSY 137 #define ERR_REQUOTE 138 #define ERR_ORDER_LOCKED 139 #define ERR_LONG_POSITIONS_ONLY_ALLOWED 140 #define ERR_TOO_MANY_REQUESTS 141 #define ERR_TRADE_MODIFY_DENIED 145 #define ERR_TRADE_CONTEXT_BUSY 146 //---. Include Files //+------------------------------------------------------------------+ //| stderror.int WindowYOnDropped() Returns y-axis coordinate in pixels were expert or script dropped to the chart.net/ | //+------------------------------------------------------------------+ //---.WindowYOnDropped()).WindowXOnDropped(). WindowOnDropped() Sample Print("Expert dropped point x=". | //| http://www.mql4 run time errors #define ERR_NO_MQLERROR 4000 #define ERR_WRONG_FUNCTION_POINTER 4001 #define ERR_ARRAY_INDEX_OUT_OF_RANGE 4002 #define ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK 4003 #define ERR_RECURSIVE_STACK_OVERFLOW 4004 #define ERR_NOT_ENOUGH_STACK_FOR_PARAMETER 4005 #define ERR_NO_MEMORY_FOR_PARAMETER_STRING 4006 #define ERR_NO_MEMORY_FOR_TEMP_STRING 4007 #define ERR_NOT_INITIALIZED_STRING 4008 #define ERR_NOT_INITIALIZED_ARRAYSTRING 4009 #define ERR_NO_MEMORY_FOR_ARRAYSTRING 4010 #define ERR_TOO_LONG_STRING 4011 #define ERR_REMAINDER_FROM_ZERO_DIVIDE 4012 #define ERR_ZERO_DIVIDE 4013 #define ERR_UNKNOWN_COMMAND 4014 #define ERR_WRONG_JUMP 4015 #define ERR_NOT_INITIALIZED_ARRAY 4016 #define ERR_DLL_CALLS_NOT_ALLOWED 4017 #define ERR_CANNOT_LOAD_LIBRARY 4018 #define ERR_CANNOT_CALL_FUNCTION 4019 . int green_value.int blue_value).mqh | //| Copyright © 2004. //+------------------------------------------------------------------+ //| WinUser32.dll" //---. IntegerToHexString(int integer_number).int precision). | //| http://www. CompareDoubles(double number1.net/" #import "user32.metaquotes. RGB(int red_value.metaquotes. MetaQuotes Software Corp. MetaQuotes Software Corp. | //| http://www. MetaQuotes Software Corp.metaquotes." #define link "http://www.net/ | //+------------------------------------------------------------------+ #import "stdlib.#define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING ERR_SYSTEM_BUSY ERR_INVALID_FUNCTION_PARAMETERS_COUNT ERR_INVALID_FUNCTION_PARAMETER_VALUE ERR_STRING_FUNCTION_INTERNAL_ERROR ERR_SOME_ARRAY_ERROR ERR_INCORRECT_SERIES_ARRAY_USING ERR_CUSTOM_INDICATOR_ERROR ERR_INCOMPATIBLE_ARRAYS ERR_GLOBAL_VARIABLES_PROCESSING_ERROR ERR_GLOBAL_VARIABLE_NOT_FOUND ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE ERR_FUNCTION_NOT_CONFIRMED ERR_SEND_MAIL_ERROR ERR_STRING_PARAMETER_EXPECTED ERR_INTEGER_PARAMETER_EXPECTED ERR_DOUBLE_PARAMETER_EXPECTED ERR_ARRAY_AS_PARAMETER_EXPECTED ERR_HISTORY_WILL_UPDATED ERR_END_OF_FILE ERR_SOME_FILE_ERROR ERR_WRONG_FILE_NAME ERR_TOO_MANY_OPENED_FILES ERR_CANNOT_OPEN_FILE ERR_INCOMPATIBLE_ACCESS_TO_FILE ERR_NO_ORDER_SELECTED ERR_UNKNOWN_SYMBOL ERR_INVALID_PRICE_PARAM ERR_INVALID_TICKET ERR_TRADE_NOT_ALLOWED ERR_LONGS__NOT_ALLOWED ERR_SHORTS_NOT_ALLOWED ERR_OBJECT_ALREADY_EXISTS ERR_UNKNOWN_OBJECT_PROPERTY ERR_OBJECT_DOES_NOT_EXIST ERR_UNKNOWN_OBJECT_TYPE ERR_NO_OBJECT_NAME ERR_OBJECT_COORDINATES_ERROR ERR_NO_SPECIFIED_SUBWINDOW 4020 4021 4022 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4200 4201 4202 4203 4204 4205 4206 //+------------------------------------------------------------------+ //| stdlib.net/ | //+------------------------------------------------------------------+ #define copyright "Copyright © 2004.double number2).ex4" string int bool string string ErrorDescription(int error_code).messages . DoubleToStrMorePrecision(double number.mqh | //| Copyright © 2004. int GetSystemMetrics(int nIndex).string lpCaption.int dwFlags /*bInvert*/).windows int FindWindowA(string lpClassName .int nCmdShow).int Msg.int nMaxCount). int DestroyWindow(int hWnd).int uCmd). int SendNotifyMessageA(int hWnd. void mouse_event(int dwFlags. int GetWindowTextA(int hWnd.int bRepaint).int SendMessageA(int hWnd.int nWidth.miscelaneouse int MessageBoxA(int hWnd .int Y. int PostMessageA(int hWnd.int wLanguageId).string lpString.int X. //---. int SetWindowPos(int hWnd.Window Messages #define WM_NULL #define WM_CREATE #define WM_DESTROY #define WM_MOVE #define WM_SIZE #define WM_ACTIVATE #define WM_SETFOCUS #define WM_KILLFOCUS #define WM_ENABLE #define WM_SETREDRAW #define WM_SETTEXT #define WM_GETTEXT #define WM_GETTEXTLENGTH #define WM_PAINT #define WM_CLOSE #define WM_QUERYENDSESSION #define WM_QUIT #define WM_QUERYOPEN #define WM_ERASEBKGND #define WM_SYSCOLORCHANGE #define WM_ENDSESSION #define WM_SHOWWINDOW #define WM_WININICHANGE #define WM_SETTINGCHANGE #define WM_DEVMODECHANGE #define WM_ACTIVATEAPP 0x0000 0x0001 0x0002 0x0003 0x0005 0x0006 0x0007 0x0008 0x000A 0x000B 0x000C 0x000D 0x000E 0x000F 0x0010 0x0011 0x0012 0x0013 0x0014 0x0015 0x0016 0x0018 0x001A 0x001A // WM_WININICHANGE 0x001B 0x001C . int IsWindowVisible(int hWnd). int AnimateWindow(int hWnd.int dy.int uFlags).string lpText.int X. int SwapMouseButton(int fSwap). int IsWindowEnabled(int hWnd).int dwReserved).int cy. int IsIconic(int hWnd).int bEnable).int wParam.int dwFlags).int dwFlags.string lpString).int dwData.int Msg. int IsZoomed(int hWnd). int EnableWindow(int hWnd. int GetWindowTextLengthA(int hWnd).string lpText.int dwExtraInfo). int MoveWindow(int hWnd.int uType).int lParam). int MessageBeep(int uType). #import //---.int Y. int GetActiveWindow(). int GetWindow(int hWnd.int dwTime.int wParam.int nHeight.int lParam). void keybd_event(int bVk.string lpWindowName).int cx.int Msg.int wParam. int ExitWindowsEx(int uFlags.int dwExtraInfo). int GetFocus(). int UpdateWindow(int hWnd). int FlashWindow(int hWnd. int ShowWindow(int hWnd.int dx.int bScan.int lParam).int uType.int hWndInsertAfter . //---. int MessageBoxExA(int hWnd . int SetWindowTextA(int hWnd. int SetFocus(int hWnd).string lpCaption. int CloseWindow(int hWnd). int SetActiveWindow(int hWnd). #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define WM_FONTCHANGE WM_TIMECHANGE WM_CANCELMODE WM_SETCURSOR WM_MOUSEACTIVATE WM_CHILDACTIVATE WM_QUEUESYNC WM_GETMINMAXINFO WM_PAINTICON WM_ICONERASEBKGND WM_NEXTDLGCTL WM_SPOOLERSTATUS WM_DRAWITEM WM_MEASUREITEM WM_DELETEITEM WM_VKEYTOITEM WM_CHARTOITEM WM_SETFONT WM_GETFONT WM_SETHOTKEY WM_GETHOTKEY WM_QUERYDRAGICON WM_COMPAREITEM WM_GETOBJECT WM_COMPACTING WM_WINDOWPOSCHANGING WM_WINDOWPOSCHANGED WM_COPYDATA WM_CANCELJOURNAL WM_NOTIFY WM_INPUTLANGCHANGEREQUEST WM_INPUTLANGCHANGE WM_TCARD WM_HELP WM_USERCHANGED WM_NOTIFYFORMAT WM_CONTEXTMENU WM_STYLECHANGING WM_STYLECHANGED WM_DISPLAYCHANGE WM_GETICON WM_SETICON WM_NCCREATE WM_NCDESTROY WM_NCCALCSIZE WM_NCHITTEST WM_NCPAINT WM_NCACTIVATE WM_GETDLGCODE WM_SYNCPAINT WM_NCMOUSEMOVE WM_NCLBUTTONDOWN WM_NCLBUTTONUP WM_NCLBUTTONDBLCLK WM_NCRBUTTONDOWN WM_NCRBUTTONUP WM_NCRBUTTONDBLCLK WM_NCMBUTTONDOWN WM_NCMBUTTONUP WM_NCMBUTTONDBLCLK WM_KEYFIRST WM_KEYDOWN WM_KEYUP WM_CHAR WM_DEADCHAR WM_SYSKEYDOWN WM_SYSKEYUP 0x001D 0x001E 0x001F 0x0020 0x0021 0x0022 0x0023 0x0024 0x0026 0x0027 0x0028 0x002A 0x002B 0x002C 0x002D 0x002E 0x002F 0x0030 0x0031 0x0032 0x0033 0x0037 0x0039 0x003D 0x0041 0x0046 0x0047 0x004A 0x004B 0x004E 0x0050 0x0051 0x0052 0x0053 0x0054 0x0055 0x007B 0x007C 0x007D 0x007E 0x007F 0x0080 0x0081 0x0082 0x0083 0x0084 0x0085 0x0086 0x0087 0x0088 0x00A0 0x00A1 0x00A2 0x00A3 0x00A4 0x00A5 0x00A6 0x00A7 0x00A8 0x00A9 0x0100 0x0100 0x0101 0x0102 0x0103 0x0104 0x0105 . #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define WM_SYSCHAR WM_SYSDEADCHAR WM_KEYLAST WM_INITDIALOG WM_COMMAND WM_SYSCOMMAND WM_TIMER WM_HSCROLL WM_VSCROLL WM_INITMENU WM_INITMENUPOPUP WM_MENUSELECT WM_MENUCHAR WM_ENTERIDLE WM_MENURBUTTONUP WM_MENUDRAG WM_MENUGETOBJECT WM_UNINITMENUPOPUP WM_MENUCOMMAND WM_CTLCOLORMSGBOX WM_CTLCOLOREDIT WM_CTLCOLORLISTBOX WM_CTLCOLORBTN WM_CTLCOLORDLG WM_CTLCOLORSCROLLBAR WM_CTLCOLORSTATIC WM_MOUSEFIRST WM_MOUSEMOVE WM_LBUTTONDOWN WM_LBUTTONUP WM_LBUTTONDBLCLK WM_RBUTTONDOWN WM_RBUTTONUP WM_RBUTTONDBLCLK WM_MBUTTONDOWN WM_MBUTTONUP WM_MBUTTONDBLCLK WM_PARENTNOTIFY WM_ENTERMENULOOP WM_EXITMENULOOP WM_NEXTMENU WM_SIZING WM_CAPTURECHANGED WM_MOVING WM_DEVICECHANGE WM_MDICREATE WM_MDIDESTROY WM_MDIACTIVATE WM_MDIRESTORE WM_MDINEXT WM_MDIMAXIMIZE WM_MDITILE WM_MDICASCADE WM_MDIICONARRANGE WM_MDIGETACTIVE WM_MDISETMENU WM_ENTERSIZEMOVE WM_EXITSIZEMOVE WM_DROPFILES WM_MDIREFRESHMENU WM_MOUSEHOVER WM_MOUSELEAVE WM_CUT WM_COPY WM_PASTE WM_CLEAR WM_UNDO 0x0106 0x0107 0x0108 0x0110 0x0111 0x0112 0x0113 0x0114 0x0115 0x0116 0x0117 0x011F 0x0120 0x0121 0x0122 0x0123 0x0124 0x0125 0x0126 0x0132 0x0133 0x0134 0x0135 0x0136 0x0137 0x0138 0x0200 0x0200 0x0201 0x0202 0x0203 0x0204 0x0205 0x0206 0x0207 0x0208 0x0209 0x0210 0x0211 0x0212 0x0213 0x0214 0x0215 0x0216 0x0219 0x0220 0x0221 0x0222 0x0223 0x0224 0x0225 0x0226 0x0227 0x0228 0x0229 0x0230 0x0231 0x0232 0x0233 0x0234 0x02A1 0x02A3 0x0300 0x0301 0x0302 0x0303 0x0304 . mouse_event routines #define MOUSEEVENTF_MOVE #define MOUSEEVENTF_LEFTDOWN #define MOUSEEVENTF_LEFTUP #define MOUSEEVENTF_RIGHTDOWN #define MOUSEEVENTF_RIGHTUP #define MOUSEEVENTF_MIDDLEDOWN #define MOUSEEVENTF_MIDDLEUP #define MOUSEEVENTF_WHEEL #define MOUSEEVENTF_ABSOLUTE //---.GetSystemMetrics() codes #define SM_CXSCREEN #define SM_CYSCREEN #define SM_CXVSCROLL #define SM_CYHSCROLL #define SM_CYCAPTION #define SM_CXBORDER #define SM_CYBORDER #define SM_CXDLGFRAME #define SM_CYDLGFRAME #define SM_CYVTHUMB #define SM_CXHTHUMB #define SM_CXICON #define SM_CYICON #define SM_CXCURSOR #define SM_CYCURSOR #define SM_CYMENU #define SM_CXFULLSCREEN #define SM_CYFULLSCREEN #define SM_CYKANJIWINDOW #define SM_MOUSEPRESENT #define SM_CYVSCROLL #define SM_CXHSCROLL #define SM_DEBUG #define SM_SWAPBUTTON #define SM_RESERVED1 #define SM_RESERVED2 #define SM_RESERVED3 #define SM_RESERVED4 .#define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define WM_RENDERFORMAT WM_RENDERALLFORMATS WM_DESTROYCLIPBOARD WM_DRAWCLIPBOARD WM_PAINTCLIPBOARD WM_VSCROLLCLIPBOARD WM_SIZECLIPBOARD WM_ASKCBFORMATNAME WM_CHANGECBCHAIN WM_HSCROLLCLIPBOARD WM_QUERYNEWPALETTE WM_PALETTEISCHANGING WM_PALETTECHANGED WM_HOTKEY WM_PRINT WM_PRINTCLIENT WM_HANDHELDFIRST WM_HANDHELDLAST WM_AFXFIRST WM_AFXLAST WM_PENWINFIRST WM_PENWINLAST WM_APP 0x0305 0x0306 0x0307 0x0308 0x0309 0x030A 0x030B 0x030C 0x030D 0x030E 0x030F 0x0310 0x0311 0x0312 0x0317 0x0318 0x0358 0x035F 0x0360 0x037F 0x0380 0x038F 0x8000 0x0001 0x0002 0x0001 0x0002 0x0004 0x0008 0x0010 0x0020 0x0040 0x0800 0x8000 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // // // // // // // // // mouse move left button down left button up right button down right button up middle button down middle button up wheel button rolled absolute move //---.keybd_event routines #define KEYEVENTF_EXTENDEDKEY #define KEYEVENTF_KEYUP //---. AnimateWindow() Commands #define AW_HOR_POSITIVE #define AW_HOR_NEGATIVE #define AW_VER_POSITIVE #define AW_VER_NEGATIVE #define AW_CENTER 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 67 68 69 70 71 // Use instead of 72 73 74 75 76 77 78 79 80 81 0 1 2 3 4 5 0x00000001 0x00000002 0x00000004 0x00000008 0x00000010 .#define SM_CXMIN #define SM_CYMIN #define SM_CXSIZE #define SM_CYSIZE #define SM_CXFRAME #define SM_CYFRAME #define SM_CXMINTRACK #define SM_CYMINTRACK #define SM_CXDOUBLECLK #define SM_CYDOUBLECLK #define SM_CXICONSPACING #define SM_CYICONSPACING #define SM_MENUDROPALIGNMENT #define SM_PENWINDOWS #define SM_DBCSENABLED #define SM_CMOUSEBUTTONS #define SM_SECURE #define SM_CXEDGE #define SM_CYEDGE #define SM_CXMINSPACING #define SM_CYMINSPACING #define SM_CXSMICON #define SM_CYSMICON #define SM_CYSMCAPTION #define SM_CXSMSIZE #define SM_CYSMSIZE #define SM_CXMENUSIZE #define SM_CYMENUSIZE #define SM_ARRANGE #define SM_CXMINIMIZED #define SM_CYMINIMIZED #define SM_CXMAXTRACK #define SM_CYMAXTRACK #define SM_CXMAXIMIZED #define SM_CYMAXIMIZED #define SM_NETWORK #define SM_CLEANBOOT #define SM_CXDRAG #define SM_CYDRAG #define SM_SHOWSOUNDS #define SM_CXMENUCHECK GetMenuCheckMarkDimensions()! #define SM_CYMENUCHECK #define SM_SLOWMACHINE #define SM_MIDEASTENABLED #define SM_MOUSEWHEELPRESENT #define SM_XVIRTUALSCREEN #define SM_YVIRTUALSCREEN #define SM_CXVIRTUALSCREEN #define SM_CYVIRTUALSCREEN #define SM_CMONITORS #define SM_SAMEDISPLAYFORMAT //---.GetWindow() Constants #define GW_HWNDFIRST #define GW_HWNDLAST #define GW_HWNDNEXT #define GW_HWNDPREV #define GW_OWNER #define GW_CHILD //---. MetaQuotes Software Corp.Dialog Box Command IDs #define IDOK #define IDCANCEL #define IDABORT #define IDRETRY #define IDIGNORE #define IDYES #define IDNO #define IDCLOSE #define IDHELP //+------------------------------------------------------------------+ Scripts //+------------------------------------------------------------------+ //| Period_Converter.metaquotes." #property link "http://www.net | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005.metaquotes. // new period multiplier factor int ExtHandle=-1. MetaQuotes Software Corp.mq4 | //| Copyright © 2005. | //| http://www.MessageBox() Flags #define MB_OK #define MB_OKCANCEL #define MB_ABORTRETRYIGNORE #define MB_YESNOCANCEL #define MB_YESNO #define MB_RETRYCANCEL #define MB_ICONHAND #define MB_ICONQUESTION #define MB_ICONEXCLAMATION #define MB_ICONASTERISK #define MB_USERICON #define MB_ICONWARNING #define MB_ICONERROR #define MB_ICONINFORMATION #define MB_ICONSTOP #define MB_DEFBUTTON1 #define MB_DEFBUTTON2 #define MB_DEFBUTTON3 #define MB_DEFBUTTON4 #define MB_APPLMODAL #define MB_SYSTEMMODAL #define MB_TASKMODAL #define MB_HELP #define MB_NOFOCUS #define MB_SETFOREGROUND #define MB_DEFAULT_DESKTOP_ONLY #define MB_TOPMOST #define MB_RIGHT #define MB_RTLREADING //---.#define #define #define #define AW_HIDE AW_ACTIVATE AW_SLIDE AW_BLEND 0x00010000 0x00020000 0x00040000 0x00080000 0x00000000 0x00000001 0x00000002 0x00000003 0x00000004 0x00000005 0x00000010 0x00000020 0x00000030 0x00000040 0x00000080 MB_ICONEXCLAMATION MB_ICONHAND MB_ICONASTERISK MB_ICONHAND 0x00000000 0x00000100 0x00000200 0x00000300 0x00000000 0x00001000 0x00002000 0x00004000 // Help Button 0x00008000 0x00010000 0x00020000 0x00040000 0x00080000 0x00100000 1 2 3 4 5 6 7 8 9 //---. //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ .net" #property show_inputs #include <WinUser32.mqh> extern int ExtPeriodMultiplier=3. if(time0>=i_time+periodseconds) { i_time=time0/periodseconds. int i_period=Period()*ExtPeriodMultiplier. FileWriteDouble(ExtHandle. i_time*=periodseconds. for(i=start_pos-1. double d_open. i_unused. int i_digits=Digits. FileWriteDouble(ExtHandle. FileWriteInteger(ExtHandle. i_digits.int start() { int i. periodseconds. d_open. if (Low[0]<d_low) d_low=Low[0]. string c_symbol=Symbol(). FileWriteDouble(ExtHandle. } last_fpos=FileTell(ExtHandle). DOUBLE_VALUE). last_volume. d_high. FileWriteString(ExtHandle. i_time*=periodseconds. LONG_VALUE). FileFlush(ExtHandle).write history file periodseconds=i_period*60.i>=0.normalize open time i_time=Time[start_pos]/periodseconds. d_high.cnt=0. d_close=Close[0]. d_close. //---. start_pos=Bars-1. if(ExtHandle < 0) return(-1). MetaQuotes Software Corp. string c_copyright. start_pos.hst".History header int version=400. //---ExtHandle=FileOpenHistory(c_symbol+i_period+". c_symbol. FILE_BIN|FILE_WRITE). LONG_VALUE). i_time. c_copyright. i--) { time0=Time[i]. FileWriteInteger(ExtHandle. 13). last_volume=Volume[i]. time0. i_time. cnt++. //timesign FileWriteInteger(ExtHandle. int hwnd=0. d_low=Low[i]. LONG_VALUE). version. 64).". //---. if(time0>=i_time+periodseconds || i==0) { if(i==0 && time0<i_time+periodseconds) { d_volume+=Volume[0]. FileWriteInteger(ExtHandle. 12). LONG_VALUE). FileWriteDouble(ExtHandle. FileWriteDouble(ExtHandle. 0. d_low=Low[start_pos]. d_high=High[i]. d_low.write history file header c_copyright="(C)opyright 2003. 0. if (High[0]>d_high) d_high=High[0]. d_volume. LONG_VALUE). LONG_VALUE). d_high=High[start_pos]. DOUBLE_VALUE). DOUBLE_VALUE). //---. DOUBLE_VALUE). d_volume. FileWriteInteger(ExtHandle. d_open=Open[i]. //---. d_volume=last_volume. //last_sync FileWriteArray(ExtHandle. i_period. d_low. FileWriteString(ExtHandle. FileWriteInteger(ExtHandle. } . DOUBLE_VALUE). last_fpos. int i_unused[13]. d_close=Close[i]. d_close. d_open=Open[start_pos]. d_volume=Volume[start_pos]. 0. d_low. FileSeek(ExtHandle. last_volume=Volume[0]. d_close=Close[0]. //---. d_close=Close[0]. FileWriteDouble(ExtHandle. d_close. d_high=High[0]. i_time. //---i_time=time0/periodseconds. d_low=Low[0]. d_high. //---." record(s) written").} else { d_volume+=Volume[i]. FileWriteDouble(ExtHandle. . DOUBLE_VALUE).SEEK_SET). FileWriteDouble(ExtHandle. DOUBLE_VALUE). i_time*=periodseconds. } //---FileWriteInteger(ExtHandle. if (Low[i]<d_low) d_low=Low[i]. while(true) { int cur_time=LocalTime(). d_open. d_open=Open[0].check for new rates if(RefreshRates()) { time0=Time[0]. } else { //---. d_high. FileWriteDouble(ExtHandle. Print(cnt. FileWriteDouble(ExtHandle. if (High[i]>d_high) d_high=High[i]. d_low. FileWriteDouble(ExtHandle. FileWriteDouble(ExtHandle. d_close. LONG_VALUE). //---if(hwnd==0) { hwnd=WindowHandle(Symbol(). //---. //---. if (High[0]>d_high) d_high=High[0]. d_open.last_fpos.no. DOUBLE_VALUE). if (High[1]>d_high) d_high=High[1]. DOUBLE_VALUE). if (Low[1]<d_low) d_low=Low[1].is there current bar? if(time0<i_time+periodseconds) { d_volume+=Volume[0]-last_volume. DOUBLE_VALUE). there is new bar d_volume+=Volume[1]-last_volume. d_volume=Volume[0]. FileWriteDouble(ExtHandle. d_volume. i_time. } } FileFlush(ExtHandle). DOUBLE_VALUE). FileWriteDouble(ExtHandle. d_volume. if(hwnd!=0) Print("Chart window detected"). DOUBLE_VALUE). FileWriteDouble(ExtHandle. last_fpos=FileTell(ExtHandle). if (Low[0]<d_low) d_low=Low[0]. DOUBLE_VALUE). FileFlush(ExtHandle).collect incoming ticks int last_time=LocalTime()-5. last_volume=d_volume. d_close=Close[i].i_period). DOUBLE_VALUE).write previous bar remains FileWriteInteger(ExtHandle. DOUBLE_VALUE). LONG_VALUE). " bars=". Time[index].mqh> string line_name="rotating_line". } } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| rotate_text.index. 0.net/" #include <stdlib. OBJ_TEXT.price2. void init() { Print("point = ". Time[10].33324. string object_name1="rotating_text". "rotating_text". ExtHandle=-1. while(IsStopped()==false) { index++. double price.WM_COMMAND. Low[index]-Point*100).fontsize=10. OBJPROP_PRICE1)+Point. OBJ_TRENDBYANGLE. } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void deinit() { if(ExtHandle>=0) { FileClose(ExtHandle). error=GetLastError(). //---price2=High[10]+Point*10. ObjectDelete(object_name1). price2)." #property link "http://www. fontsize). double angle=0. ObjectCreate(object_name1.refresh window not frequently than 1 time in 2 seconds if(hwnd!=0 && cur_time-last_time>=2) { PostMessageA(hwnd.price1.mq4 | //| Copyright © 2004.Bars). | //| http://www. last_time=cur_time. Point. if(error!=0) } //---. MetaQuotes Software Corp. MetaQuotes Software Corp. int error. ObjectsRedraw().} } //---return(0).metaquotes.0. ObjectSetText(object_name1.0). } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void deinit() { ObjectDelete(line_name).metaquotes. } //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { int time2. price=ObjectGet(object_name1. } . index=20. ObjectCreate(line_name. 0.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. 48. price2-Point*50).0-angle. ObjectSet(line_name.Ask. OBJPROP_WIDTH." : ".mq4 | //| Copyright © 2004. //---int ticket=OrderSend(Symbol().price. if(fontsize>48) fontsize=6. OBJPROP_ANGLE. ObjectSet(object_name1. } //---OrderPrint().0. if(GetLastError()==0) { if(MathAbs(price1-price) < Point*50) { Print("price=".OP_BUY. price1). else time2=Time[0].OBJPROP_TIME2)."expert comment". "REMOVED".0) ObjectSet(line_name. "Script".net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. OBJPROP_ANGLE.0. | //| http://www. OBJPROP_PRICE2. Time[index]. . fontsize++.mqh> #include <WinUser32.metaquotes. index). return.net/" #include <stdlib. } } } return(0).215. angle+=3.1.0). } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| trade. double line_angle=360.255. price2+Point*50). ObjectDelete(object_name1). if(line_angle==90. Sleep(5000).ErrorDescription(error)). 0.0) angle=360.metaquotes. ObjectsRedraw().MB_YESNO|MB_ICONQUESTION)!=IDYES) return(1).{ // } ObjectMove(object_name1.CLR_NONE). if(line_angle==270. "Arial". ObjectSetText(object_name1. Sleep(500). MetaQuotes Software Corp. time2=ObjectGet(line_name.0.0) ObjectSet(line_name. OBJPROP_PRICE2.0 && line_angle<270.mqh> //+------------------------------------------------------------------+ //| script "trading for all money" | //+------------------------------------------------------------------+ int start() { //---if(MessageBox("Do you really want to BUY 1. Print("Error = ". line_angle). if(ticket<1) { int error=GetLastError(). fontsize). OBJPROP_FONTSIZE.0)).0-angle. OBJPROP_TIME2.ErrorDescription(error)). ObjectSet(line_name. Print(object_name1. ObjectSet(object_name1. price1=ObjectGetValueByShift(line_name." #property link "http://www.0) time2=Time[index+10]." price1=". if(line_angle>90. ObjectsRedraw(). ObjectSet(line_name. time2).0.00 "+Symbol()+" at ASK price? ". angle*2).0. MetaQuotes Software Corp.3. break. angle/18. RGB(255. price). if(angle>=360. ExtRedBuffer). int counted_bars=IndicatorCounted(). } //+------------------------------------------------------------------+ Templates <expert> type=INDICATOR_ADVISOR description=Accelerator Oscilator separate_window=1 used_buffers=4 <ind> color=Green type=DRAW_HISTOGRAM </ind> <ind> color=Red type=DRAW_HISTOGRAM </ind> </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---.indicator buffers double ExtGreenBuffer[]. } //+------------------------------------------------------------------+ //| Accelerator/Decelerator Oscillator | //+------------------------------------------------------------------+ int start() { int limit.name for DataWindow and indicator subwindow label IndicatorShortName("AC").initialization done return(0). SetIndexDrawBegin(0. SetIndexBuffer(3. //---. SetIndexBuffer(2. . SetIndexBuffer(1. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used#. //---.last counted bar will be recounted if(counted_bars>0) counted_bars--. double ExtRedBuffer[]. ExtMABuffer). ExtGreenBuffer). //---. SetIndexDrawBegin(1. double prev.38). double ExtBuffer[].current.indicator buffers mapping SetIndexBuffer(0. //---.38).check for possible errors if(counted_bars<0) return(-1).drawing settings #indicators_init# //---IndicatorDigits(6). //---.return(0). ExtBuffer). //---. double ExtMABuffer[]. i). for(i=limit-1.0. //---. i++) ExtMABuffer[i]=iMA(NULL.Bars.MODE_SMA. //---.i).dispatch values between 2 buffers bool up=true.34.MODE_SMA. //---. prev=ExtMABuffer[i+1]-ExtBuffer[i+1]. i++) ExtBuffer[i]=iMAOnArray(ExtMABuffer.MODE_SMA.macd counted in the 1-st additional buffer for(int i=0. ExtGreenBuffer[i]=0.PRICE_MEDIAN. i--) { current=ExtMABuffer[i]-ExtBuffer[i].limit=Bars-counted_bars. } } //---.0. } else { ExtGreenBuffer[i]=current. i<limit.done return(0).5. if(current<prev) up=false.PRICE_MEDIAN. ExtRedBuffer[i]=0. if(current>prev) up=true.0.0.i)iMA(NULL.5.0. i<limit.0. i>=0.0. } //+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR description= used_buffers=3 <param> name=JawsPeriod type=int value=13 </param> <param> name=JawsShift type=int value=8 </param> <param> name=TeethPeriod type=int value=8 </param> <param> name=TeethShift type=int value=5 </param> <param> name=LipsPeriod type=int value=5 </param> <param> name=LipsShift type=int value=3 </param> <ind> . if(!up) { ExtRedBuffer[i]=current.signal line counted in the 2-nd additional buffer for(i=0. 0.TeethShift).PRICE_MEDIAN.last counted bar will be recounted if(counted_bars>0) counted_bars--. SetIndexDrawBegin(1. //---. SetIndexShift(2.0.i). double ExtLimeBuffer[].0. int counted_bars=IndicatorCounted().MODE_SMMA. i++) { //---. limit=Bars-counted_bars. double ExtRedBuffer[].3 indicator buffers mapping SetIndexBuffer(0. SetIndexDrawBegin(2. //---. SetIndexShift(1. //---. //---. SetIndexBuffer(1.MODE_SMMA.TeethPeriod.JawsPeriod.0.initialization done return(0). ExtRedBuffer[i]=iMA(NULL.TeethShift+TeethPeriod).done return(0). //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used# //---.i).PRICE_MEDIAN.JawsShift). } //---. } //+------------------------------------------------------------------+ //| Bill Williams' Alligator | //+------------------------------------------------------------------+ int start() { int limit.color=Blue </ind> <ind> color=Red </ind> <ind> color=Lime </ind> </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---.LipsShift+LipsPeriod).line shifts when drawing SetIndexShift(0. //---.MODE_SMMA.ExtLimeBuffer).drawing settings #indicators_init# //---.ma_shift set to 0 because SetIndexShift called abowe ExtBlueBuffer[i]=iMA(NULL.0. ExtLimeBuffer[i]=iMA(NULL. i<limit.indicator buffers double ExtBlueBuffer[].check for possible errors if(counted_bars<0) return(-1). SetIndexBuffer(2.first positions skipped when drawing SetIndexDrawBegin(0.ExtRedBuffer).PRICE_MEDIAN.LipsShift). } . //---.ExtBlueBuffer).JawsShift+JawsPeriod).i).main loop for(int i=0.0.LipsPeriod. //---.//+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR description=Awesome Oscilator separate_window=1 used_buffers=3. } //+------------------------------------------------------------------+ //| Awesome Oscillator | //+------------------------------------------------------------------+ int start() { int limit. i++) ExtMABuffer[i]=iMA(NULL. i>=0. double prev. //---.MODE_SMA. ExtMABuffer). //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used# //---.macd counted in the 1-st additional buffer for(int i=0.check for possible errors if(counted_bars<0) return(-1). SetIndexDrawBegin(1.drawing settings #indicators_init# IndicatorDigits(5).MODE_SMA. //---. SetIndexBuffer(1.0.PRICE_MEDIAN.indicator buffers double ExtGreenBuffer[]. ExtGreenBuffer). int counted_bars=IndicatorCounted().5.0.34. i--) .i)iMA(NULL.indicator buffers mapping SetIndexBuffer(0.current. SetIndexDrawBegin(0.name for DataWindow and indicator subwindow label IndicatorShortName("AO"). //---.34). //---.dispatch values between 2 buffers bool up=true. ExtRedBuffer).0.i). i<limit. double ExtRedBuffer[].PRICE_MEDIAN.0. //---. limit=Bars-counted_bars. for(i=limit-1.initialization done return(0). //---. SetIndexBuffer(2. double ExtMABuffer[].last counted bar will be recounted if(counted_bars>0) counted_bars--. <ind> color=Green type=DRAW_HISTOGRAM </ind> <ind> color=Red type=DRAW_HISTOGRAM </ind> </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---.34). if(current<prev) up=false. } . } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---//---return(0).done return(0). } //+------------------------------------------------------------------+ <expert> type=EXPERT_ADVISOR </expert> #header# #property copyright "#copyright#" #property link "#link#" #extern_variables# //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---//---return(0). } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0). } //+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR </expert> #header# #property copyright "#copyright#" #property link "#link#" current=ExtMABuffer[i].0. prev=ExtMABuffer[i+1].{ } //---. } else { ExtGreenBuffer[i]=current. if(!up) { ExtRedBuffer[i]=current. if(current>prev) up=true.0. ExtGreenBuffer[i]=0. ExtRedBuffer[i]=0. } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { int counted_bars=IndicatorCounted().indicators #indicators_init# //---return(0).#indicator_properties# #extern_variables# #mapping_buffers# //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used# //---. } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0). //---//---return(0). } //+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR separate_window=1 used_buffers=2 <param> type=int name=FastEMA value=12 </param> <param> type=int name=SlowEMA value=26 </param> <param> type=int name=SignalSMA value=9 </param> <ind> color=Silver type=DRAW_HISTOGRAM </ind> <ind> color=Red </ind> </expert> #header# #property copyright "#copyright#" . indicator buffers double ExtSilverBuffer[]. } //+------------------------------------------------------------------+ <expert> type=INDICATOR_ADVISOR separate_window=1 used_buffers=3 <param> name=FastEMA type=int value=12 </param> <param> name=SlowEMA type=int value=26 </param> <param> ."+SignalSMA+")"). SetIndexBuffer(1.indicator buffers mapping SetIndexBuffer(0. //---.MODE_SMA.PRICE_CLOSE.Bars. //---.0. //---.SlowEMA. //---.i). ExtRedBuffer).done return(0).name for DataWindow and indicator subwindow label IndicatorShortName("MACD("+FastEMA+"."+SlowEMA+". limit=Bars-counted_bars.macd counted in the 1-st buffer for(int i=0.drawing settings #indicators_init# //---SetIndexDrawBegin(1.SignalSMA. //---. } //+------------------------------------------------------------------+ //| Moving Averages Convergence/Divergence | //+------------------------------------------------------------------+ int start() { int limit. i++) ExtRedBuffer[i]=iMAOnArray(ExtSilverBuffer.MODE_EMA.PRICE_CLOSE.0. i++) ExtSilverBuffer[i]=iMA(NULL.SignalSMA). i<limit.check for possible errors if(counted_bars<0) return(-1). //---. //---.MODE_EMA.#property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---. IndicatorDigits(5). //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used#. //---.i)iMA(NULL.i). //---.last counted bar will be recounted if(counted_bars>0) counted_bars--.0.FastEMA. i<limit. ExtSilverBuffer).signal line counted in the 2-nd buffer for(i=0.initialization done return(0).0. double ExtRedBuffer[]. int counted_bars=IndicatorCounted().0. SignalSMA. IndicatorDigits(6).MODE_EMA. i++) ExtBuffer[i]=iMAOnArray(ExtMABuffer.check for possible errors if(counted_bars<0) return(-1).indicator buffers double ExtSilverBuffer[].done return(0). //---.FastEMA. i++) ExtSilverBuffer[i]=ExtMABuffer[i]-ExtBuffer[i].macd counted in the 1-st additional buffer for(int i=0. double ExtBuffer[]. i<limit.i)iMA(NULL.i).MODE_SMA.initialization done return(0). //---.name=SignalSMA type=int value=9 </param> <ind> type=DRAW_HISTOGRAM color=Silver </ind> </expert> #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---.indicator buffers mapping SetIndexBuffer(0. //---. } //+------------------------------------------------------------------+ //| Moving Average of Oscillator | //+------------------------------------------------------------------+ int start() { int limit.name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+". i++) ExtMABuffer[i]=iMA(NULL. //---. //---. SetIndexBuffer(2.Bars.i).ExtMABuffer). limit=Bars-counted_bars. //---.PRICE_CLOSE."+SlowEMA+". //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used#.main loop for(i=0. //---. double ExtMABuffer[]. } //+------------------------------------------------------------------+ .last counted bar will be recounted if(counted_bars>0) counted_bars--.ExtSilverBuffer). i<limit.SignalSMA).SlowEMA. //---. i<limit.0. //---.ExtBuffer).MODE_EMA.drawing settings #indicators_init# //---SetIndexDrawBegin(0."+SignalSMA+")").0.signal line counted in the 2-nd additional buffer for(i=0.0. //---.0.0. SetIndexBuffer(1.PRICE_CLOSE. int counted_bars=IndicatorCounted(). case 6: error_string="no connection with trade server". case 3: error_string="invalid trade parameters". //---switch(error_code) { //---. case 8: error_string="too frequent requests". | //| http://www.net/" #property library /* int init() { Print("Init function defined as feature sample"). break. break. } int deinit() { Print("Deinit function defined as feature sample too"). case 5: error_string="old version of the client terminal". MetaQuotes Software Corp. MetaQuotes Software Corp.codes returned from trade server case 0: case 1: error_string="no error". case 2: error_string="common error".metaquotes. break. } //+------------------------------------------------------------------+ Library //+------------------------------------------------------------------+ //| stdlib. break. break. case 7: error_string="not enough rights". . break. } */ //+------------------------------------------------------------------+ //| return error description | //+------------------------------------------------------------------+ string ErrorDescription(int error_code) { string error_string.<expert> type=SCRIPT_ADVISOR </expert> #header# #property copyright "#copyright#" #property link "#link#" #extern_variables# //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { //---//---return(0).net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004.mq4 | //| Copyright © 2004. break." #property link "http://www.metaquotes. case 4: error_string="trade server is busy". case 137: error_string="broker is busy". break. break. break. case 134: error_string="not enough money". break. error_string="invalid account". break. break. case 133: error_string="trade is disabled". break. case 9: case 64: case 65: error_string="malfunctional trade operation". case 129: error_string="invalid price". case 4010: error_string="no memory for array\' string". break. break. break. break. case 4004: error_string="recursive stack overflow". case 138: error_string="requote".break.mql4 errors case 4000: error_string="no error". case 4005: error_string="not enough stack for parameter". case 4003: error_string="no memory for function call stack". case 146: error_string="trade context is busy". //---. break. case 139: error_string="order is locked". case 132: error_string="market is closed". break. case 145: error_string="modification denied because order too close to market". break. case 131: error_string="invalid trade volume". break. . break. break. error_string="account disabled". case 4002: error_string="array index is out of range". case 4013: error_string="zero divide". case 4009: error_string="not initialized string in array". break. case 128: error_string="trade timeout". break. break. case 4012: error_string="remainder from zero divide". case 136: error_string="off quotes". break. case 4011: error_string="too long string". case 130: error_string="invalid stops". break. break. break. case 4007: error_string="no memory for temp string". break. break. break. case 4001: error_string="wrong function pointer". break. break. case 140: error_string="long positions only allowed". break. case 4006: error_string="no memory for parameter string". case 4008: error_string="not initialized string". case 135: error_string="price changed". break. break. case 141: error_string="too many requests". case 4016: error_string="not initialized array". 4102: error_string="too many opened files". case break. 4099: error_string="end of file". case break. break. 4057: error_string="global variables processing error". case break. case break. 4054: error_string="incorrect series array using". break. case break. 4055: error_string="custom indicator error". 4061: error_string="send mail error". case break. case break. case 4018: error_string="cannot load library". case break. break. case break. 4066: error_string="requested history data in update state". 4060: error_string="function is not confirmed". case function". 4105: error_string="no order selected". 4050: error_string="invalid function parameters count". case 4014: error_string="unknown command". case break. case 4019: error_string="cannot call function". case 4017: error_string="dll calls are not allowed". break. case break. break. 4051: error_string="invalid function parameter value".break. case break. . case break. 4065: error_string="array as parameter expected". 4064: error_string="double parameter expected". 4052: error_string="string function internal error". case break. 4100: error_string="some file error". 4104: error_string="incompatible access to a file". case break. case break. case break. 4056: error_string="arrays are incompatible". 4101: error_string="wrong file name". break. case break. 4021: error_string="not enough memory for temp string returned from break. 4053: error_string="some array error". 4062: error_string="string parameter expected". break. case break. 4059: error_string="function is not allowed in testing mode". case 4015: error_string="wrong jump (never generated error)". 4058: error_string="global variable not found". 4103: error_string="cannot open file". case break. case break. case break. 4022: error_string="system is busy (never generated error)". case break. case break. case 4020: error_string="expert function calls are not allowed". case break. 4063: error_string="integer parameter expected". break.0. case 4111: error_string="shorts are not allowed". if(blue_value>255) blue_value=255. break. 10000000000. case 4202: error_string="object is not exist". case 4201: error_string="unknown object property". 1000000000. case 4203: error_string="unknown object type".0. break. case 4206: error_string="no specified subwindow".0.0. green and blue values to color | //+------------------------------------------------------------------+ int RGB(int red_value. blue_value<<=16. else return(false). break. 100000000. break. 10000. } //+------------------------------------------------------------------+ //| right comparison of 2 doubles | //+------------------------------------------------------------------+ bool CompareDoubles(double number1. } //---return(error_string).double number2) { if(NormalizeDouble(number1-number2. break. case 4204: error_string="no object name".int blue_value) { //---. break. default: error_string="unknown error". 10.0. case 4200: error_string="object is already exist". break. 100000000000.0. . } //+------------------------------------------------------------------+ //| up to 16 digits after decimal point | //+------------------------------------------------------------------+ string DoubleToStrMorePrecision(double number. 100. break.0. 1000000. 100000. if(blue_value<0) blue_value=0.0. if(red_value>255) red_value=255. case 4109: error_string="trade is not allowed". 100000000000000. return(red_value+green_value+blue_value). 10000000000000. break.0. if(green_value<0) green_value=0. } //+------------------------------------------------------------------+ //| convert red.check parameters if(red_value<0) red_value=0.break. case 4106: error_string="unknown symbol". 1000.integer2.0. 10000000.0.int green_value.0.0.integer. 1000000000000000. 1000000000000000.int precision) { double rem. //---green_value<<=8.0.0. if(green_value>255) green_value=255. case 4108: error_string="invalid ticket". double DecimalArray[17]={ 1. break. break. case 4107: error_string="invalid price parameter for trade function".0. case 4110: error_string="longs are not allowed".8)==0) return(true). case 4205: error_string="object coordinates error". } //+------------------------------------------------------------------+ //| convert integer to string contained input's hexadecimal notation | //+------------------------------------------------------------------+ string IntegerToHexString(int integer_number) { string hex_string="00000000". } Indicators //+------------------------------------------------------------------+ //| CCI. if(isnegative) retstring="-"+intstring. remstring=rem2+remstring. remstring="".remstring. for(int i=0. //---double p=DecimalArray[precision].0) { isnegative=true. value+'0'). else hex_string=StringSetChar(hex_string.0 }. shift-=4. int value.integer_number).net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 LightSeaGreen //---. i++) { value=(integer_number>>shift)&0x0F. MetaQuotes Software Corp." #property link "http://www. double RelBuffer[]. i++) { integer2=MathFloor(rem/10). if(number<0.buffers double CCIBuffer[].metaquotes. //---. if(precision>16) precision=16. i<8. } //---intstring=DoubleToStr(integer. rem=MathRound((number-integer)*p). int rem2.0). // Print("Parameter for IntegerHexToString is ". i. i<precision. i. | //| http://www. double DevBuffer[]. } integer=MathFloor(number). else retstring=intstring.10000000000000000. string intstring. bool isnegative=false. //---for(int i=0.metaquotes. MetaQuotes Software Corp. return(retstring). } //---return(hex_string). shift=28. rem=integer2. number=-number. rem2=NormalizeDouble(rem-integer2*10.mq4 | //| Copyright © 2004. . if(value<10) hex_string=StringSetChar(hex_string."+remstring.input parameters extern int CCIPeriod=14. //---if(precision<0) precision=0. if(precision>0) retstring=retstring+". (value-10)+'A').net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004.0).retstring. //---.015/CCIPeriod.PRICE_TYPICAL. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name. i--. //---.standard deviations i=Bars-CCIPeriod+1. SetIndexLabel(0.0.CCIPeriod. SetIndexBuffer(2. if(counted_bars>0) limit++. //---return(0).DRAW_LINE).CCIBuffer).double MovBuffer[]. i++) MovBuffer[i]=iMA(NULL.0.0.0.moving average for(i=0.sum. //---. double price. IndicatorBuffers(4). .k. for(i=1.initial zero if(counted_bars<1) { for(i=1. k--. SetIndexBuffer(3. while(k>=i) { price=(High[k]+Low[k]+Close[k])/3. } i=Bars-CCIPeriod+1.i++) CCIBuffer[Bars-i]=0.last counted bar will be recounted int limit=Bars-counted_bars. if(Bars<=CCIPeriod) return(0). IndicatorShortName(short_name). SetIndexBuffer(0.MODE_SMA.indicator lines SetIndexStyle(0. while(i>=0) { sum=0. DevBuffer). RelBuffer). k=i+CCIPeriod-1.CCIPeriod).i++) MovBuffer[Bars-i]=0. mul=0. } DevBuffer[i]=sum*mul.0. while(i>=0) { price=(High[i]+Low[i]+Close[i])/3.i<=CCIPeriod.short_name). //---. sum+=MathAbs(price-MovBuffer[i]). if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1. if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1.0. MovBuffer).i++) DevBuffer[Bars-i]=0.i<=CCIPeriod.i<=CCIPeriod. } //---. for(i=1. //---. SetIndexBuffer(1. } //+------------------------------------------------------------------+ //| Commodity Channel Index | //+------------------------------------------------------------------+ int start() { int i.name for DataWindow and indicator subwindow label short_name="CCI("+CCIPeriod+")".mul.3 additional buffers are used for counting. i<limit. //---SetIndexDrawBegin(0.counted_bars=IndicatorCounted(). //---.i). metaquotes.RelBuffer[i]=price-MovBuffer[i]. //---. MetaQuotes Software Corp. double Chinkou_Buffer[]. SetIndexLabel(1. SetIndexStyle(2.net/" #property indicator_chart_window #property indicator_buffers 7 #property indicator_color1 Red #property indicator_color2 Blue #property indicator_color3 SandyBrown #property indicator_color4 Thistle #property indicator_color5 Lime #property indicator_color6 SandyBrown #property indicator_color7 Thistle //---. double SpanA2_Buffer[]. double SpanB2_Buffer[]. else CCIBuffer[i]=RelBuffer[i]/DevBuffer[i].metaquotes. SetIndexBuffer(2. double SpanB_Buffer[].Tenkan-1).buffers double Tenkan_Buffer[].Tenkan_Buffer). double SpanA_Buffer[].0."Tenkan Sen"). i--.STYLE_DOT). //---int a_begin.DRAW_HISTOGRAM. if(a_begin<Tenkan) a_begin=Tenkan. i--." #property link "http://www.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. SetIndexDrawBegin(1. //---a_begin=Kijun. } //---return(0). //---SetIndexStyle(1. | //| http://www.cci counting i=Bars-CCIPeriod+1. if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1. SetIndexDrawBegin(0. } //---.input parameters extern int Tenkan=9.DRAW_LINE).Kijun_Buffer). extern int Kijun=26.DRAW_LINE). SetIndexBuffer(1.mq4 | //| Copyright © 2004. while(i>=0) { if(DevBuffer[i]==0. extern int Senkou=52.SpanA_Buffer). double Kijun_Buffer[].Kijun-1). } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Ichimoku. .0) CCIBuffer[i]=0. SetIndexLabel(0."Kijun Sen"). //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---SetIndexStyle(0. SetIndexBuffer(0. MetaQuotes Software Corp. } Tenkan_Buffer[i]=(high+low)/2. SetIndexBuffer(5. SpanB2_Buffer[Bars-i]=0.DRAW_LINE.i++) { SpanA_Buffer[Bars-i]=0.STYLE_DOT). SetIndexStyle(5.i++) { SpanB_Buffer[Bars-i]=0.i++) Tenkan_Buffer[Bars-i]=0. SetIndexLabel(4.STYLE_DOT). SetIndexBuffer(4. if(counted_bars>Tenkan) i=Bars-counted_bars-1. SetIndexBuffer(3. low=Low[i].STYLE_DOT). SetIndexDrawBegin(5. while(i>=0) { . for(i=1. SetIndexLabel(6. while(i>=0) { high=High[i]. SetIndexShift(3. SetIndexDrawBegin(3. SetIndexLabel(2.k. SetIndexBuffer(6. int counted_bars=IndicatorCounted().Kijun). } } //---.i<=a_begin. SetIndexShift(2.DRAW_HISTOGRAM.Kijun+Senkou-1). //---SetIndexStyle(4. for(i=1.i<=Senkou. SetIndexLabel(5. SetIndexStyle(6. SetIndexShift(4."Senkou Span A"). //---if(Bars<=Tenkan || Bars<=Kijun || Bars<=Senkou) return(0).NULL). k--.i<=Tenkan.-Kijun).Tenkan Sen i=Bars-Tenkan."Chinkou Span").low.SpanB2_Buffer).price.i++) Kijun_Buffer[Bars-i]=0. if(high<price) high=price. } for(i=1. if(low>price) low=price.SetIndexDrawBegin(2. //---. SpanA2_Buffer[Bars-i]=0.DRAW_LINE). } //+------------------------------------------------------------------+ //| Ichimoku Kinko Hyo | //+------------------------------------------------------------------+ int start() { int i. price=Low[k].i<=Kijun.SpanA2_Buffer). SetIndexLabel(3.SpanB_Buffer).Kijun).Kijun+Senkou-1).Kijun+a_begin-1). double high. SetIndexShift(6. } //---. k=i-1+Tenkan. while(k>=i) { price=High[k]. SetIndexDrawBegin(6.Kijun).DRAW_LINE. i--. if(counted_bars>Kijun) i=Bars-counted_bars-1.Kijun+a_begin-1).Kijun)."Senkou Span B").Chinkou_Buffer). SetIndexShift(5.initial zero if(counted_bars<1) { for(i=1.Kijun Sen i=Bars-Kijun.NULL). //---return(0). //---SetIndexStyle(3. price=Low[k]. i--. if(counted_bars>a_begin-1) i=Bars-counted_bars-1. low=Low[i]. MetaQuotes Software Corp. if(low>price) low=price. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Custom MACD. if(high<price) high=price. while(i>=0) { Chinkou_Buffer[i]=Close[i]. low=Low[i]. | //| http://www. } //---.indicator buffers high=High[i].net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. i--. } price=(high+low)/2. while(k>=i) { price=High[k]." #property link "http://www. while(i>=0) { high=High[i]. k--. i--.Senkou Span B i=Bars-Senkou.metaquotes. SpanA2_Buffer[i]=price. SpanA_Buffer[i]=price. } Kijun_Buffer[i]=(high+low)/2. price=Low[k]. //---. extern int SlowEMA=26.Chinkou Span i=Bars-1. k--.metaquotes. extern int SignalSMA=9. SpanB_Buffer[i]=price. if(counted_bars>Senkou) i=Bars-counted_bars-1.net/" //---. i--.indicator parameters extern int FastEMA=12.mq4 | //| Copyright © 2004. k=i-1+Kijun. while(i>=0) { price=(Kijun_Buffer[i]+Tenkan_Buffer[i])/2.Senkou Span A i=Bars-a_begin+1. . MetaQuotes Software Corp. if(high<price) high=price. SpanB2_Buffer[i]=price.} //---. while(k>=i) { price=High[k]. } //---. k=i-1+Senkou.indicator settings #property indicator_separate_window #property indicator_buffers 2 #property indicator_color1 Silver #property indicator_color2 Red //---. } //---return(0). if(counted_bars>1) i=Bars-counted_bars-1. if(low>price) low=price. 0.initialization done return(0)."+SignalSMA+")"). ind_buffer2[].indicator buffers mapping if(!SetIndexBuffer(0.signal line counted in the 2-nd buffer for(i=0. i++) ind_buffer1[i]=iMA(NULL.indicator line . } //+------------------------------------------------------------------+ //| Momentum. } //+------------------------------------------------------------------+ //| Moving Averages Convergence/Divergence | //+------------------------------------------------------------------+ int start() { int limit.double double ind_buffer1[].0. //---.macd counted in the 1-st buffer for(int i=0.0.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 DodgerBlue //---. //---.ind_buffer1) && !SetIndexBuffer(1.check for possible errors if(counted_bars<0) return(-1).drawing settings SetIndexStyle(0.i).metaquotes. //---. //---.ind_buffer2)) Print("cannot set indicator buffers!"). //---.i)iMA(NULL.STYLE_SOLID. MetaQuotes Software Corp. MetaQuotes Software Corp.DRAW_HISTOGRAM.mq4 | //| Copyright © 2004.i). //---.MODE_DIGITS)+1). | //| http://www.MODE_EMA.PRICE_CLOSE.PRICE_CLOSE.done return(0).MODE_EMA. //---.SignalSMA."MACD"). int counted_bars=IndicatorCounted().0.Bars. SetIndexLabel(1. i<limit.buffers double MomBuffer[].last counted bar will be recounted if(counted_bars>0) counted_bars--. //---. //---. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---.FastEMA.name for DataWindow and indicator subwindow label IndicatorShortName("MACD("+FastEMA+".net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004.SlowEMA. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name. SetIndexLabel(0. IndicatorDigits(MarketInfo(Symbol()."Signal").MODE_SMA."+SlowEMA+".3).input parameters extern int MomPeriod=14. //---." #property link "http://www. i++) ind_buffer2[i]=iMAOnArray(ind_buffer1.SignalSMA).metaquotes. limit=Bars-counted_bars.0. i<limit. SetIndexDrawBegin(1. SetIndexStyle(0. //---. extern int MA_Shift=0.DRAW_LINE).DRAW_LINE).indicator buffers double ExtMapBuffer[].initial zero if(counted_bars<1) for(i=1. //---. draw_begin=MA_Period-1. //---int ExtCountedBars=0. MetaQuotes Software Corp.net/" #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Red //---. SetIndexShift(0." #property link "http://www. i--. SetIndexBuffer(0. IndicatorDigits(MarketInfo(Symbol(). while(i>=0) { MomBuffer[i]=Close[i]*100/Close[i+MomPeriod].MomBuffer). extern int MA_Method=0.MA_Shift). //---i=Bars-MomPeriod-1.metaquotes.i<=MomPeriod.indicator parameters extern int MA_Period=13.MomPeriod). IndicatorShortName(short_name).drawing settings SetIndexStyle(0. if(MA_Period<2) MA_Period=13. //---.name for DataWindow and indicator subwindow label short_name="Mom("+MomPeriod+")". } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Custom Moving Average.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004.counted_bars=IndicatorCounted().mq4 | //| Copyright © 2004. //---if(Bars<=MomPeriod) return(0).i++) MomBuffer[Bars-i]=0. //---return(0). MetaQuotes Software Corp.short_name). //---. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { int draw_begin. | //| http://www. //---. //---SetIndexDrawBegin(0. string short_name. } //+------------------------------------------------------------------+ //| Momentum | //+------------------------------------------------------------------+ int start() { int i. } return(0).0.MODE_DIGITS)).indicator short name . SetIndexLabel(0. if(counted_bars>=MomPeriod) i=Bars-counted_bars-1. sum-=Close[pos+MA_Period-1]. //---switch(MA_Method) { case 0 : sma().i++.i<MA_Period. //---. case 3 : short_name="LWMA(". } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { if(Bars<=MA_Period) return(0). //---.done return(0). } //+------------------------------------------------------------------+ //| Exponential Moving Average | //+------------------------------------------------------------------+ void ema() { double pr=2. break. short_name="SMA(".check for possible errors if (ExtCountedBars<0) return(-1).0/(MA_Period+1). case 1 : ema(). } //---. SetIndexDrawBegin(0. break. } //+------------------------------------------------------------------+ //| Simple Moving Average | //+------------------------------------------------------------------+ void sma() { double sum=0. default : MA_Method=0. break. break.initial accumulation if(pos<MA_Period) pos=MA_Period. //---. int i.main calculation loop while(pos>=0) { sum+=Close[pos]. ExtCountedBars=IndicatorCounted().i++) ExtMapBuffer[Bars-i]=0.pos--) sum+=Close[pos].last counted bar will be recounted if (ExtCountedBars>0) ExtCountedBars--. } //---.ExtMapBuffer).zero initial bars if(ExtCountedBars<1) for(i=1. ExtMapBuffer[pos]=sum/MA_Period. //---. //---. draw_begin=0. break.switch(MA_Method) { case 1 : short_name="EMA(".pos=Bars-ExtCountedBars-1. case 2 : short_name="SMMA(". case 3 : lwma(). .initialization done return(0). for(i=1. break. case 2 : smma(). } IndicatorShortName(short_name+MA_Period+")"). //---.draw_begin). pos--.indicator buffers mapping SetIndexBuffer(0.i<MA_Period. i=pos+MA_Period. //---.k++) { sum+=Close[k]. ExtMapBuffer[pos]=Close[pos]*pr+ExtMapBuffer[pos+1]*(1-pr). pos--. double price. if(pos==0) break. ExtMapBuffer[pos]=sum/MA_Period. while(pos>=0) { if(pos==Bars-MA_Period) { //---.0. lsum+=price.i++.main calculation loop pos=Bars-MA_Period.main calculation loop while(pos>=0) { if(pos==Bars-2) ExtMapBuffer[pos+1]=Close[pos+1]. int i.lsum=0. while(pos>=0) { ExtMapBuffer[pos]=sum/weight. if(pos>Bars-ExtCountedBars) pos=Bars-ExtCountedBars. } } //+------------------------------------------------------------------+ //| Linear Weighted Moving Average | //+------------------------------------------------------------------+ void lwma() { double sum=0.k=pos.k.i++. if(ExtCountedBars>2) pos=Bars-ExtCountedBars-1.i<MA_Period. i--. //---.int pos=Bars-2. sum=sum-lsum+price*MA_Period.main calculation loop pos++. lsum+=price. pos--. price=Close[pos].pos--) { price=Close[pos]. .i<=MA_Period.0. for(i=1. pos--. } } else sum=ExtMapBuffer[pos+1]*(MA_Period-1)+Close[pos]. //---. int i. } //---. sum+=price*i.initial accumulation for(i=0.weight=0.zero initial bars ExtMapBuffer[k]=0.pos=Bars-ExtCountedBars+1.initial accumulation if(pos<MA_Period) pos=MA_Period. weight+=i.pos=Bars-ExtCountedBars-1. //---. lsum-=Close[i]. } } //+------------------------------------------------------------------+ //| Smoothed Moving Average | //+------------------------------------------------------------------+ void smma() { double sum=0. | //| http://www.drawing settings SetIndexStyle(0. IndicatorBuffers(3).DRAW_HISTOGRAM. IndicatorDigits(MarketInfo(Symbol().i).3).metaquotes. //---.mq4 | //| Copyright © 2004. i++) ind_buffer3[i]=iMAOnArray(ind_buffer2.PRICE_CLOSE. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| OsMA.SlowEMA.MODE_EMA.indicator parameters extern int FastEMA=12. extern int SlowEMA=26.ind_buffer2) && !SetIndexBuffer(2. i++) ind_buffer2[i]=iMA(NULL.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. i<limit. //---." #property link "http://www.0. //---. SetIndexDrawBegin(0.SignalSMA. //---.0. double ind_buffer3[]. } //+------------------------------------------------------------------+ //| Moving Average of Oscillator | //+------------------------------------------------------------------+ int start() { int limit. extern int SignalSMA=9.i++) ExtMapBuffer[Bars-i]=0.STYLE_SOLID.i)iMA(NULL.0."+SlowEMA+".indicator buffers double ind_buffer1[].PRICE_CLOSE. //---.SignalSMA). //---. //---. double ind_buffer2[].ind_buffer3)) Print("cannot set indicator buffers!").3 indicator buffers mapping if(!SetIndexBuffer(0. int counted_bars=IndicatorCounted().i). MetaQuotes Software Corp.net/" //---.} //---. //---.zero initial bars if(ExtCountedBars<1) for(i=1.indicator settings #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---.name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+".FastEMA.last counted bar will be recounted if(counted_bars>0) counted_bars--. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---.check for possible errors if(counted_bars<0) return(-1).macd counted in the 1-st additional buffer for(int i=0.0.metaquotes.MODE_EMA.signal line counted in the 2-nd additional buffer for(i=0.MODE_SMA.initialization done return(0).MODE_DIGITS)+2).Bars. limit=Bars-counted_bars. .2 additional buffers are used for counting.ind_buffer1) && !SetIndexBuffer(1.i<MA_Period. i<limit. MetaQuotes Software Corp."+SignalSMA+")").0. //---. | //| http://www. SetIndexStyle(0.double ep.double sar) { save_lastreverse=last. bool dirlong.2.last_low. MetaQuotes Software Corp.//---. //---int save_lastreverse." #property link "http://www. save_start=start.last_high. double start.main loop for(i=0. MetaQuotes Software Corp. save_last_low=low. double save_last_high.done return(0). } //+------------------------------------------------------------------+ //| Parabolic Sell And Reverse system | //+------------------------------------------------------------------+ int start() { static bool first=true. //---. SetIndexBuffer(0. .int dir.159). i<limit. SetIndexArrow(0.double high. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Parabolic. bool save_dirlong. //---return(0).indicators IndicatorDigits(Digits). double save_start. //---.buffers double SarBuffer[].net/" #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Lime //---.double start. double save_sar.double low. double save_ep.metaquotes. double save_last_low. extern double Maximum=0. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---.DRAW_ARROW).SarBuffer). save_last_high=high. save_dirlong=dir.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void SaveLastReverse(int last. i++) ind_buffer1[i]=ind_buffer2[i]-ind_buffer3[i]. save_sar=sar. save_ep=ep.input parameters extern double Step=0.02.mq4 | //| Copyright © 2004. double ep,sar,price_low,price_high,price; int i,counted_bars=IndicatorCounted(); //---if(Bars<3) return(0); //---- initial settings i=Bars-2; if(counted_bars==0 || first) { first=false; dirlong=true; start=Step; last_high=-10000000.0; last_low=10000000.0; while(i>0) { save_lastreverse=i; price_low=Low[i]; if(last_low>price_low) last_low=price_low; price_high=High[i]; if(last_high<price_high) last_high=price_high; if(price_high>High[i+1] && price_low>Low[i+1]) break; if(price_high<High[i+1] && price_low<Low[i+1]) { dirlong=false; break; } i--; } //---- initial zero int k=i; while(k<Bars) { SarBuffer[k]=0.0; k++; } //---- check further if(dirlong) { SarBuffer[i]=Low[i+1]; ep=High[i]; } else { SarBuffer[i]=High[i+1]; ep=Low[i]; } i--; } else { i=save_lastreverse+1; start=save_start; dirlong=save_dirlong; last_high=save_last_high; last_low=save_last_low; ep=save_ep; sar=save_sar; } //---while(i>=0) { price_low=Low[i]; price_high=High[i]; //--- check for reverse if(dirlong && price_low<SarBuffer[i+1]) { SaveLastReverse(i,true,start,price_low,last_high,ep,sar); start=Step; dirlong=false; ep=price_low; last_low=price_low; SarBuffer[i]=last_high; i--; continue; } if(!dirlong && price_high>SarBuffer[i+1]) { SaveLastReverse(i,false,start,last_low,price_high,ep,sar); start=Step; dirlong=true; ep=price_high; last_high=price_high; SarBuffer[i]=last_low; i--; continue; } //--price=SarBuffer[i+1]; sar=price+start*(ep-price); if(dirlong) { if(ep<price_high && (start+Step)<=Maximum) start+=Step; if(price_high<High[i+1] && i==Bars-2) sar=SarBuffer[i+1]; price=Low[i+1]; if(sar>price) sar=price; price=Low[i+2]; if(sar>price) sar=price; if(sar>price_low) { SaveLastReverse(i,true,start,price_low,last_high,ep,sar); start=Step; dirlong=false; ep=price_low; last_low=price_low; SarBuffer[i]=last_high; i--; continue; } if(ep<price_high) { last_high=price_high; ep=price_high; } } else { if(ep>price_low && (start+Step)<=Maximum) start+=Step; if(price_low<Low[i+1] && i==Bars-2) sar=SarBuffer[i+1]; } SarBuffer[i]=sar; i--; price=High[i+1]; if(sar<price) sar=price; price=High[i+2]; if(sar<price) sar=price; if(sar<price_high) { SaveLastReverse(i,false,start,last_low,price_high,ep,sar); start=Step; dirlong=true; ep=price_high; last_high=price_high; SarBuffer[i]=last_low; i--; continue; } if(ep>price_low) { last_low=price_low; ep=price_low; } } // sar=SarBuffer[0]; // price=iSAR(NULL,0,Step,Maximum,0); // if(sar!=price) Print("custom=",sar," SAR=",price," counted=",counted_bars); // if(sar==price) Print("custom=",sar," SAR=",price," counted=",counted_bars); //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| RSI.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_minimum 0 #property indicator_maximum 100 #property indicator_buffers 1 #property indicator_color1 DodgerBlue //---- input parameters extern int RSIPeriod=14; //---- buffers double RSIBuffer[]; double PosBuffer[]; double NegBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 2 additional buffers are used for counting. IndicatorBuffers(3); SetIndexBuffer(1,PosBuffer); SetIndexBuffer(2,NegBuffer); //---- indicator line SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,RSIBuffer); //---- name for DataWindow and indicator subwindow label short_name="RSI("+RSIPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---SetIndexDrawBegin(0,RSIPeriod); //---return(0); } //+------------------------------------------------------------------+ //| Relative Strength Index | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); double rel,negative,positive; //---if(Bars<=RSIPeriod) return(0); //---- initial zero if(counted_bars<1) for(i=1;i<=RSIPeriod;i++) RSIBuffer[Bars-i]=0.0; //---i=Bars-RSIPeriod-1; if(counted_bars>=RSIPeriod) i=Bars-counted_bars-1; while(i>=0) { double sumn=0.0,sump=0.0; if(i==Bars-RSIPeriod-1) { int k=Bars-2; //---- initial accumulation while(k>=i) { rel=Close[k]-Close[k+1]; if(rel>0) sump+=rel; else sumn-=rel; k--; } positive=sump/RSIPeriod; negative=sumn/RSIPeriod; } else { //---- smoothed moving average } //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Stochastic.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_minimum 0 #property indicator_maximum 100 #property indicator_buffers 2 #property indicator_color1 LightSeaGreen #property indicator_color2 Red //---- input parameters extern int KPeriod=5; extern int DPeriod=3; extern int Slowing=3; //---- buffers double MainBuffer[]; double SignalBuffer[]; double HighesBuffer[]; double LowesBuffer[]; //---int draw_begin1=0; int draw_begin2=0; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 2 additional buffers are used for counting. IndicatorBuffers(4); SetIndexBuffer(2, HighesBuffer); SetIndexBuffer(3, LowesBuffer); //---- indicator lines SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0, MainBuffer); SetIndexStyle(1,DRAW_LINE); SetIndexBuffer(1, SignalBuffer); //---- name for DataWindow and indicator subwindow label short_name="Sto("+KPeriod+","+DPeriod+","+Slowing+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); SetIndexLabel(1,"Signal"); //---draw_begin1=KPeriod+Slowing; draw_begin2=draw_begin1+DPeriod; SetIndexDrawBegin(0,draw_begin1); } PosBuffer[i]=positive; NegBuffer[i]=negative; if(negative==0.0) RSIBuffer[i]=0.0; else RSIBuffer[i]=100.0-100.0/(1+positive/negative); i--; rel=Close[i]-Close[i+1]; if(rel>0) sump=rel; else sumn=-rel; positive=(PosBuffer[i+1]*(RSIPeriod-1)+sump)/RSIPeriod; negative=(NegBuffer[i+1]*(RSIPeriod-1)+sumn)/RSIPeriod; SetIndexDrawBegin(1,draw_begin2); //---return(0); } //+------------------------------------------------------------------+ //| Stochastic oscillator | //+------------------------------------------------------------------+ int start() { int i,k; int counted_bars=IndicatorCounted(); double price; //---if(Bars<=draw_begin2) return(0); //---- initial zero if(counted_bars<1) { for(i=1;i<=draw_begin1;i++) MainBuffer[Bars-i]=0; for(i=1;i<=draw_begin2;i++) SignalBuffer[Bars-i]=0; } //---- minimums counting i=Bars-KPeriod; if(counted_bars>KPeriod) i=Bars-counted_bars-1; while(i>=0) { double min=1000000; k=i+KPeriod-1; while(k>=i) { price=Low[k]; if(min>price) min=price; k--; } LowesBuffer[i]=min; i--; } //---- maximums counting i=Bars-KPeriod; if(counted_bars>KPeriod) i=Bars-counted_bars-1; while(i>=0) { double max=-1000000; k=i+KPeriod-1; while(k>=i) { price=High[k]; if(max<price) max=price; k--; } HighesBuffer[i]=max; i--; } //---- %K line i=Bars-draw_begin1; if(counted_bars>draw_begin1) i=Bars-counted_bars-1; while(i>=0) { double sumlow=0.0; double sumhigh=0.0; for(k=(i+Slowing-1);k>=i;k--) { sumlow+=Close[k]-LowesBuffer[k]; sumhigh+=HighesBuffer[k]-LowesBuffer[k]; } if(sumhigh==0.0) MainBuffer[i]=100.0; else MainBuffer[i]=sumlow/sumhigh*100; i--; int limit=Bars-counted_bars. //---.initialization done return(0). back.signal line is simple movimg average for(i=0.drawing settings SetIndexStyle(0. if((Low[shift]-val)>(ExtDeviation*Point)) val=0. //---. //---.metaquotes.ExtDepth.0).0.indicator parameters extern int ExtDepth=12. ArraySetAsSeries(ExtMapBuffer2. MetaQuotes Software Corp.ExtMapBuffer). for(shift=Bars-ExtDepth. else { lastlow=val."+ExtDeviation+".MODE_LOW.0.DPeriod.indicator buffers mapping SetIndexBuffer(0. double ExtMapBuffer2[].lasthigh.net/" #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Red //---."+ExtBackstep+")").Bars.ExtMapBuffer2). extern int ExtDeviation=5.MODE_SMA. shift>=0.lastlowpos. . extern int ExtBackstep=3.true).res. //---return(0). double val.lasthighpos.lastlow. SetIndexEmptyValue(0. SetIndexBuffer(1.indicator short name IndicatorShortName("ZigZag("+ExtDepth+".0. //---.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005.shift)]. i++) SignalBuffer[i]=iMAOnArray(MainBuffer.true). shift--) { val=Low[Lowest(NULL. //---. | //| http://www.DRAW_SECTION).0." #property link "http://www. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Custom Moving Average.last counted bar will be recounted if(counted_bars>0) counted_bars--. MetaQuotes Software Corp. //---. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { IndicatorBuffers(2). ArraySetAsSeries(ExtMapBuffer.i). double curlow.0.curhigh. if(val==lastlow) val=0.metaquotes. i<limit.} //---. } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { int shift.indicator buffers double ExtMapBuffer[].mq4 | //| Copyright © 2005. 0. lastlow=-1.ExtDepth. } //--if((curlow<lastlow)||(lastlow<0)) { lastlow=curlow. . else { for(back=1.else { for(back=1. } // final cutting lasthigh=-1.0.high val=High[Highest(NULL. back++) { res=ExtMapBuffer[shift+back].MODE_HIGH.0. if((res!=0)&&(res>val)) ExtMapBuffer[shift+back]=0.0. } //---if(curlow!=0) { if(lastlow>0) { if(lastlow>curlow) ExtMapBuffer[lastlowpos]=0. } } } ExtMapBuffer[shift]=val. curhigh=ExtMapBuffer2[shift]. back<=ExtBackstep.shift)]. } //--if(lasthigh<curhigh || lasthigh<0) { lasthigh=curhigh. shift>=0. lastlowpos=shift.0. if(val==lasthigh) val=0. } } } ExtMapBuffer2[shift]=val. if((res!=0)&&(res<val)) ExtMapBuffer2[shift+back]=0. else ExtMapBuffer[shift]=0. lasthighpos=-1. back<=ExtBackstep. //--. //--if(curhigh!=0) { if(lasthigh>0) { if(lasthigh<curhigh) ExtMapBuffer2[lasthighpos]=0. shift--) { curlow=ExtMapBuffer[shift]. else ExtMapBuffer2[shift]=0. lasthighpos=shift. lastlowpos=-1. for(shift=Bars-ExtDepth. } lastlow=-1. else { lasthigh=val. if((val-High[shift])>(ExtDeviation*Point)) val=0. back++) { res=ExtMapBuffer2[shift+back]. if((curlow==0)&&(curhigh==0)) continue. double ExtBuffer2[].} lasthigh=-1. SetIndexBuffer(1. SetIndexLabel(1. } } } //+------------------------------------------------------------------+ //| Accelerator. if(res!=0.net/" //---. SetIndexBuffer(4. SetIndexDrawBegin(2. shift--) { if(shift>=Bars-ExtDepth) ExtMapBuffer[shift]=0.ExtBuffer2). SetIndexBuffer(3.38)." #property link "http://www.metaquotes. SetIndexLabel(2. SetIndexDrawBegin(1. else { res=ExtMapBuffer2[shift]. } //+------------------------------------------------------------------+ //| Accelerator/Decelerator Oscillator | //+------------------------------------------------------------------+ int start() .name for DataWindow and indicator subwindow label IndicatorShortName("AC").metaquotes. | //| http://www. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---.initialization done return(0).38). IndicatorBuffers(5).indicator buffers double ExtBuffer0[].indicator settings #property indicator_separate_window #property indicator_buffers 3 #property indicator_color1 Black #property indicator_color2 Green #property indicator_color3 Red //---. //---.DRAW_HISTOGRAM). SetIndexBuffer(2. MetaQuotes Software Corp. SetIndexStyle(1.ExtBuffer0).0) ExtMapBuffer[shift]=res. //---. double ExtBuffer1[].ExtBuffer1).drawing settings SetIndexStyle(0. //---.4 indicator buffers mapping SetIndexBuffer(0. } } for(shift=Bars-1.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005.ExtBuffer4).mq4 | //| Copyright © 2005. IndicatorDigits(Digits+2).2 additional buffers are used for counting. //---.38). double ExtBuffer4[].DRAW_NONE).NULL). SetIndexDrawBegin(0. MetaQuotes Software Corp.NULL). SetIndexStyle(2.ExtBuffer3). shift>=0.DRAW_HISTOGRAM). double ExtBuffer3[].0. double PlusSdiBuffer[].PRICE_MEDIAN. if(current<prev) up=false. //---.int limit. //---. limit=Bars-counted_bars.metaquotes. if(current>prev) up=true.i). } else { ExtBuffer1[i]=current.0.Bars.34. ExtBuffer2[i]=0.dispatch values between 2 buffers bool up=true.MODE_SMA.mq4 | //| Copyright © 2004.input parameters extern int ADXPeriod=14. double MinusSdiBuffer[].i)iMA(NULL.i).metaquotes. | //| http://www. int counted_bars=IndicatorCounted().0. if(!up) { ExtBuffer2[i]=current. MetaQuotes Software Corp.0. i<limit.current.0. i--) { current=ExtBuffer3[i]-ExtBuffer4[i].MODE_SMA. //---.signal line counted in the 2-nd additional buffer for(i=0. double MinusDiBuffer[]. for(i=limit-1." #property link "http://www. { .0.last counted bar will be recounted if(counted_bars>0) counted_bars--.0. } //---. } ExtBuffer0[i]=current. //---. i>=0.done return(0). i++) ExtBuffer4[i]=iMAOnArray(ExtBuffer3.MODE_SMA. IndicatorBuffers(6).5. double PlusDiBuffer[]. prev=ExtBuffer3[i+1]-ExtBuffer4[i+1].0.5.net/" #property indicator_separate_window #property indicator_buffers 3 #property indicator_color1 LightSeaGreen #property indicator_color2 YellowGreen #property indicator_color3 Wheat //---. i++) ExtBuffer3[i]=iMA(NULL.buffers double ADXBuffer[].macd counted in the 1-st additional buffer for(int i=0. i<limit. double TempBuffer[]. ExtBuffer1[i]=0. //---. } //+------------------------------------------------------------------+ //| ADX. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---. double prev.PRICE_MEDIAN.3 additional buffers are used for counting. MetaQuotes Software Corp.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. ADXPeriod). // +DM if(mdm<0) mdm=0.ADXBuffer). //---.counting plus/minus direction if(tr==0) { PlusSdiBuffer[i]=0. } //+------------------------------------------------------------------+ //| Average Directional Movement Index | //+------------------------------------------------------------------+ int start() { double pdm. SetIndexBuffer(4.apply EMA to -DI for(i=0.Bars. SetIndexLabel(0. //---.MinusSdiBuffer). mdm=Low[i+1]-price_low.counted_bars=IndicatorCounted(). . //---i=Bars-2.i).PlusSdiBuffer). tr=MathMax(tr. mdm=0.//---."-DI").âû÷èñëÿåì èñòèííûé èíòåðâàë double num1=MathAbs(price_high-price_low). int starti. //---.indicator buffers SetIndexBuffer(0. SetIndexDrawBegin(2.name for DataWindow and indicator subwindow label IndicatorShortName("ADX("+ADXPeriod+")").TempBuffer). else if(mdm<pdm) mdm=0. double num2=MathAbs(price_high-Close[i+1]).last counted bar will be recounted if(counted_bars>0) counted_bars--. } //---.0*mdm/tr.i.Bars. i<=limit. if(pdm<0) pdm=0. //---pdm=price_high-High[i+1]. MinusSdiBuffer[i+1]=0.num2).apply EMA to +DI for(i=0. SetIndexBuffer(2. //---return(0)."+DI"). SetIndexLabel(1. //---. price_high=High[i].tr. } else if(pdm<mdm) pdm=0. SetIndexLabel(2.ADXPeriod). if(counted_bars>=i) i=Bars-counted_bars-1. MinusSdiBuffer[i]=100.0.price_low.MinusDiBuffer).0*pdm/tr. int limit=Bars-counted_bars. SetIndexBuffer(3. starti=i."ADX").MODE_EMA.0. i++) PlusDiBuffer[i]=iMAOnArray(PlusSdiBuffer. double num3=MathAbs(price_low-Close[i+1]). SetIndexBuffer(1. SetIndexBuffer(5. // -DM if(pdm==mdm) { pdm=0. SetIndexDrawBegin(1.ADXPeriod). PlusSdiBuffer[i+1]=0. } else { PlusSdiBuffer[i]=100. //---. //---while(i>=0) { price_low=Low[i].ADXPeriod. double price_high.num3). i++) MinusDiBuffer[i]=iMAOnArray(MinusSdiBuffer. tr=MathMax(num1.i).PlusDiBuffer).ADXPeriod. //---SetIndexDrawBegin(0. MinusSdiBuffer[i]=0.MODE_EMA.mdm. i<=limit. } //---i--. ExtBlueBuffer). i--.JawsShift).ExtRedBuffer). //---. extern int JawsShift=8. else TempBuffer[i]=100*(MathAbs(PlusDiBuffer[i]-MinusDiBuffer[i])/div). //---.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. MetaQuotes Software Corp. i=starti.TeethShift+TeethPeriod). } //---.Bars. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Alligator. extern int TeethShift=5. .mq4 | //| Copyright © 2004.DRAW_LINE). //---. if(div==0. | //| http://www.Directional Movement (DX) i=Bars-2.MODE_EMA. SetIndexDrawBegin(2. MetaQuotes Software Corp. SetIndexBuffer(2. SetIndexStyle(2.drawing settings SetIndexStyle(0.TeethShift).ExtLimeBuffer). //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---. SetIndexShift(2. extern int TeethPeriod=8.JawsShift+JawsPeriod).0. double ExtLimeBuffer[]. SetIndexDrawBegin(1. //---. SetIndexShift(1.metaquotes. TempBuffer[i+1]=0.DRAW_LINE).indicator buffers double ExtBlueBuffer[]. i<limit.LipsShift+LipsPeriod).first positions skipped when drawing SetIndexDrawBegin(0.DRAW_LINE).index labels SetIndexLabel(0.line shifts when drawing SetIndexShift(0.metaquotes. extern int LipsShift=3. //---. while(i>=0) { double div=MathAbs(PlusDiBuffer[i]+MinusDiBuffer[i]). double ExtRedBuffer[].input parameters extern int JawsPeriod=13." #property link "http://www.//---. SetIndexStyle(1.00) TempBuffer[i]=0.ADX is exponential moving average on DX for(i=0.ADXPeriod. extern int LipsPeriod=5. //---return(0).i).net/" #property indicator_chart_window #property indicator_buffers 3 #property indicator_color1 Blue #property indicator_color2 Red #property indicator_color3 Lime //---."Gator Jaws"). SetIndexBuffer(1.3 indicator buffers mapping SetIndexBuffer(0. i++) ADXBuffer[i]=iMAOnArray(TempBuffer.LipsShift). //---. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Awesome.ExtBuffer2).SetIndexLabel(1. //---.net/" //---. int counted_bars=IndicatorCounted().last counted bar will be recounted if(counted_bars>0) counted_bars--. IndicatorDigits(Digits+1).name for DataWindow and indicator subwindow label .MODE_SMMA.0. //---.mq4 | //| Copyright © 2005.check for possible errors if(counted_bars<0) return(-1).MODE_SMMA. //---.metaquotes. //---.metaquotes. limit=Bars-counted_bars.i). SetIndexDrawBegin(1.ma_shift set to 0 because SetIndexShift called abowe ExtBlueBuffer[i]=iMA(NULL.ExtBuffer1).DRAW_HISTOGRAM).i).0. double ExtBuffer1[].TeethPeriod.34). SetIndexBuffer(2."Gator Teeth"). } //+------------------------------------------------------------------+ //| Bill Williams' Alligator | //+------------------------------------------------------------------+ int start() { int limit. | //| http://www.indicator buffers double ExtBuffer0[].i). //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---.ExtBuffer0). i<limit.PRICE_MEDIAN. ExtLimeBuffer[i]=iMA(NULL. MetaQuotes Software Corp.0. double ExtBuffer2[]. i++) { //---.PRICE_MEDIAN. } //---."Gator Lips").34).DRAW_HISTOGRAM).34). ExtRedBuffer[i]=iMA(NULL.0.done return(0).MODE_SMMA. MetaQuotes Software Corp. SetIndexDrawBegin(0.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005. SetIndexStyle(2. SetIndexDrawBegin(2. SetIndexStyle(1.main loop for(int i=0.DRAW_NONE).indicator settings #property indicator_separate_window #property indicator_buffers 3 #property indicator_color1 Black #property indicator_color2 Green #property indicator_color3 Red //---.initialization done return(0)." #property link "http://www. SetIndexBuffer(1.drawing settings SetIndexStyle(0.0.0.PRICE_MEDIAN.JawsPeriod.3 indicator buffers mapping SetIndexBuffer(0. //---. SetIndexLabel(2.LipsPeriod. int. double prev.last counted bar will be recounted if(counted_bars>0) counted_bars--. double GetDoubleValue(double).int). } else { ExtBuffer1[i]=current.current.dll" int GetIntValue(int).NULL). for(i=limit-1. //---.metaquotes.0.5.PRICE_MEDIAN. MetaQuotes Software Corp. } Samples Includes #import "ExpertSample.34.i). if(current<prev) up=false.0.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005. bool SetArrayItemValue(double& arr[].int.0. i--) { current=ExtBuffer0[i]. | //| http://www. double GetRatesItemValue(double rates[][6]. ExtBuffer2[i]=0.int. i>=0. SetIndexLabel(2. i<limit. Samples Indicators //+------------------------------------------------------------------+ //| ATR. limit=Bars-counted_bars.int).0. //---.PRICE_MEDIAN. //---. SetIndexLabel(1. i++) ExtBuffer0[i]=iMA(NULL.double).int).MODE_SMA. ExtBuffer1[i]=0.macd for(int i=0.0. } } //---. } //+------------------------------------------------------------------+ //| Awesome Oscillator | //+------------------------------------------------------------------+ int start() { int limit.NULL)." .dispatch values between 2 buffers bool up=true. int SortStringArray(string& arr[].0.i)iMA(NULL.int. int ProcessStringArray(string& arr[].done return(0).int. double GetArrayItemValue(double arr[]. prev=ExtBuffer0[i+1]. string GetStringValue(string).initialization done return(0). //---.mq4 | //| Copyright © 2005. if(!up) { ExtBuffer2[i]=current.MODE_SMA. int counted_bars=IndicatorCounted(). if(current>prev) up=true.int).IndicatorShortName("AO"). MetaQuotes Software Corp. i++) AtrBuffer[Bars-i]=0.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 DodgerBlue //---. } i--. TempBuffer[i]=MathMax(high.AtrPeriod.initial zero if(counted_bars<1) for(i=1.prevclose).Bars. SetIndexBuffer(0.counted_bars=IndicatorCounted(). //---.0.1 additional buffer used for counting.#property link "http://www.short_name). //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name.TempBuffer).0. int limit=Bars-counted_bars. if(i==Bars-1) TempBuffer[i]=high-low.AtrPeriod).prevclose)-MathMin(low.i<=AtrPeriod. SetIndexBuffer(1. else { double prevclose=Close[i+1]. IndicatorShortName(short_name). //---SetIndexDrawBegin(0. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ .metaquotes.buffers double AtrBuffer[]. //---if(Bars<=AtrPeriod) return(0). //---. //---. while(i>=0) { double high=High[i]. //---return(0). i++) AtrBuffer[i]=iMAOnArray(TempBuffer. //---return(0). SetIndexLabel(0. for(i=0. i<limit. //---. } //+------------------------------------------------------------------+ //| Average True Range | //+------------------------------------------------------------------+ int start() { int i.AtrBuffer). double low =Low[i].MODE_SMA.DRAW_LINE).input parameters extern int AtrPeriod=14. //---i=Bars-counted_bars-1. IndicatorBuffers(2).indicator line SetIndexStyle(0.name for DataWindow and indicator subwindow label short_name="ATR("+AtrPeriod+")". double TempBuffer[]. //---. } //---if(counted_bars>0) counted_bars--.i). //| Bands.oldval.initial zero if(counted_bars<1) for(i=1. if(counted_bars>BandsPeriod-1) i=Bars-counted_bars-1.DRAW_LINE).mq4 | //| Copyright © 2005. SetIndexStyle(1. //---if(Bars<=BandsPeriod) return(0).MODE_SMA. //---SetIndexDrawBegin(0. //---. double LowerBuffer[].metaquotes. double sum. extern double BandsDeviations=2.BandsPeriod+BandsShift). SetIndexBuffer(0. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---.i++) { MovingBuffer[Bars-i]=EMPTY_VALUE.indicators SetIndexStyle(0." #property link "http://www. //---. UpperBuffer[Bars-i]=EMPTY_VALUE. } //+------------------------------------------------------------------+ //| Bollinger Bands | //+------------------------------------------------------------------+ int start() { int i. i++) MovingBuffer[i]=iMA(NULL. } //---int limit=Bars-counted_bars. //---return(0).UpperBuffer). MetaQuotes Software Corp.buffers double MovingBuffer[].k.i<=BandsPeriod. while(i>=0) { .LowerBuffer).counted_bars=IndicatorCounted(). //---i=Bars-BandsPeriod+1.newres.DRAW_LINE).BandsPeriod.metaquotes. MetaQuotes Software Corp. double deviation.i).indicator parameters extern int BandsPeriod=20. i<limit.net/" #property indicator_chart_window #property indicator_buffers 3 #property indicator_color1 LightSeaGreen #property indicator_color2 LightSeaGreen #property indicator_color3 LightSeaGreen //---. for(i=0.DRAW_LINE).PRICE_CLOSE.MovingBuffer). SetIndexStyle(2. LowerBuffer[Bars-i]=EMPTY_VALUE. double UpperBuffer[].BandsShift. if(counted_bars>0) limit++. SetIndexDrawBegin(1. | //| http://www.0.0. SetIndexBuffer(1. SetIndexBuffer(2.BandsPeriod+BandsShift). SetIndexDrawBegin(2. extern int BandsShift=0.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005.BandsPeriod+BandsShift). } //---return(0). MetaQuotes Software Corp. //---. MetaQuotes Software Corp. LowerBuffer[i]=oldval-deviation.short_name).metaquotes. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Bears. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name. i<limit.1 additional buffer used for counting. while(k>=i) { newres=Close[k]-oldval." #property link "http://www. IndicatorShortName(short_name). SetIndexLabel(0. oldval=MovingBuffer[i].mq4 | //| Copyright © 2005.name for DataWindow and indicator subwindow label short_name="Bears("+BearsPeriod+")". //---if(Bars<=BearsPeriod) return(0). k--. sum+=newres*newres. .indicator line SetIndexStyle(0. k=i+BandsPeriod-1.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005.buffers double BearsBuffer[]. IndicatorBuffers(2). if(counted_bars>0) limit++. SetIndexBuffer(1. //---int limit=Bars-counted_bars. SetIndexBuffer(0. //---..counted_bars=IndicatorCounted(). i--.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---.DRAW_HISTOGRAM).metaquotes. } deviation=BandsDeviations*MathSqrt(sum/BandsPeriod).0. | //| http://www. i++) sum=0. //---. UpperBuffer[i]=oldval+deviation. } //+------------------------------------------------------------------+ //| Bears Power | //+------------------------------------------------------------------+ int start() { int i.BearsBuffer). IndicatorDigits(Digits). double TempBuffer[]. for(i=0. //---return(0).input parameters extern int BearsPeriod=13. //---.TempBuffer). metaquotes.PRICE_CLOSE. SetIndexBuffer(1. while(i>=0) { BearsBuffer[i]=Low[i]-TempBuffer[i].counted_bars=IndicatorCounted(). //---. IndicatorDigits(Digits). //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name.input parameters extern int BullsPeriod=13.1 additional buffer used for counting.mq4 | //| Copyright © 2005. for(i=0.short_name). double TempBuffer[]. //---.0.0.buffers double BullsBuffer[]. i<limit. if(counted_bars>0) limit++. //---return(0). MetaQuotes Software Corp. //---.indicator line SetIndexStyle(0. //---i=Bars-counted_bars-1.metaquotes. IndicatorBuffers(2).TempBuffer[i]=iMA(NULL. | //| http://www.BullsBuffer). .BearsPeriod. //---int limit=Bars-counted_bars.BullsPeriod. IndicatorShortName(short_name).MODE_EMA.MODE_EMA. while(i>=0) { BullsBuffer[i]=High[i]-TempBuffer[i].0." #property link "http://www. //---i=Bars-counted_bars-1. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Bulls.i).net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005.TempBuffer). SetIndexBuffer(0. i--. //---.DRAW_HISTOGRAM). //---if(Bars<=BullsPeriod) return(0).PRICE_CLOSE.name for DataWindow and indicator subwindow label short_name="Bulls("+BullsPeriod+")". } //+------------------------------------------------------------------+ //| Bulls Power | //+------------------------------------------------------------------+ int start() { int i. MetaQuotes Software Corp.i). } //---return(0).0.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---. i++) TempBuffer[i]=iMA(NULL. SetIndexLabel(0. .ExtMapBuffer1).10). ExtMapBuffer2). ExtMapBuffer4).DRAW_HISTOGRAM. SetIndexBuffer(2.On 'Color' Tab select 'Black' for 'Line Graph' | //| . } //---return(0). SetIndexBuffer(3.On 'Common' Tab disable 'Chart on Foreground' checkbox and | //| select 'Line Chart' radiobutton | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. 3. 3. MetaQuotes Software Corp. | //| http://www.ExtMapBuffer2).DRAW_HISTOGRAM. SetIndexBuffer(1. double ExtMapBuffer3[].buffers double ExtMapBuffer1[]. //---.net | //+------------------------------------------------------------------+ //| For Heiken Ashi we recommend next chart settings ( press F8 or | //| select on menu 'Charts'->'Properties. //+------------------------------------------------------------------+ //| Custom indicator initialization function | //|------------------------------------------------------------------| int init() { //---.TODO: add your code here . ExtMapBuffer3). SetIndexBuffer(0. 1. double ExtMapBuffer2[].DRAW_HISTOGRAM. SetIndexDrawBegin(2. SetIndexBuffer(3. Red). SetIndexBuffer(1. SetIndexStyle(2. ExtMapBuffer1). //---int ExtCountedBars=0.metaquotes. SetIndexBuffer(2.10). SetIndexStyle(3. //---.initialization done return(0).10). 0.ExtMapBuffer4)." #property link "http://www. SetIndexDrawBegin(3. Red).indicator buffers mapping SetIndexBuffer(0.mq4 | //| Copyright c 2004.ExtMapBuffer3).i--. 0.net" #property indicator_chart_window #property indicator_buffers 4 #property indicator_color1 Red #property indicator_color2 White #property indicator_color3 Red #property indicator_color4 White //---. SetIndexStyle(1. MetaQuotes Software Corp. 0. 1.metaquotes. SetIndexDrawBegin(1.DRAW_HISTOGRAM.. White). } //+------------------------------------------------------------------+ //| Custom indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---.'): | //| . //---SetIndexDrawBegin(0. 0.10). White).indicators SetIndexStyle(0. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Heiken Ashi. double ExtMapBuffer4[]. if(Bars<=10) return(0).metaquotes. haLow=MathMin(Low[pos]. } //---return(0). MetaQuotes Software Corp. //---if(OrderSelect(0. MathMax(haOpen. haClose=(Open[pos]+High[pos]+Low[pos]+Close[pos])/4. if (haOpen<haClose) { ExtMapBuffer1[pos]=haLow. haClose)).SELECT_BY_POS. } else { ExtMapBuffer1[pos]=haHigh. int pos=Bars-ExtCountedBars-1. MetaQuotes Software Corp. haHigh=MathMax(High[pos]. } //+------------------------------------------------------------------+ Samples Scripts //+------------------------------------------------------------------+ //| close. MathMin(haOpen.first order is buy or sell . ExtMapBuffer2[pos]=haHigh.check for possible errors if (ExtCountedBars<0) return(-1).net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. haLow." #property link "http://www. haHigh. //---. ExtCountedBars=IndicatorCounted(). haClose. int cmd. ExtMapBuffer2[pos]=haLow. pos--.//---return(0). ExtMapBuffer4[pos]=haClose.error.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "close first market order if it is first in the list" | //+------------------------------------------------------------------+ int start() { bool result. double price. | //| http://www.mq4 | //| Copyright © 2004.metaquotes. } ExtMapBuffer3[pos]=haOpen. while(pos>=0) { haOpen=(ExtMapBuffer3[pos+1]+ExtMapBuffer4[pos+1])/2. } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { double haOpen. //---.last counted bar will be recounted if (ExtCountedBars>0) ExtCountedBars--. //---. haClose)).MODE_TRADES)) { cmd=OrderType(). else price=Ask.SELECT_BY_POS.mq4 | //| Copyright © 2004. //---total=OrdersTotal(). } } //---return(0).delete first pending order result=OrderDelete(OrderTicket()). if(result!=TRUE) { error=GetLastError().net/" #property show_confirm if(cmd==OP_BUY || cmd==OP_SELL) { while(true) { if(cmd==OP_BUY) price=Bid. //---.total. break. //---. | //| http://www. | //| http://www. MetaQuotes Software Corp.CLR_NONE). else break. result=OrderClose(OrderTicket(). MetaQuotes Software Corp.net/ | //+------------------------------------------------------------------+ . } } else { Print( "Error when order select ". } else error=0. if(result!=TRUE) Print("LastError = ". i++) { if(OrderSelect(i." #property link "http://www. if(error==135) RefreshRates(). break. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| modify. GetLastError()). //---return(0).3.} else Print( "Error when order select ".metaquotes.mq4 | //| Copyright © 2004. } } //+------------------------------------------------------------------+ //| script "delete first pending order" | //+------------------------------------------------------------------+ int start() { bool result. GetLastError()).metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. int cmd. Print("LastError = ". i<total. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| delete_pending.print selected order OrderPrint(). //---for(int i=0. GetLastError()).price.pending orders only are considered if(cmd!=OP_BUY && cmd!=OP_SELL) { //---. MetaQuotes Software Corp.metaquotes.error).MODE_TRADES)) { cmd=OrderType().OrderLots(). MODE_TRADES)) { //---. //---total=OrdersTotal(). | //| http://www. double price.point. GetLastError()). } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| modify_pending.metaquotes.0.SELECT_BY_POS.CLR_NONE). break.MODE_POINT). int expiration. //---for(int i=0. MetaQuotes Software Corp. } } //---return(0).metaquotes. } } else { Print( "Error when order select ". MetaQuotes Software Corp.#property copyright "Copyright © 2004. else stop_loss=Ask+20*point.point. //---. result=OrderModify(OrderTicket(). cmd=OrderType().stop_loss. if(result==135) RefreshRates().buy or sell orders are considered if(cmd==OP_BUY || cmd==OP_SELL) { //---. MetaQuotes Software Corp. break. //---- . i<total.metaquotes.0. int cmd.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "modify first market order" | //+------------------------------------------------------------------+ int start() { bool result." #property link "http://www. GetLastError()). int cmd.0.modify first market order while(true) { if(cmd==OP_BUY) stop_loss=Bid-20*point.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "modify first pending order" | //+------------------------------------------------------------------+ int start() { bool result. double stop_loss.print modified order (it still selected after modify) OrderPrint(). if(result!=TRUE) Print("LastError = ". i++) { if(OrderSelect(i.mq4 | //| Copyright © 2004.total. else break. } //---.print selected order OrderPrint(). point=MarketInfo(Symbol().total." #property link "http://www. i++) { if(OrderSelect(i.price2. 0.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void deinit() { ObjectDelete(line_name).modify first pending order price=OrderOpenPrice()-10*point. OBJ_TRENDBYANGLE." #property link "http://www.print modified order (it still selected after modify) else OrderPrint(). //---for(int i=0. //---. | //| http://www. result=OrderModify(OrderTicket().price. price2). } } else { Print( "Error when order select ".0.total=OrdersTotal(). //---. if(result!=TRUE) Print("LastError = ".expiration. . //---.net/" #include <stdlib. int error.metaquotes.fontsize=10.print selected order OrderPrint(). point=MarketInfo(Symbol().MODE_TRADES)) { cmd=OrderType().0. MetaQuotes Software Corp.mqh> string line_name="rotating_line". i<total.pending orders only are considered if(cmd!=OP_BUY && cmd!=OP_SELL) { //---. GetLastError()). MetaQuotes Software Corp.price1. break. expiration=OrderExpiration().metaquotes. string object_name1="rotating_text". double angle=0. } } //---return(0). double price.index.MODE_POINT). Time[10]. ObjectCreate(line_name. void init() { Print("point = ". } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| rotate_text. break. Point.Bars).mq4 | //| Copyright © 2004. GetLastError()).0.CLR_NONE). } //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { int time2. //---price2=High[10]+Point*10. ObjectsRedraw()." bars=". ObjectDelete(object_name1).SELECT_BY_POS. net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. OBJPROP_PRICE2. price2+Point*50). if(line_angle==270. ObjectSet(object_name1. if(error!=0) { Print(object_name1. Low[index]-Point*100). else time2=Time[0]. Sleep(500). index).0-angle. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| send_pending. 0. "REMOVED". fontsize). "rotating_text". MetaQuotes Software Corp. Sleep(5000).0)). OBJPROP_ANGLE. if(line_angle==90.ErrorDescription(error)).215.metaquotes. Time[index]." : ". angle+=3.0) ObjectSet(line_name. 0. ObjectCreate(object_name1. Time[index]. OBJPROP_PRICE2.expiration." price1=". price1=ObjectGetValueByShift(line_name.MODE_POINT). expiration=CurTime()+PERIOD_D1*60. OBJPROP_PRICE1)+Point. OBJPROP_WIDTH. ObjectSet(line_name. price). } } } return(0). time2). if(fontsize>48) fontsize=6.index=20. | //| http://www. OBJPROP_FONTSIZE. if(angle>=360. price1).0) angle=360.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "send pending order with expiration data" | //+------------------------------------------------------------------+ int start() { int ticket. fontsize++. double point. RGB(255. price=ObjectGet(object_name1. price2-Point*50). angle/18. . double line_angle=360. line_angle). 48.0. while(IsStopped()==false) { index++. angle*2). break. ObjectSet(line_name. ObjectSet(line_name. fontsize). ObjectsRedraw().0). ObjectsRedraw().OBJPROP_TIME2). MetaQuotes Software Corp. time2=ObjectGet(line_name. OBJ_TEXT. if(GetLastError()==0) { if(MathAbs(price1-price) < Point*50) { Print("price=". ObjectSetText(object_name1.0-angle.price. //---point=MarketInfo(Symbol(). OBJPROP_TIME2.0) ObjectSet(line_name.metaquotes. error=GetLastError().0 && line_angle<270. } ObjectMove(object_name1. ObjectSetText(object_name1.0) time2=Time[index+10].mq4 | //| Copyright © 2004. "Arial". OBJPROP_ANGLE. if(line_angle>90." #property link "http://www. // ObjectDelete(object_name1). ObjectSet(object_name1. 10 seconds wait Sleep(10000).255.net/" #include <sampledll.0.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005.0.metaquotes."some comment".0.ticket). "Script"." #property link "http://www.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004. | //| http://www. return.0. if(ticket<=0) Print("Error = ".metaquotes.1.mq4 | //| Copyright © 2005.OP_BUY.expiration.0. } //---return(0). MetaQuotes Software Corp.metaquotes.net/" #include <stdlib.1."expert comment". | //| http://www. else { Print("ticket = ".GetLastError()).3.mqh> //+------------------------------------------------------------------+ //| script "trading for all money" | //+------------------------------------------------------------------+ int start() { //---if(MessageBox("Do you really want to BUY 1. Print("Error = ". return(0).Bid-100*point.0. } //---. MetaQuotes Software Corp.mqh> #include <WinUser32. } //---OrderPrint(). break.mq4 | //| Copyright © 2004.Green).Ask.CLR_NONE).00 "+Symbol()+" at ASK price? ".//---while(true) { ticket=OrderSend(Symbol().mqh> #define TIME_INDEX 0 #define OPEN_INDEX 1 #define LOW_INDEX 2 #define HIGH_INDEX 3 #define CLOSE_INDEX 4 #define VOLUME_INDEX 5 //+------------------------------------------------------------------+ .0.OP_SELLSTOP. MetaQuotes Software Corp. } //+------------------------------------------------------------------+ Samples Program //+------------------------------------------------------------------+ //| ExportFunctions.metaquotes.MB_YESNO|MB_ICONQUESTION)!=IDYES) return(1).0. MetaQuotes Software Corp. //---int ticket=OrderSend(Symbol().ErrorDescription(error)).16384. if(ticket<1) { int error=GetLastError()." #property link "http://www. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| trade. 6. "second".5. cnt=ProcessStringArray(strarray. //---. "fifth" }. MaCurrent. for(int i=0.strarray[i]). SignalCurrent. ticket. MACDCloseLevel=2. Print("Returned value is ".CLOSE_INDEX). //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { double MacdCurrent. Print("Returned from arr[0] ".strarray[i]). MacdPrevious.1234. 3. } //+------------------------------------------------------------------+ //| array functions call | //+------------------------------------------------------------------+ int start() { double price.7.simple dll-functions call cnt=GetIntValue(some_value). MaPrevious. 5. double SignalPrevious.price).some_value=10. double rates[][6].ArraySize(strarray)). MetaQuotes Software Corp. 2. Print("Returned value is ". //---return(0). //---. MACDOpenLevel=3.price). sret=GetStringValue("some string").5)==true) Print("Changed to ". TrailingStop = 30. //---return(0).1.8. Lots = 0.change second item in the passed array if(SetArrayItemValue(arr.get current close ArrayCopyRates(rates). | //| http://www.".get first item from passed array price=GetArrayItemValue(arr.0. //---.". 4.arr[1]). Print("Returned from Close ".ArraySize(strarray)). Print("Returned value is ". price=GetRatesItemValue(rates.sret).0). MATrendPeriod=26. double arr[5]={1. for(i=0. int cnt.//| expert initialization function | //+------------------------------------------------------------------+ int init() { double ret.5. //---. //---cnt=SortStringArray(strarray. i<cnt.5. "third".9 }.metaquotes. total.ret). string sret. i++) Print(i. int cnt.cnt).Bars.net/ | //+------------------------------------------------------------------+ extern extern extern extern extern extern double double double double double double TakeProfit = 50. } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| MACD Sample." . string strarray[6]={ "first".mq4 | //| Copyright © 2005. i++) Print(i. ret=GetDoubleValue(some_value). .1.5." . i<cnt. "fourth". } return(0).0).MATrendPeriod.PRICE_CLOSE.0)..MODE_TRADES)) Print("BUY order opened : ".MATrendPeriod. if(total<1) { // no opened orders identified if(AccountFreeMargin()<(1000*Lots)) { Print("We have no money. for(cnt=0. SignalCurrent=iMACD(NULL.1).. return(0).OP_SELL. // but it is more important to exit it correctly.26. // check TakeProfit } // to simplify the coding and speed up access // data are put into internal variables MacdCurrent=iMACD(NULL.Lots.SELECT_BY_TICKET.cnt<total. if(ticket>0) { if(OrderSelect(ticket.Bid.// // // // // // initial data checks it is important to make sure that the expert works with a normal chart and the user did not make any mistakes setting external variables (Lots. } // check for short position (SELL) possibility if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious && MacdCurrent>(MACDOpenLevel*Point) && MaCurrent<MaPrevious) { ticket=OrderSend(Symbol().cnt++) .0.3.0. total=OrdersTotal().OrderOpenPrice()). MacdPrevious=iMACD(NULL.MODE_TRADES)) Print("SELL order opened : ".16384.Ask+TakeProfit*Point.GetLastError()). } else Print("Error opening BUY order : ".0).0.Green).0. MaCurrent=iMA(NULL.12. Free Margin = ".12.PRICE_CLOSE.MODE_EMA.Ask."macd sample".0.26. MaPrevious=iMA(NULL. } // it is important to enter the market correctly. we check TakeProfit on a chart of less than 100 bars if(Bars<100) { Print("bars less than 100").12. StopLoss.GetLastError()).9.MODE_SIGNAL. return(0).0.PRICE_CLOSE.9. } else Print("Error opening SELL order : ". TrailingStop) in our case.Bid-TakeProfit*Point.PRICE_CLOSE. TakeProfit.MODE_MAIN.PRICE_CLOSE.SELECT_BY_TICKET. } if(TakeProfit<10) { Print("TakeProfit less than 10").9.OrderOpenPrice()).0.26.MODE_MAIN. return(0).3. return(0).0. SignalPrevious=iMACD(NULL.Lots.0.PRICE_CLOSE."macd sample". } // check for long position (BUY) possibility if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious && MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && MaCurrent>MaPrevious) { ticket=OrderSend(Symbol().0. AccountFreeMargin()).12.1).1).MODE_SIGNAL.26.Red).0.0. if(ticket>0) { if(OrderSelect(ticket.OP_BUY.16384.9.MODE_EMA. return(0). 3. MODE_TRADES).Violet). // exit } // check for trailing stop if(TrailingStop>0) { if((OrderOpenPrice()-Ask)>(Point*TrailingStop)) { if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) { OrderModify(OrderTicket().3.Ask+Point*TrailingStop. SELECT_BY_POS.mq4 | //| Copyright © 2005.net/ | //+------------------------------------------------------------------+ #define MAGICMA 20050610 { . return(0). // close position return(0).Red).OrderLots(). | //| http://www.OrderTakeProfit().OrderLots(). return(0).OrderSelect(cnt. MetaQuotes Software Corp.0.metaquotes.OrderOpenPrice().OrderOpenPrice(). // close position return(0). } } } } else // go to short position { // should it be closed? if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious && MathAbs(MacdCurrent)>(MACDCloseLevel*Point)) { OrderClose(OrderTicket(). } // the end.Green).Bid.Ask.0. } } } } } } return(0).Violet). OrderTakeProfit(). //+------------------------------------------------------------------+ //| Moving Average.BidPoint*TrailingStop. if(OrderType()<=OP_SELL && // check for opened position OrderSymbol()==Symbol()) // check for symbol { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious && MacdCurrent>(MACDCloseLevel*Point)) { OrderClose(OrderTicket(). // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(). calcuulate number of losses orders without a break if(DecreaseFactor>0) { for(int i=orders-1.extern double Lots = 0.sells=0. if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA) { if(OrderType()==OP_BUY) buys++. extern double MaximumRisk = 0.1).return lot size if(lot<0.MODE_TRADES)==false) break. extern double MovingShift = 6. } if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue.return orders volume if(buys>0) return(buys).0). break.MovingPeriod. // history orders total int losses=0. //---.1) lot=0.i<OrdersTotal(). //---. } } //---.get Moving Average ma=iMA(NULL. // number of losses orders without a break //---. } //+------------------------------------------------------------------+ //| Calculate optimal lot size | //+------------------------------------------------------------------+ double LotsOptimized() { double lot=Lots.i--) { if(OrderSelect(i. int res.SELECT_BY_POS.sell conditions if(Open[1]>ma && Close[1]<ma) { .go trading only for first tiks of new bar if(Volume[0]>1) return.0.select lot size lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.1. extern double DecreaseFactor = 3.PRICE_CLOSE.i++) { if(OrderSelect(i. else return(-sells).MovingShift.MODE_HISTORY)==false) { Print("Error in history!").1. } //---. //---if(OrderProfit()>0) break. if(OrderType()==OP_SELL) sells++.MODE_SMA. //---for(int i=0. //---.0.SELECT_BY_POS. if(OrderProfit()<0) losses++. } if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor. return(lot). //---.02. int orders=HistoryTotal().i>=0. } //+------------------------------------------------------------------+ //| Check for open order conditions | //+------------------------------------------------------------------+ void CheckForOpen() { double ma. //+------------------------------------------------------------------+ //| Calculate open positions | //+------------------------------------------------------------------+ int CalculateCurrentOrders(string symbol) { int buys=0.1). extern double MovingPeriod = 12. Ask. } } //---} //+------------------------------------------------------------------+ //| Start function | //+------------------------------------------------------------------+ void start() { //---. } //---.check for history and trading if(Bars<100 || IsTradeAllowed()==false) return.3. if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue.3.0.OrderLots().White). //---.Red).0.MODE_SMA. return. break.go trading only for first tiks of new bar if(Volume[0]>1) return.Blue).MovingPeriod.MovingShift.0. } //---} //+------------------------------------------------------------------+ //| Check for close order conditions | //+------------------------------------------------------------------+ void CheckForClose() { double ma.i++) { if(OrderSelect(i.LotsOptimized().MAGICMA. } if(OrderType()==OP_SELL) { if(Open[1]<ma && Close[1]>ma) OrderClose(OrderTicket().MAGICMA.3.buy conditions if(Open[1]<ma && Close[1]>ma) { res=OrderSend(Symbol().3.res=OrderSend(Symbol().LotsOptimized(). //---.0.0.0.check order type if(OrderType()==OP_BUY) { if(Open[1]>ma && Close[1]<ma) OrderClose(OrderTicket().get Moving Average ma=iMA(NULL.Ask. break.Bid. //---.i<OrdersTotal().PRICE_CLOSE.White).OP_SELL.0.OP_BUY.calculate open orders by current symbol if(CalculateCurrentOrders(Symbol())==0) CheckForOpen().0).SELECT_BY_POS."". else CheckForClose(). return. //---} //+------------------------------------------------------------------+ .Bid. //---for(int i=0."".OrderLots().MODE_TRADES)==false) break. //---.
Copyright © 2024 DOKUMEN.SITE Inc.