Vous êtes sur la page 1sur 78

MetaQuotes Language 4 (MQL4) is a new built -in language for programming of trading strategies.

This language allows to create your own Expert Advisors that make trading management automated and are perfectly suitable for implementing of one's own trade strategies. Besides, one can use MQL4 for creation of one's own Custom Indicators, Scripts, and Libraries. A large amount of functions necessary for analysis of the current and previously inco me quotes, as well as 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 orientate themselves in the expert system text quite easily. We use MetaQuotes Language Dictionary as a Help System for MQL4 language. An abridged 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: y Expert Advisor is a mechanical trading system (M TS) linked up to a certain chart. An Advisor starts to run with every incoming tick for a given symbol. The Advisor will not be launched for a new, tick if it is processing the previous one at this moment (i.e., the Advisor has not completed its operation yet). The Advisor can both inform you about a possibility to trade and trade at an account automatically sending orders directly to the trade server. Like most trading systems, the terminal supports testing strategies on history data with displa ying trading in-and-out points in the chart. Experts are stored in terminal_directory\experts. y Custom Indicator is a technical indicator written independently in addition to those already integrated into the client terminal. Like built -in indicators, they cannot trade automatically and are intended for implementing of analytical functions only. Custom Indicators are stored in terminal_directory\experts\indicators. y Script is a program intended for a single execution of some actions. Unlike Expert Advisors, Scripts are not run tickwise, but on request. Scripts are stored in terminal_dictionary\experts\scripts. y Library is a set of custom functions containing programs most frequently used. Libraries cannot start execution by itself. Libraries are recommended to be stored in terminal_directory\experts\libraries. y Included file is a source text of the most frequently used blocks of custom programs. Such files can be included into the source texts of e xperts, scripts, custom indicators, and libraries at the compiling stage. The use of included files is more preferable than the use of libraries because of additional burden occurring at calling library functions. Included files are recommended to be stored in terminal_directory\experts\include MetaQuotes Language 4 (MQL4) is a new integrated language for programming of trading strategies. This language allows users writing of their own programs (Expert Advisors) that automate trading management and ideally suit for implementing of their own trading strategies . Besides, one can create one's own technical indicators (Custom Indicators), scripts, and libraries in MQL 4. Syntax of MQL4 is much a C-like syntax, apart from some features: y no address arithmetic; y no operator do ... while; y no operator goto ...; y no operation of [condition]?[expression 1]:[expression 2]; y no compound data types (structures); y complex assignments are impossible; for example, val1=val2=0; arr[i++]=val; cond=(cnt=OrdersTotal)>0; etc.; y calculation of a logical expression is always completed, never early terminated. Multiline 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 multiline comments. Comments are allowed where blank spaces ar e possible and tolerate any number of spaces. Examples: // single comment /* multiline // nested single comment comment */ Identifiers are used as names of variables, functions, and data types. The length of an identifier cannot exceed 3 1 character. Symbols you can use: numbers from 0 to 9, Latin capital and small letters a to z, A to Z (recognized as different symbols), t he 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 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 color datetime double int string void Extern Static break case continue default else for if return switch while Any program operates with data. Data can be of different types depending on their purposes. For example, integer data are used to access to array components. Price data belong to those of double precision with floating point. This is related to the fact that no special d ata type is foreseen for price data in MQL 4. false true

Data of different types are processed with d ifferent rates. Integer data are processed at the fastest. To process the double precision data, a special co processor is used. However, because of complicity of internal presentation of data with floating point, they are processed sl ower than the integer ones. String data are processed at the longest because of dynamic computer memory allocation/reallocation. The main data types are: y Integer (int) y Boolean (bool) y Literals (char) y Strings (string) y Floating-point number (double) y Color (color) y Date and time (datetime) The color and datetime types make sense only to facilitate visualization and enter those parameters that had been set from expert advisor property tab or custom indicator "Inputs" tab. The data of color and datetime types are represented as integer values. int and double are called arithmetic (numeric) types. Only implicit type casting is used in expressions. Only implicit type casting is used in MQL 4 expressions. The type priority grows at casting: int (bool,color,datetime); double; string; Before operations (except for the assignment ones) are performed, the data have been conversed into the maximum priority type . Before assignment operations are performed, the data have been cast into the target type. Examples: int i = 1 / 2; // no types casting, the result is 0 int i = 1 / 2.0; // the expression is cast to the double type, then is to the target type of int, the result is 0 double d = 1.0 / 2.0; // no types casting, the result is 0.5 double d = 1 / 2.0; // the expression is cast to the double type that is the same as the target type, the result is 0.5 double d = 1 / 2; // the expression of the int type is cast to the target type of double, the result is 0.0 string s = 1.0 / 8; // the expression is cast to the double type, then is to the target type of string, the result is "0.12 500000" (the string containing 10 characters) string s = NULL; // the constant of type int is cas t to the target type of string, the result is "0" (the string containing 1 character) string s = "Ticket #"+12345; // the expression is cast to the string type that is the same as the target type, the result is "Ticket #12345" Type casting is applied to not only constants, but also variables of corresponding types. Decimals: numbers from 0 to 9; zero must not be the first number. Examples: 12, 111, -956 1007 Hexadecimals: numbers from 0 to 9, letters from a to f or A to F to represent the values 10 to 15; they start with 0x or 0X. Examples: 0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7 Its internal representation is a long 4 -byte integer number. Integer constants can assume values from -2147483648 to 2147483647. If the constant exceeds this range, the result is undefined. 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 ('), do uble 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: int a = 'A'; int b = '$'; int c = ''; // code 0xA9 int d = '\xAE'; // symbol code Its internal representation is a long 4 -byte integer number. Literal constants can assume values from 0 to 255. If the constant exceeds this given range, the result is undefined. Boolean constants may have the value of true or false, numeric representation of them is 1 or 0, respectively. True or TRUE, False or FALSE can be used, as well. Examples: bool a = true; bool b = false; bool c = 1; Its internal representation is a long 4 -byte integer number. Boolean constants can assume the values of 0 or 1. Floating-point constants consist of an integer part, a point (.), and a fractional part. The integer and the fractional part s represent sequences of decimal numbers. Examples: double a = 12.111; double b = -956.1007; double c = 0.0001; double d = 16; Its internal representation is a double -precision number of 8 bytes. Floating -point constants can assume values from -1.7 * e-308 to 1.7 * e308. If a constant exceeds this range, the result is undefined. String constant is a sequence 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. If there is a need to insert a double quote (") into the string, a reverse slash (\) must be put before it. Any special character constants can be inserted into the string 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 will be rejected, and compiler will alert correspondingly. Examples: "This is a character string" "Copyright symbol \t\xA9" "this line contains a line feed symbol \n" "C:\\Program Files\\MetaTrader 4" "A" "1234567890" "0" "$" Its internal representation is a structure of 8 bytes. The first element of the structure is a long integer that contains the size of the buffer distributed for the line. The second element of the structure is 32 -order address of the buffer that contains the line. Color constants can be represented in three ways: litera lly, by integers, or by name (for named Web colors only). Literal representation consists of three parts representing numerical rate values of three main color components: red, green, blue. The constant starts with C and is enclosed in single quotes. Numer ical 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 whe re 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 a 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 Its internal representation is a long integer number of 4 bytes. The first byte will not be considered. The other three bytes contain RGB components. Datetime constants can be represented as a literal line consisting of 6 parts for values of year, month, date, hours, minutes, and seconds. The constant is enclosed in single quotes and starts with D. Either date (year, month, date) or time (hours, minutes, seconds), or both can b e skipped. Datetime constant can vary from Jan 1, 1970 to Dec 3 1, 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' Its internal representation is a long integer number of 4 bytes. The value represents the amount of seconds elapse from 00:00 Jan 1, 1970. Some characters and character sequences are of a special importance. These are so -called operation symbols, for example: + - * / % symbols of arithmetic operations && || symbols of logic operations = += *= symbols of assignment operations Operation symbols are used in expressions and have sense when appopriate operands are given them Punctuation marks are emphasized, as well. These are parentheses, braces, comma, colon, and semicolon. Operation symbols, punctuation marks, spaces are used to separate langua ge elements from each other. An expression consists of one or more operands and operation characters. An expression can be written in several lines. Examples: a++; b = 10; x = (y * z) / (w + 2) + 127; An expression that ends with a semicolon (;) is an operator. Arithmetical operations include additive and multiplicative 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 (increment/decrement) cannot be used in expressions. Examples: int a=3; a++; // valid expression int b=(a++)*3; // invalid expression The value of the expression that includes the given operation is the value of the lef t operand after assignment. Assigning the y value to the x variable y = x; The following operations unite arithmetic or bitwise operations with operation of assignment: 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 of x and y binary notations y ^= x; There can be only one operation of assignment in an expression. Bitwise operations are performed with integer numbers only. T he 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 to 31 bit. By % = operation (y value by module of x), the result sign is equal to the sign of divided number. 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. 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. Complement of the variable value up to one. The value of the expression contains 1 in all digits where n contains 0, and it c ontains 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 a logical one, i.e., the freed left -side bits will be filled with zeros. x = x >> y; The binary-coded representation of x is shifted to the right by y digits, the freed digits on the right will b e filled with zeroes. 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 do not contain zero; and it contains 0 (FALSE) in all other digits. b = ((x & y) != 0); Bitwise operation OR of binary-coded x and y representations. The expression value contains 1 in all digits where x or y is not equal to 0, and it contains 0 in all other digits. b = x | y; Bitwise operation EXCLUSIVE OR of binary-coded x and y representations. The expression value contains 1 in all digits where x and y have different binary values, and it contains 0 in all other digits. b = x ^ y; Bitwise operations are executed with integers only. Indexing At addressing to the i-th element of array, the expression value is the value of the variable with serial number of i. Example: array[i] = 3; //Assign the value of 3 to the i -th element of the array. Only an integer can be index of an array. Four -dimensional and below arrays are allowed. Each me asurement is indexed from 0 to measurement size-1. In particular case, for a one-dimensional array consisting of 50 elements, the reference to the first element will look like array[0], that to the the last element will array[49]. At access beyond the array, the executing subsystem will generate the error of ERR_ARRAY_INDEX_OUT_OF_RANGE that can be got through the GetLastError() function. Call for function with x1,x2,...,xn arguments. Each argument can represent a constant, a variable, or an expression of the corresponding type. The arguments passed are sepa rated by commas and must be inside of parentheses, the opening parenthesis to follow the name of t he called function. The expression value is the value returned by the function. If the returned value is of the void type, such function call can not be placed to the right in the assignment operation. Please make sure that the expressions x1,x2,...,xn are executed exactly in this order. Example: double SL=Bid-25*Point; int ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,SL,Ask+25*Point,"My comment",123,0,Red); Comma operation Expressions separated by commas are executed from left to right. All side effects of the left expression calculation can appear before the right expression is calculated. The result type and value coincide with those of the right expression. The list of parameters to be passed (se e above) can be considered as an example. Example: for(i=0,j=99; i<100; i++,j--) Print(array[i][j]);

Each group of operations in the table has the same priority. The higher is the priority, the higher is the position of the gr oup in the table. The precedence rules determine the grouping of operations and operands. () Function call From left to right [] Referencing to an array element ! Logical negation From right to left - Sign changing operation ++ Increment -- Decrement ~ Bitwise negation (complement) & Bitwise operation AND From left to right | Bitwise operation OR ^ Bitwise operation exclusive OR << Left shift >> Right shift * Multiplication From left to right / Division % Module division + Addition From left to right - Subtraction < Less than From left to right <= Less than or equal > Greater than >= Greater than or equal == Equal != Not equal || Logical OR From left to right && Logical AND 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 Parentheses that have higher priority are applied to change the execution order of the operations. Attention: Priority of performing operations in MQL4 differs to some extent from that conventional in the C language. Language operators describe some algorithmic operations that must be executed to accomplish a task. The program body is a sequence of such operators. Operators following one by one are separated with a semicolon. One operator can occupy one or several lines. Two or more operators can be located in the same line. Operators that control over the execution order (if, if-else, switch, while and for) can be nested into each other. Example: if(Month() == 12) if(Day() == 31) Print("Happy New Year!"); A compound operator (a block) consists of one or more operators of any type enclosed in braces {}. The closing brace must not be followed by a semicolon (;). Example: if(x==0) { Print("invalid position x=",x); return; } Any expression followed by a semicolon (;) is an operator. Here are some examples of expression operators: Assignment operator: Identifier=expression; x=3; y=x=3; // error Assignment operator can be used in an expression only once. Function call operator: Function_name(argument1,..., argumentN); FileClose(file); Empty operator It consists of a semicolon (;) only and used to denote a null body of a control operator. A break operator terminates the execution of the nearest nested outward switch, while, or for operator. 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 for the first zero element for(i=0;i<array_size;i++) if((array[i]==0) break;

A continue operator gives control to the beginning of the nearest outward cycle while or for operator, the next iteration being called. The purpose of this operator is opposite to that of break operator. 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); } 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 with result transmission. The operator expression must be enclosed in parentheses a nd should not contain an assignment operator. Example: int CalcSum(int x, int y) { return(x+y); } In functions with the value of void type to be returned, the return operator must be used without the expression: void SomeFunction() { Print("Hello!"); return; // this operator can be deleted } The right brace of the function means implicit execution of the return operator without expression. 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. if (expression) operator1 else operator2 The else part of the if operator can be omitted. Thus, a divergence may appear in nested if operators with omitted else part. In this case, else addresses to the nearest previous if operator in the same block that has no else part. Examples: // 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"); It compares the expression value with constants in all variants of case and gives control to the operator that corresponds with the expression value. Each variant of the case can be marked with an integer or literal constant or with a constant expression. The constant expression cannot contain variables or function calls. Expression of the switch operator must be of integer type. switch(expression) { case constant: operators case constant: operators ... default: operators

} Operators connected with the default label are executed if none of the constants in case operators equals the expression value. The default variant must be necessarily final. If none of the constants corresponds to the expression value and the default variant is not available, no actions are executed. The keyword case and the constant are just labels, and if operators are executed for some case variant, the program will further execute the operators of all following variants until break operator occurs. It makes it possible to bind a subsequence of operators with several variants. A constant expression is calculated during compilation. No two constants in one switch operator can have the same values. 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; } If the expression is true, the operator is executed until the expression becomes false. If the expression is false, the control will be given to the next operator. while(expression) operator; An expression value has been defined before the operator is executed. Therefore, if the expression is false from the very beginning, the operator will not be executed at all. Example: while(k<n) { y=y*x; k++; } Expression1 describes the cycle initialization. Expression2 is the conditional test for the cycle termination. If it is true, the loop body for operator will be executed. The cycle repeats until Expression2 becomes false. If it is false, the cycle will be terminated, and the control will be given to the next operator. Expression3 is calculated after each iteration. for (Expression1; Expression2; Expression3) operator; The for operator is equivalent to the following succession of operators: Expression1; while(Expression2) { operator; Expression3; }; Any of the three or all three expressions can be absent in the for operator, but the semicolons (;) that separate them must not be omitted. If Expression2 is omitted, it is considered constantly true. The for (;;) operator is a continuous cycle equivalent to the while(1) operator. Either expression 1 or 3 can consist of several expressions combined by a comma operator ','. Examples: for(x=1;x<=7;x++) Print(MathPower(x,2)); for(;;) { Print(MathPower(x,2)); x++; if(x>10) break; } for(i=0,j=n-l;i<n;i++,j--) a[i]=a[j]; Function is a named part of a program that can be called from other parts of the program so many times as it is necessary. It consists of type definition for the value to be returned, name, formal parameters, and a composite operator (block) of actions to be performed. Amount of pas sed parameters is limited and cannot exceed 64. Example: double // type of value to be returned linfunc (double x, double a, double b) // function name and parameters list { // composite operator return (a + b); // returned value } The "return" operator can return the value of the expression included into this operator. If necessary, the expression value can be transformed into the type of function result. A function that does not return values must be of "void" type. Example: void errmesg(string s) { Print("error: "+s); }

Parameters to be passed to the function can have default values that are defined by constants of the appropriate type. Example: int somefunc(double a, double d=0.0001, int n=5, bool b=true, string s="passed strin g") { Print("Required parameter a=",a); Print("The following parameters are transmitted: d=",d," n=",n," b=",b," s=",s); return (0); } If the default value was assigned to a parameter, all follow -up parameters must have the default value, too. Example of a wrong declaration: int somefunc(double a, double d=0.0001, int n, bool b, string s="passed string") { } If a name that has not been described before appears in an expression and is followed by the left parenthesis, it will be con textually considered as the name of a function. function_name (x1, x2,..., xn) Arguments (formal parameters) are passed by value, i.e., each expression xl, . . . , xn is calculated, and the value is passed t o the function. The order of expressions calculation and that of values loading are guaranteed. During the execution, the system checks the number and typ e of arguments given to the function. Such way of addressing to the function is called a value call. F unction call is an expression thy value of which is the value returned by the function. The function type described above must correspond with the type of the returned value. The function can be declared or described in any part of the program on the global scope, i.e., outside other functions. The function cannot be declared or described inside of another function. Examples: int start() { double some_array[4]={0.3, 1.4, 2.5, 3.6}; double a=linfunc(some_array, 10.5, 8); //... } double linfunc(double x[], double a, double b) { return (a*x[0] + b); } At calling of a function with default parameters, the list of parameters to be passed can be limited, but not before the firs t default parameter. Examples: void somefunc(double init,double sec=0.0001,int level=10); // function prototype somefunc(); // wrong call, the first required parameter must be presented. somefunc(3.14); // proper call somefunc(3.14, 0.0002); // proper call somefunc(3.14, 0.0002, 10); // proper call When calling a function, one may not skip parameters, even those having default values: somefunc(3.14, , 10); // wrong call. the second parameter was skipped. There are three functions with pre-defined names in MQL4: init() is a function to be called during the module initialization. If it is not available, no function will be called at initializa tion. start() is the basic function. For experts, it is called after the next tick has income. For custom indicators, it is called at recalculation after the indicator has been attached to the chart, at opening of the client terminal (if the indicator is attached to the chart), and after the next tick has income, as well. For scripts, it is executed immediately after the script has been attached to the chart and initialized. If there is no start() function in the module, the module (expert, script, or custom indicator) cannot be launched. deinit() is a function to be called during deinitialization of the module. If it is not available, no function will be called at deinitialization. Pre-defined functions can have some parameters. However, no parameters will be taken from outside when these functions are called by the client terminal, but the default values will be used. Fu nctions of start(), init(), and deinit() can be called from any point of the module according to the common rules, equally to other functions. It is not recommended to call start() function from init() function or to perform trade operations, as chart data, market prices, etc. can be incomplete by the moment of the module initialization. The init() and deinit() functions must finish their working as soon as possible and, in no case, shall they loop when trying to start its full -fledged working before the start() function is called. Variables must be declared before they are used. Unique names are used to identify variables. Descriptions of variables are u sed for them to be defined and for types to be declared. Description is not an operator. The basic types are: y bool - boolean values of true and false; y string - character strings; y double - double-precision numbers with floating point. Examples: string MessageBox; int Orders; double SymbolPrice; bool bLog; Additional types: y color is an integer representing an RGB color; y datetime is date and time, an unsigned integer containing seconds that have passed since 0.00 a.m. on 1 January, 1970. Additional data types make sense only at the declaration of input parameters for their more convenient representation in the properties window. Example: datetime tBegin_Data = D'2004.01.01 00:00'; color cModify_Color = C'0x44,0xB9,0xE6';

Arrays Array is the indexed sequence of the identical-type data. 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 are allowed. Numbering of array elements starts with 0. The last element of a one-dimensional array has the number which i s 1 less than the array size. This means that call for the last element of an array consisting of 50 integers will appear as a[49]. The same concerns multidimensional arrays: A dimension is indexed from 0 to the dimension size-1. The last element of a two dimensional array from the example will appear as m[6][49]. If there is an attempt to access out of the array range, the executing subsystem will generate error named ERR_ARRAY_INDEX_OUT_OF_RANGE that can be got using the GetLastError() function. A variable declared inside any function is local. The scope of a local variable is limited to the function range inside which it is declared. A local variable can be initialized by outcome of any expression. Every call of the function initializes a local variable. Local variables are stored in memory area of the corresponding function. Example: int somefunc() { int ret_code=0; .... return(ret_code); } Parameters passed to the function are local. Scope is the function block. Formal parameters must have names differing from those of external variables and local variables defined within one functi on. In the block of the function to the formal parameters some values can be assigned. Some values can be assigned to formal parameters in the function block. Example: void func(int x[], double y, bool z) { if(y>0.0 && !z) Print(x[0]); ... } Formal parameters can be initialized by constants. In this case, the initializing value is considered as the default value. P arameters, next to the intialized one, must also be initialized. Example: void func(int x, double y = 0.0, bool z = true) { ... } When calling such a function, the initialized parameters can be omitted, the defaults being substituted instead of them. Example: func(123, 0.5); MQL4-library functions imported within other modules cannot have parameters initialized by default values. Parameters are passed by value, i.e., modifications of the corresponding local variable inside the called function will not b e shown in the calling function in any way. It is possible to pass arrays as parameters. However, for an array passed as parameter, it is impossible to change values of its elements. It is also possible to pass parameters by reference. In this case, modification of such parameters will be shown in the corre sponding variables in the called function passed by reference. Array elements cannot be passed by reference. Parameters can be passed by reference only within one module, such possibility being not provided for libraries. In order to inform that a parameter is pa ssed by reference, it is necessary to put the & modifier after the data type. Example: void func(int& x, double& y, double& z[]) { double calculated_tp; ... for(int i=0; i<OrdersTotal(); i++) { if(i==ArraySize(z)) break; if(OrderSelect(i)==false) break; z[i]=OrderOpenPrice(); } x=i; y=calculated_tp; } Arrays can be passed by reference, as well, all changes being shown in the source array. Unlike simple parameters, arrays can be passed by reference into library functions, as well. Parameters passed by reference cannot be initialized with defaults. Into function cannot be passed more than 64 parameters. The memory class of "static" defines a static variable. The specifier "static" is declared before a da ta type. Example: int somefunc() { static int flag=10; .... return(flag);

} Static variables are stored in the permanent memory, their values do not get lost when the function is exited. Any variables in a block, except for formal parameters of the function, can be defined as static. The static variable can be initialized by a constant of the corresponded type, unl ike 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 of the "init()" function, that is at exit from the function inside which the static vari able is declared, the value of this variable not getting lost. Global variables are defined at the same level as functions, i.e. they are not local in any block. Example: int GlobalFlag=10; // global variable int start() { ... } Scope of global variables is the entire program. Global variables are accessible from all functions d efined in the program. They are initialized with zero if no other initial value is explicitly defined. A global variable can be initialized only by a constant that corresponds with i ts type. Global variables can be initialized only once after program loadi ng into client terminal memory. Note: Variables declared at global level must not be mixed up with the Client Terminal global variables that can be accessed unsing the GlobalVariable...() functions. The extern memory class defines an extern variable. The extern specifier is declared before a data type. Example: extern double InputParameter1 = 1.0; extern color InputParameter2 = red; int init() { ... } Extern variables determine inputs of the program, they are accessible from a program properties window. Arrays cannot represent themselves as extern variables. Any variable can be initialized at its defining. Any variable is initialized with zero (0) if no other initial value is expli citly defined. Global and static variables can be initialized only by a constant of the corresponding type. Local variables can be initialized by any expressi on, not only constant. Global and static variables are initialized only once. Local variables are initialized every tim e by call of the corresponded functions. Examples: int n = 1; double p = MarketInfo(Symbol(),MODE_POINT); string s = "hello"; double f[] = { 0.0, 0.236, 0.382, 0.5, 0.618, 1.0 }; int a[4][4] = { 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3 , 3, 4, 4, 4, 4 }; The list of array elements values must be enclosed in braces. Initializing values omitted are considered as equal to 0. If th e initializing array size is not defined, it will be defined by the compiler from the szie of the initializing sequence. Multidimensional arrays are initialized by a one -dimensional sequence, i.e. sequence without additional braces. All arrays, including those declared in the local scope, can be initialize d with constants only. The type of external functions defined in another component of a program must be explicitly described. The absence of such a definition may result in errors during the compilation, linkage, or execution of the program. While describing an external object, the keyword of #import must be used with the reference to the module. #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 Import can be used to easily describe functions called from external DLLs or compiled EX4 libraries. Pointers to variables can be passed to imported dll functions. Data of the string type are passed as a pointer to the corresponding memory block (one should keep in mind that internal representation of string data consists of two parts: the memory block length and the memory blo ck pointer). If there is a need to pass data of the int or double type, then the one-dimensional array of the corresponding type sh ould be passed by reference as a parameter. Example: #import "some_lib.dll" void PassIntegerByref(int& OneInt[]); #import int start() { int array[1]; //... PassIntegerByref(array); Print(array[0]); //... } Preprocessor is a special subsystem of MQL4 compiler that is intended for preparation of the program source code immediately before the program is compiled. Preprocessor allows enhancement of the source code readability. The code can be structured by including of specific files con taining source codes of MQL4 programs. The possibility to assign mnemonic names to specific constants contributes to enhancement of the code readabil ity.

Preprocessor also allows determining of specific parameters of MQL4 programs. If the # symbol is used in the first line of the program, this line is a preprocessor directive. A preprocessor directive ends with a line feed characte r. Using the #define construction, one can define the symbolic name or symbolic constant at the program start to be the specific sy mbol string. Later on, the compiler will replace all appearances of this name without quotation marks with the corresponding string. In fact, this name can be replaced by any absolutely arbitrary text, not necessary with digits: #define identifier value The constant identifier conforms to the same rules as those regulating names of variables. The value can be of any type: #define ABC 100 #define PI 0.314 #define COMPANY_NAME "MetaQuotes Software Corp." void ShowCopyright() { Print("Copyright 2001-2007, ",COMPANY_NAME); Print("http://www.metaquotes.net"); } Every MQL4 program allows to specify additional specific parameters named #property that help client terminal in proper servicing for programs without the necessity to launch them explicitly. This concerns external settings of indicators, first of all. #property identifier value Constant Link Copyright Stacksize library indicator_chart_window indicator_buffers indicator_minimum indicator_maximum indicator_colorN indicator_widthN indicator_styleN indicator_levelN indicator_levelcolor indicator_levelwidth indicator_levelstyle show_confirm void int double double color int int double color int int void indicator_separate_window void Type string string int a link to the company website the company name stack size a library; no start function is assigned, non -referenced functions are not removed show the indicator in the chart window show the indicator in a separate window the number of buffers for calculation, up to 8 the bottom scaling limit for a separate indicator window the top scaling limit for a separate indicator window the color for displaying line N, where N lies between 1 and 8 width of the line N, where N lies between 1 and 8 style of the line N, where N lies between 1 and 8 predefined level N for separate window custom indicator, where N lies between 1 and 8 level line color level line width level line style before script run message box with confirmation appears Description

show_inputs void before script run its property sheet appears; disables show_confirm property Examples: #property link "http://www.metaquotes.net" #property copyright "MetaQuotes Software Corp." #property library #property stacksize 1024 Compiler will write the declared values in the settings of the executed module. The #include command line can be placed anywhere in the program, but usually all inclusions are placed at the beginning of the source code. Call format: #include <file_name> #include "file_name"; Examples: #include <WinUser32.mqh> #include "mylib.mqh" Preprocessor replaces this line with the content of the file WinUser32.mqh. Angle brackets mean that the WinUser32.mqh file will be taken from the default directory (usually terminal_directory\experts\include). The current directory is not searched. If the file name is enclosed in quotation marks, the search will be performed in the current directory (where the main file of the s ource code is located). The standard directory is not searched in. Functions are imported from compiled MQL4 modules (*.ex4 files) and from operating system modules (*.dll files). The module name is specified in the #import directive. For compiler to be able to form the imported function call and pass parameters in a proper way, the full descripti on of functions is needed. Functions descriptions follow the #import "module name" immediately. The new #import command (can be without parameters) completes the imported functions description block. #import "file_name" func1 define; func2 define; ... funcN define;

#import Imported functions must have their unique names. Functions having the same names cannot be imported simultaneously from differen t modules. Imported functions names may not coincide with those of built -in functions. Since the imported functions are out of the module to be compiled, the compiler cannot check correctness of parameters passed. This is why, to avoid runtime errors, it is necessary to declare the compliance of types and order of parameters precisely. The parameters passed t o imported functions (both from EX4 and from DLL modules) cannot have values by default. Examples: #import "user32.dll" int MessageBoxA(int hWnd, string lpText, string lpCaption, int uType); #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); #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); #import For importing of functions during execution of an mql4 program, the so -called late binding is used. This means that until the imported function has not been called, the corresponding module (ex4 or dll) will not be loaded. It is not recommended to use the fully qualified name of loaded module appearing as Drive:\Directory\FileName.Ext. MQL4 libraries are loaded from the terminal_dir\experts\libraries folder. If the library has not been found, there will be an attempt to load a library from the terminal_dir\experts folder. To simplify the program writing and to make program texts more convenien t for perception, predefined standard constants are forseen in MQL4. Standard constants are similar to macro substitutions and are of int type. The constants are grouped by their purposes. Series array identifier used with ArrayCopySeries(), iHighest() and iLowest() functions. It can be any of the following values: Constant Value MODE_OPEN MODE_LOW MODE_HIGH MODE_CLOSE MODE_VOLUME 0 1 2 3 4 Open price. Low price. High price. Close price. Volume, used in iLowest() and iHighest() functions.

Description

MODE_TIME 5 Bar open time, used in ArrayCopySeries() function. Timeframe of the chart (chart period). It can be any of the following values: Constant Value Description PERIOD_M1 PERIOD_M5 PERIOD_M15 PERIOD_M30 PERIOD_H1 PERIOD_H4 PERIOD_D1 PERIOD_W1 PERIOD_MN1 1 5 15 30 60 240 1440 10080 43200 1 minute. 5 minutes. 15 minutes. 30 minutes. 1 hour. 4 hour. Daily. Weekly. Monthly.

0 (zero) 0 Timeframe used on the chart. Operation type for the OrderSend() function. It can be any of the following values: Constant Value OP_BUY OP_SELL OP_BUYLIMIT OP_SELLLIMIT 0 1 2 3 Buying position. Selling position. Buy limit pending position. Sell limit pending position.

Description

OP_BUYSTOP

Buy stop pending position.

OP_SELLSTOP 5 Sell stop pending position. Applied price constants. It can be any of the following values: Constant Value PRICE_CLOSE PRICE_OPEN PRICE_HIGH PRICE_LOW PRICE_MEDIAN PRICE_TYPICAL 0 1 2 3 4 5 Close price. Open price. High price. Low price. Median price, (high+low)/2. Typical price, (high+low+close)/3.

Description

PRICE_WEIGHTED 6 Weighted close price, (high+low+close+close)/4. Market information identifiers, used with MarketInfo() function. It can be any of the following values: Constant Value 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 MODE_TRADEALLOWED MODE_MINLOT MODE_LOTSTEP MODE_MAXLOT MODE_SWAPTYPE MODE_PROFITCALCMODE MODE_MARGINCALCMODE MODE_MARGININIT MODE_MARGINMAINTENANCE MODE_MARGINHEDGED MODE_MARGINREQUIRED MODE_FREEZELEVEL Drawing shape style enumeration for SetIndexStyle() function. It can be any of the following values : Constant Value 1 2 5 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 Low day price. High day price.

Description

The last incoming tick time (last known server time). Last incoming bid price. For the current symbol, it is stored in the predefined variable Bid Last incoming ask price. For the current symbol, it is stored in the predefined variable Ask Point size in the quote currency. For the current symbol, it is stored in the predefined variable Point Count of digits after decimal point in the symbol prices. For the current symbol, it is stored in the predefined variable Digits Spread value in points. Stop level in points. Lot size in the base currency. Tick value in the deposit currency. Tick size in points. Swap of the long position. Swap of the short position. Market starting date (usually used for futures). Market expiration date (usually used for futures). Trade is allowed for the symbol. Minimum permitted amount of a lot. Step for changing lots. Maximum permitted amount of a lot. Swap calculation method. 0 - in points; 1 - in the symbol base currency; 2 - by interest; 3 - in the margin currency. Profit calculation mode. 0 - Forex; 1 - CFD; 2 - Futures. Margin calculation mode. 0 - Forex; 1 - CFD; 2 - Futures; 3 - CFD for indices. Initial margin requirements for 1 lot. Margin to maintain open positions calculated for 1 lot. Hedged margin calculated for 1 lot. Free margin required to open 1 lot for buying. Order freeze level in points. If the execution price lies within the range defined by the freeze level, the order cannot be modified, cancelled or closed.

Description

DRAW_LINE DRAW_SECTION DRAW_ARROW DRAW_ZIGZAG

0 1 3 4

Drawing line. Drawing sections. Drawing histogram. Drawing arrows (symbols). Drawing sections between even and odd indicator buffers.

DRAW_HISTOGRAM 2

DRAW_NONE 12 No drawing. Drawing style. Valid when width=1. It can be any of the following values: Constant Value STYLE_SOLID STYLE_DASH STYLE_DOT STYLE_DASHDOT 0 1 2 3 The pen is solid. The pen is dashed. The pen is dotted.

Description

The pen has alternating dashes and dots.

STYLE_DASHDOTDOT 4 The pen has alternating dashes and double dots. Predefined Arrow codes enumeration. Arrows code constants. It can be one of the following values: Constant Value Description SYMBOL_THUMBSUP SYMBOL_ARROWUP SYMBOL_ARROWDOWN SYMBOL_STOPSIGN 67 241 242 251 Thumb up symbol (C). Thumb down symbol (D). Arrow up symbol (). Arrow down symbol (). Stop sign symbol (). SYMBOL_THUMBSDOWN 68

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 2 3 4 SYMBOL_LEFTPRICE 5 SYMBOL_RIGHTPRICE 6 Wingdings font symbols used with Arrow objects. 32 ! 33 " 34 # 35 $ 36 % 37 & 38 ' 0 48 1 49 2 50 3 51 4 52 5 53 6 54 7 @ 64 A 65 B 66 C 67 D 68 E 69 F 70 G P 80 Q 81 R 82 S 83 T 84 U 85 V 86 W ` 96 a 97 b 98 c 99 d 100 e 101 f 102 g p 112 q 113 r 114 s 115 t 116 u 117 v 118 w 128 129 130 131 132 133 134 144 145 146 147 148 149 150 160 161 162 163 164 165 166 176 177 178 179 180 181 182 192 193 194 195 196 197 198 208 209 210 211 212 213 214 224 225 226 227 228 229 230 240 241 242 243 244 245 246 color type supported color constants. Black DarkGreen Maroon SeaGreen LightSeaGreen Goldenrod DarkOrange DeepSkyBlue LightSlateGray Indigo DarkGoldenrod DarkViolet MediumSpringGreen Orange Blue DeepPink Upwards arrow with tip rightwards ( ). Downwards arrow with tip rightwards ( ). Left pointing triangle ( ). En Dash symbol (). Left sided price label. Right sided price label. 39 ( 55 8 71 H 87 X 103 h 119 x 135 151 167 183 199 215 231 247 40 56 72 88 104 120 136 152 168 184 200 216 232 248 ) 9 I Y i y 41 * 57 : 73 J 89 Z 105 j 121 z 137 153 169 185 201 217 233 249 42 58 74 90 106 122 138 154 170 186 202 218 234 250 + 43 ; 59 K 75 [ 91 k 107 { 123 139 155 171 187 203 219 235 251 , < L \ l | 44 60 76 92 108 124 140 156 172 188 204 220 236 252 = M ] m } 45 61 77 93 109 125 141 157 173 189 205 221 237 253 . > N ^ n ~ 46 / 62 ? 78 O 94 _ 110 o 126 142 158 174 190 206 222 238 254 47 63 79 95 111 127 143 159 175 191 207 223 239 255

DarkSlateGray MidnightBlue DarkSlateBlue FireBrick LawnGreen Gold Magenta MediumTurquoise

Olive DarkBlue Sienna CadetBlue Yellow Red DodgerBlue

Green MediumBlue DarkOrchid Chartreuse Gray Turquoise

DarkOliveGreen SaddleBrown Brown Chocolate YellowGreen Lime SlateGray RoyalBlue

MediumVioletRed MediumSeaGreen

Teal

Navy ForestGreen DarkTurquoise Crimson LimeGreen SpringGreen Peru SlateBlue

Purple OliveDrab DimGray SteelBlue OrangeRed Aqua BlueViolet DarkKhaki

IndianRed MediumPurple DarkSalmon Plum PaleGreen Moccasin LemonChiffon Lavender

MediumOrchid PaleVioletRed BurlyWood Khaki Thistle LightPink Beige MistyRose

GreenYellow Coral HotPink LightGreen PowderBlue Gainsboro AntiqueWhite OldLace

MediumAquamarine CornflowerBlue Salmon Aquamarine PaleGoldenrod PeachPuff PapayaWhip WhiteSmoke

DarkSeaGreen DarkGray Violet Silver PaleTurquoise Pink Cornsilk Seashell

Tomato LightCoral LightGray Bisque LightYellow Ivory

RosyBrown SkyBlue Wheat LightCyan Honeydew

Orchid Tan LightSalmon LightBlue NavajoWhite Linen AliceBlue

SandyBrown MediumSlateBlue LightSkyBlue LightSteelBlue

LightGoldenrod BlanchedAlmond

LavenderBlush MintCream Snow White Indicator line identifiers used in iMACD(), iRVI() and iStochastic() indicators. It can be one of the following values: Constant Value MODE_MAIN 0 Base indicator line. MODE_SIGNAL 1 Signal line. Indicator line identifiers used in iADX() indicator. Constant Value MODE_MAIN MODE_PLUSDI 0 1 Base indicator line. +DI indicator line.

Description

Description

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. Ichimoku Kinko Hyo identifiers used in iIchimoku() indicator call as source of requested data. It can be one of the following values: Constant Value Description MODE_TENKANSEN MODE_KIJUNSEN MODE_SENKOUSPANA MODE_SENKOUSPANB 1 2 3 4 Tenkan-sen. Kijun-sen. Senkou Span A. Senkou Span B.

MODE_CHINKOUSPAN 5 Chinkou Span. 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 MODE_EMA MODE_SMMA 0 1 2 Simple moving average, Exponential moving average, Smoothed moving average,

MODE_LWMA 3 Linear weighted moving average. 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 IDCANCEL IDABORT IDRETRY IDIGNORE IDYES IDNO IDTRYAGAIN 1 2 3 4 5 6 7 10 OK button was selected. Cancel button was selected. Abort button was selected. Retry button was selected. Ignore button was selected. Yes button was selected. No button was selected. Try Again button was selected.

IDCONTINUE 11 Continue button was selected. The MessageBox function flags specify the contents and behavior of the dialog box. This value can be a combination of flags from the followi ng groups of flags.

To indicate the buttons displayed in the message box, specify one of the following values. Constant Value Description MB_OK MB_OKCANCEL MB_ABORTRETRYIGNORE MB_YESNOCANCEL MB_YESNO MB_RETRYCANCEL 0x00000000 The message box contains one push button: OK. This is the default. 0x00000001 The message box contains two push buttons: OK and Cancel. 0x00000002 The message box contains three push buttons: Abort, Retry, and Ignore. 0x00000003 The message box contains three push buttons: Yes, No, and Cancel. 0x00000004 The message box contains two push buttons: Yes and No. 0x00000005 The message box contains two push buttons: Retry and Cancel.

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_CANCELTRYCONTINUE 0x00000006 MB_ICONSTOP, MB_ICONERROR, MB_ICONHAND MB_ICONQUESTION 0x00000010 A stop-sign icon appears in the message box. 0x00000020 A question-mark icon appears in the message box.

MB_ICONEXCLAMATION, 0x00000030 An exclamation-point icon appears in the message box. MB_ICONWARNING MB_ICONINFORMATION, 0x00000040 An icon consisting of a lowercase letter i in a circle appears in the message box. MB_ICONASTERISK 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. MessageBox() function behavior flags are defined in the WinUser32.mqh file, this is why this heading file must be included to programs through #include <WinUser32.mqh>. Not all possible flags are listed here. For more details, please refer to Win32 API description. 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 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 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Vertical line. Uses time part of first coordinate. Horizontal line. Uses price part of first coordinate. Trend line. Uses 2 coordinates. Trend by angle. Uses 1 coordinate. To set angle of line use ObjectSet() function. Regression. Uses time parts of first two coordinates. Channel. Uses 3 coordinates. Standard deviation channel. Uses time parts of first two coordinates. Gann line. Uses 2 coordinate, but price part of second coordinate ignored. Gann fan. Uses 2 coordinate, but price part of second coordinate ignored. Gann grid. Uses 2 coordinate, but price part of second coordinate ignored. Fibonacci retracement. Uses 2 coordinates. Fibonacci time zones. Uses 2 coordinates. Fibonacci fan. Uses 2 coordinates. Fibonacci arcs. Uses 2 coordinates. Fibonacci expansions. Uses 3 coordinates. Fibonacci channel. Uses 3 coordinates. Rectangle. Uses 2 coordinates. Triangle. Uses 3 coordinates. Ellipse. Uses 2 coordinates. Andrews pitchfork. Uses 3 coordinates.

OBJ_CYCLES OBJ_TEXT OBJ_ARROW

20 21 22

Cycles. Uses 2 coordinates. Text. Uses 1 coordinate. Arrows. Uses 1 coordinate.

OBJ_LABEL 23 Text label. Uses 1 coordinate in pixels. Object value index used with ObjectGet() and ObjectSet() functions. It can be any of the following values: Constant Value Type Description 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_LEVELCOLOR OBJPROP_LEVELSTYLE OBJPROP_LEVELWIDTH OBJPROP_FIRSTLEVEL+n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 100 101 102 103 200 201 202 203 210+n datetime double datetime double datetime double color int int bool bool bool double double int int double int int int int int color int int int Datetime value to set/get first coordinate time part. Double value to set/get first coordinate price part. Datetime value to set/get second coordinate time part. Double value to set/get second coordinate price part. Datetime value to set/get third coordinate time part. Double value to set/get third coordinate price part. Color value to set/get object color. Value is one of STYLE_SOLID, STYLE_DASH, STYLE_DOT, STYLE_DASHDOT, STYLE_DASHDOTDOT constants to set/get object line style. Integer value to set/get object line width. Can be from 1 to 5. Boolean value to set/get background drawing flag for object. Boolean value to set/get ray flag of object. Boolean value to set/get ellipse flag for fibo arcs. Double value to set/get scale object property. Double value to set/get angle object property in degrees. Integer value or arrow enumeration to set/get arrow code object property. Value can be one or combination (bitwise addition) of object visibility constants to set/get timeframe object property. Double value to set/get deviation property for Standard deviation objects. Integer value to set/get font size for text objects. Integer value to set/get anchor corner property for label objects. Must be from 03. Integer value to set/get anchor X distance object property in pixels. Integer value is to set/get anchor Y distance object property in pixels. Integer value to set/get Fibonacci object level count. Can be from 0 to 32. Color value to set/get object level line color. Value is one of STYLE_SOLID, STYLE_DASH, STYLE_DOT, STYLE_DASHDOT, STYLE_DASHDOTDOT constants to set/get object level line style. Integer value to set/get object level line width. Can be from 1 to 5.

Integer value to set/get the value of Fibonacci object level with index n. Index n can be from 0 (number of levels -1), but not larger than 31. Timeframes where object may be shown. Used in ObjectSet() function to set OBJPROP_TIMEFRAMES property. Constant Value Description 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 0x0001 0x0002 0x0004 0x0008 0x0010 0x0020 0x0040 0x0080 0x0100 0x01FF 0 Object shown is only on 1-minute charts. Object shown is only on 5-minute charts. Object shown is only on 15-minute charts. Object shown is only on 30-minute charts. Object shown is only on 1-hour charts. Object shown is only on 4-hour charts. Object shown is only on daily charts. Object shown is only on weekly charts. Object shown is only on monthly charts. Object shown is on all timeframes. Object shown is on all timeframes.

EMPTY -1 Hidden object on all timeframes. Uninitialize reason codes returned by UninitializeReason() function. It can be any one of the following values: Constant Value Description 0 REASON_REMOVE REASON_RECOMPILE REASON_CHARTCHANGE REASON_CHARTCLOSE REASON_PARAMETERS 1 2 3 4 5 Script finished its execution independently. Expert removed from chart. Expert recompiled. symbol or timeframe changed on the chart. Chart closed. Inputs parameters was changed by user.

REASON_ACCOUNT 6 Other account activated. Special constants used to indicate parameters and variables states. It can be one of the following values: Constant Value Description NULL EMPTY EMPTY_VALUE CLR_NONE 0 -1 0x7FFFFFFF 0xFFFFFFFF Indicates empty state of the string. Indicates empty state of the parameter. Default custom indicator empty value. Indicates empty state of colors.

WHOLE_ARRAY 0 Used with array functions. Indicates that all array elements will be processed. 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 <stderror.mqh> #include <stdlib.mqh> void SendMyMessage(string text) { int check; SendMail("some subject", text); check=GetLastError(); if(check!=ERR_NO_ERROR) Print("Cannot send message, error: ",ErrorDescription(check)); } Error codes returned from trade server. Constant Value Description 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 0 1 2 3 4 5 6 7 8 9 64 65 128 129 130 131 132 133 134 135 136 137 138 No error returned. No error returned, but the result is unknown. Common error. Invalid trade parameters. Trade server is busy. Old version of the client terminal. No connection with trade server. Not enough rights. Too frequent requests. Malfunctional trade operation. Account disabled. Invalid account. Trade timeout. Invalid price. Invalid stops. Invalid trade volume. Market is closed. Trade is disabled. Not enough money. Price changed. Off quotes. Broker is busy. Requote.

ERR_ORDER_LOCKED ERR_TOO_MANY_REQUESTS ERR_TRADE_MODIFY_DENIED ERR_TRADE_CONTEXT_BUSY ERR_TRADE_EXPIRATION_DENIED ERR_TRADE_TOO_MANY_ORDERS ERR_TRADE_HEDGE_PROHIBITED ERR_TRADE_PROHIBITED_BY_FIFO MQL4 run time error codes Constant ERR_NO_MQLERROR ERR_WRONG_FUNCTION_POINTER ERR_ARRAY_INDEX_OUT_OF_RANGE ERR_NO_MEMORY_FOR_CALL_STACK ERR_RECURSIVE_STACK_OVERFLOW ERR_NOT_ENOUGH_STACK_FOR_PARAM ERR_NO_MEMORY_FOR_PARAM_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_CALLS_NOT_ALLOWED ERR_NO_MEMORY_FOR_RETURNED_STR ERR_SYSTEM_BUSY ERR_INVALID_FUNCTION_PARAMSCNT ERR_INVALID_FUNCTION_PARAMVALUE ERR_STRING_FUNCTION_INTERNAL ERR_SOME_ARRAY_ERROR ERR_INCORRECT_SERIESARRAY_USING ERR_CUSTOM_INDICATOR_ERROR ERR_INCOMPATIBLE_ARRAYS ERR_GLOBAL_VARIABLES_PROCESSING ERR_GLOBAL_VARIABLE_NOT_FOUND ERR_FUNC_NOT_ALLOWED_IN_TESTING ERR_FUNCTION_NOT_CONFIRMED ERR_SEND_MAIL_ERROR ERR_STRING_PARAMETER_EXPECTED ERR_INTEGER_PARAMETER_EXPECTED ERR_DOUBLE_PARAMETER_EXPECTED

139 141 145 146 147 148 149 150

Order is locked. Long positions only allowed. Too many requests. Modification denied because order too close to market. Trade context is busy. Expirations are denied by broker. The amount of open and pending orders has reached the limit set by the broker. An attempt to open a position opposite to the existing one when hedging is disabled. An attempt to close a position contravening the FIFO rule. Value 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 No error. Wrong function pointer. Array index is out of range. No memory for function call stack. Recursive stack overflow. Not enough stack for parameter. No memory for parameter string. No memory for temp string. Not initialized string. Not initialized string in array. No memory for array string. Too long string. Remainder from zero divide. Zero divide. Unknown command. Wrong jump (never generated error). Not initialized array. DLL calls are not allowed. Cannot load library. Cannot call function. Expert function calls are not allowed. Not enough memory for temp string returned from function. System is busy (never generated error). Invalid function parameters count. Invalid function parameter value. String function internal error. Some array error. Incorrect series array using. Custom indicator error. Arrays are incompatible. Global variables processing error. Global variable not found. Function is not allowed in testing mode. Function is not confirmed. Send mail error. String parameter expected. Integer parameter expected. Double parameter expected. Description

ERR_LONG_POSITIONS_ONLY_ALLOWED 140

ERR_ARRAY_AS_PARAMETER_EXPECTED ERR_HISTORY_WILL_UPDATED ERR_TRADE_ERROR ERR_END_OF_FILE ERR_SOME_FILE_ERROR ERR_WRONG_FILE_NAME ERR_TOO_MANY_OPENED_FILES ERR_CANNOT_OPEN_FILE ERR_INCOMPATIBLE_FILEACCESS 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

4065 4066 4067 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4200 4201 4202 4203 4204 4205 4206

Array as parameter expected. Requested history data in updating state. Some error in trading function. End of file. Some file error. Wrong file name. Too many opened files. Cannot open file. Incompatible access to a file. No order selected. Unknown symbol. Invalid price. Invalid ticket. Trade is not allowed. Enable checkbox "Allow live trading" in the expert properties. Longs are not allowed. Check the expert properties. Shorts are not allowed. Check the expert properties. Object exists already. Unknown object property. Object does not exist. Unknown object type. No object name. Object coordinates error. No specified subwindow.

ERR_SOME_OBJECT_ERROR 4207 Some error in object function. For each executable MQL4 program, a number of predefined variables is supported that reflect the state of the current price chart at the launching of a program: an expert, a script, or a custom indicator. Libraries use variables of the module that has called a library. To have a safe and quick access to these data, client terminal provides local copies of predefined variables for each launched program separately. These data are updated at every launch of an attached expert or a custom indicator automatically or using the RefreshRates() function call. double Ask The latest known seller's price (ask price) for the current symbol. The RefreshRates() function must be used to update. See also MarketInfo(). Sample: if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25) { OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid -StopLoss*Point,Ask+TakeProfit*Point, "My order #2",3,D'2005.10.10 12:30',Red); return; } int Bars Number of bars in the current chart. See also iBars(). Sample: int counter=1; for(int i=1; i<=Bars; i++) { Print(Close[i-1]); } double Bid The latest known buyer's price (offer price, bid price) of the current symbol. The RefreshRates() function must be used to update. See also MarketInfo(). Sample: if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) { OrderSend("EURUSD",OP_SELL,Lots,Bid,3,Ask+StopLoss*Point,Bid-TakeProfit*Point, "My Order #2",3,D'2005.10.10 12:30',Red); return(0); } double Close[]

Series array that contains close prices for each bar of the current chart. Series array elements are indexed in the reverse order, i.e., from the last one to the first one. The current bar which is th e last in the array is indexed as 0. The oldest bar, the first in the chart, is indexed as Bars-1. See also iClose(). Sample: int handle = FileOpen("file.csv", FILE_CSV|FILE_WRITE, ";"); if(handle>0) { // table column headers recording FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // data recording 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 prices. See also MarketInfo(). Sample: Print(DoubleToStr(Close[0], Digits)); double High[] Series array that contains the highest prices of each ba r of the current chart. Series array elements are indexed in the reverse order, i.e., from the last one to the first one. The current bar which is th e last in the array is indexed as 0. The oldest bar, the first in the chart, is indexed as Bars-1. See also iHigh(). Sample: //---- 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--; } //---double Low[] Series array that contains the lowest prices of each bar of the current chart. Series array elements are indexed in the reverse order, i.e., from the last one to the first one. The current bar which is th e last in the array is indexed as 0. The oldest bar, the first in the chart, is indexed as Bars-1. See also iLow(). Sample: //---- minima 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--; } //---double Open[] Series array that contains open prices of each bar of the current chart.

Series array elements are indexed in the reverse order, i.e., from the last one to the first one. The current bar which is th e last in the array is indexed as 0. The oldest bar, the first in the chart, is indexed as Bars-1. See also iOpen(). Sample: i = Bars - counted_bars - 1; while(i>=0) { double high = High[i]; double low = Low[i]; double open = Open[i]; double close = Close[i]; AccumulationBuffer[i] = (close -low) - (high-close); if(AccumulationBuffer[i] != 0) { double diff = high - low; if(0==diff) AccumulationBuffer[i] = 0; else { AccumulationBuffer[i] /= diff; AccumulationBuffer[i] *= Volume[i]; } } if(i<Bars-1) AccumulationBuffer[i] += AccumulationBuffer[i+1]; i--; } double Point The current symbol point value in the quote currency. See also MarketInfo(). Sample: OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point); datetime Time[] Series array that contains open time of each bar of the current chart. Data like datetime represent time, in seconds, that has passed sinc e 00:00 a.m. of 1 January, 1970. Series array elements are indexed in the reverse order, i.e., from the last one to the first one. The current bar which is the last in the array is indexed as 0. The oldest bar, the first in the chart, is indexed as Bars-1. See also iTime(). Sample: for(i=Bars-2; i>=0; i--) { if(High[i+1] > LastHigh) LastHigh = High[i+1]; if(Low[i+1] < LastLow) LastLow = Low[i+1]; //---if(TimeDay(Time[i]) != TimeDay(Time[i+1])) { P = (LastHigh + LastLow + Close[i+1])/3; R1 = P*2 - LastLow; S1 = P*2 - LastHigh; R2 = P + LastHigh - LastLow; S2 = P - (LastHigh - LastLow); R3 = P*2 + LastHigh - LastLow*2; S3 = P*2 - (LastHigh*2 - LastLow); LastLow = Open[i]; LastHigh = Open[i]; } //---PBuffer[i] = P; S1Buffer[i] = S1; R1Buffer[i] = R1; S2Buffer[i] = S2; R2Buffer[i] = R2; S3Buffer[i] = S3; R3Buffer[i] = R3; } double Volume[] Series array that contains tick volumes of each bar of the current chart. Series array elements are indexed in the reverse order, i.e., from the last one to the first one. The current bar which is th e last in the array is i ndexed as 0. The oldest bar, the first in the chart, is indexed as Bars-1. See also iVolume(). Sample: 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); For an MQL4 program to work, it must be compiled (the "Compile" button or F5). It must be compiled without any errors (warnin gs are allowed, but they must be analyzed). At this, in the corresponding directory, terminal_dir\experts, terminal_dir\experts\indicators, or terminal_dir\experts\scripts, an executable file must be created that has the same name and extension EX4. It is this file that can be launched for execution. Experts, custom indicators, and scripts are attached to one of the opened charts by dragging with the mouse from the "Navigat or" window of the client terminal to the corresponding chart (the Drag'n'Drop technique). MQL4 programs can work only when the client terminal is on. For an expert to stop working,it must be deleted from the chart using "Expert Advisors - Delete" in the chart context menu. The status of the "Enable Expert Advisors" field influences the running of the exper t. For a custom indicator to stop working, it must be deleted from the chart. Custom indicators and expert advisors operate until they are explicitly deleted from the chart. Information about the attache d experts and custom indicators is saved between client terminal startups. Scripts are executed once and deleted automatically after they have completed their operation, or when the current chart has been closed or changed its status, or when the client terminal has been terminated. Scripts are no t launched at the terminal restart since information about them is not saved. In the same chart, one expert, one script, and an unlimited amount of indicators can work simultaneously. Immediately after the program has been attached to the chart, it starts working with the init() function. The init() function of an expert advisor or a custom indicator attached to the chart will run just after client terminal has started and history data (this concerns only experts, but not indicators) have been loaded additionally, after the symbol and/or chart period have been changed, after the program has been recompiled in MetaEditor, after inputs hav e been changed from the window of expert or custom indicator settings. An expert will also be initialized after the account has bee n changed. Every program attached to a chart completes its work with the deinit() function. The deinit() function runs at the client ter minal shutdown, at chart closing, immediately before the symbol and/or chart period is changed, at successful recompili ng of the program, at changing of inputs, or at changing of the account. One can see the reason of deinitialization using the UninitializeReason() function during execution of the deinit() functio n. The deinit() function must be executed within 2.5 seconds. If the function has not completed its execution within this time period, it wil l be completed forcedly. Scripts are an exception to this rule, as they normally finish their working independently , without any commands from outside. If a script works very long (due to endless loop, foe example), it can be finished by an outside command (at deletion of the script from the chart contex t menu, at attaching of a new script to the same chart, at closing of the chart, at changing of the symbol and/or chart period). In this case, the deinit() function is limited by 2.5 seconds, too. At incoming of new quotes, the start() function of the attached experts and custom indicators will be executed. If the start () function launched at the preceding quote was running when a new quote came, the new quote will be skipped by the expert. All new quotes income while t he program was being executed are skipped by the program until the current execution of the start() fun ction has been completed. After that, the start() function will be run only when a successive new quote incomes. For custom indicators, the start() function will be launched for recalculation after the current chart symbol or timeframe has been changed independently on new quotes incoming. The start() function will not be run when the expert properties window is open. The latter cannot be opened during the expert execution. Detaching of the program from the chart, change of symbol and/or chart period, chan ge of the account, closing of the chart, as well as shutdown of the client terminal will interrupt execution of the program. If the start() function was being executed at the moment when the st op working command was given, the time remaining for its work i s limited by 2.5 seconds. The program can get to know that it is tried to shut it down with the built -in function of IsStopped() and finish its work correctly. Execution of scripts does not depend on incoming quotes. At change of symbol and/or chart period, the script will finish its work and be unloaded from the client terminal. Scripts and experts work in their own thread. Custom indicators work in the main interface thread. If a custom indicator has been called with the iCustom() function, this indicator works in the thread of the program that has called it. Library (imported) functions work in the call ing program thread, as well. To import functions during execution of an mql4 program, the so -called late binding is used. This means that, until the imported function is called, the corresponding module (ex4 or dll) will not be loaded. MQL4 and DLL libraries are executed in the calling module thread. It is not recommended to use a fully qualified name of the module to be loaded like Drive:\Directory\FileName.Ext. MQL4 libraries are loaded from the terminal_dir\experts\libraries folder. If the library has not been found, there will be made an attempt to load the library from the terminal_dir\experts folder. System libraries (DLLs) are loaded by the rules of the operation system. If the library has already been loaded (by another e xpert, for example, or from another client terminal launched at the same time), the library already loaded will be referenced to. Otherwise, the searchin g will be preformed in the following order: 1. The terminal_dir\experts\libraries directory. 2. The directory from which the terminal_dir client terminal was launched. 3. The current directory.

4. The system directory of windows_dir\SYSTEM32 (or windows_dir\SYSTEM for Win98). 5. The directory where windows_dir operation system was installed. 6. Directories listed in the P ATH environment system variable. If a DLL uses another DLL in its work, the former one will not be loaded if the latter one is unavailable. Unlike system libraires, custom libraries (MQL4) are loaded for every calling module separately, independently on whether the called library has been loaded by any other module. For example, the caller.ex4 module calls functions from lib1.ex4 and lib2.ex4 libraries. The lib1 .ex4 library, in its turn, calls functions from the lib2.ex4 library. In this case, one more co py of the lib1.ex4 library and two copies of the lib2.ex4 library will be loaded, regardless that all calls come from the same caller.ex4 module. Functions imported from DLL into an mql4 program must provide linkage convention accepted for Windows API fun ctions. To provide such a convention, the key word __stdcall specific for compilers of Microsoft(r) company is used in the source codes of programs wri tten in C or C++ language. The above linkage convention is characterized by the following: - calling function (in our case, it is an mql4 program) must "see" the called (imported from DLL) function prototype in order to put parame ters onto the stack in a proper way; - calling function (in our case, it is an mql4 program) puts parameters onto the stack in the reversed order, i.e., from right to left; it is this order in which the imported function reads parameters passed to it; - parameters are passed by their values, except for those explicitely passed by a link (in our case, these are lines); - on reading the parameters passed to it, the imported function will flush the stack by itself. At describing of the imported function prototype, it is useless to use parameters with default values as all parameters must be passed explicitely to the imported function. If the call for an imported function failed (expert settings do not allow DLL imports, or the corresponding library could not be loaded for any reason), the expert stops working putting the corresponding me ssage into the "expert stopped" journal. At that, the expert will not be launched until it is re -initialized. An expert can be re-initialized as a result of recompiling or opening of the expert properties table and pressing of OK button. In the executing sub-system of the client terminal, the error code can be stored, in the case of its occurring at an mql4 program execution. There is a specific last_error variable provided for every executable mql4 program. Before the init function is run, the last_error variable has been zeroized. If an error occurs during the process of calculation or that of calling the built -in function, the last_error variable takes the corresponding error code. Value stored in this variable can be got using the GetLastError function. At that, the last_error variable will be zeroized. There is a number of critical errors that cause immediate stopping of program execution: Constant Value Description ERR_WRONG_FUNCTION_POINTER ERR_NO_MEMORY_FOR_CALL_STACK ERR_RECURSIVE_STACK_OVERFLOW 4001 4003 4004 At calling of an internal function, a wrong function pointer has been detected At calling of an internal function, it is impossible to reallocate memory for the function calls stack The data stack is overflowed at the recursive function call At calling of an internal function, it is impossible to allocate memory for passing the string as a function parameter It is impossible to allocate the temporary buffer for string operations At assignment, it is impossible to reallocate memory for a string in an array At assignment, too long resulting string to be placed into the service buffer (no possibility to reallocate for the service buffer) Dividing by 0 when taking the remainder of the division Dividing by 0

ERR_NO_MEMORY_FOR_PARAM_STRING 4006 ERR_NO_MEMORY_FOR_TEMP_STRING ERR_NO_MEMORY_FOR_ARRAYSTRING ERR_TOO_LONG_STRING ERR_REMAINDER_FROM_ZERO_DIVIDE ERR_ZERO_DIVIDE 4007 4010 4011 4012 4013

ERR_UNKNOWN_COMMAND 4014 Unknown instruction If the program stopped working due to a critical error, the code of this error can be read at the next launching of the start or deinit function using the GetLastError() function. The last_error variable is not zeroized before the st art or deinit function starts. There is a number of critical errors referred to imported functions call that cause immediate stopping of expert advisor or custom indicator execution the start function will not be launched until expert or indicator is re -initialized. Constant Value Description ERR_CANNOT_LOAD_LIBRARY ERR_CANNOT_CALL_FUNCTION ERR_DLL_CALLS_NOT_ALLOWED 4018 4019 4017 At calling of an imported function, loading error of dll or ex4 library occurred At calling of an imported function, it was found out that dll or ex4 library did not contain the called function At calling of an imported dll function, it was found out that dll imports were not allowed At calling of an ex4 function, it was found out that external ex4 imports were not allowed Description Attempt to access an array item number of which is out of the array range Not initialized string; no value was assigned to the string being an operand in an expression Not initialized string in the array string; no value was assigned to the string item being

ERR_EXTERNAL_CALLS_NOT_ALLOWED 4020 Other errors do not interrupt program execution. Constant Value ERR_ARRAY_INDEX_OUT_OF_RANGE ERR_NOT_INITIALIZED_STRING ERR_NOT_INITIALIZED_ARRAYSTRING 4002 4008 4009

an operand in an expression ERR_NO_MEMORY_FOR_RETURNED_STR 4021 It is impossible to reallocate memory for a string returned from function The ERR_NO_MQLERROR (4000) code is never generated. There is a number of errors which are possible only as a result of software or hardware fail ure.If any errors described below occur repeatedly, one should contact the developers. Constant Value Description ERR_WRONG_FUNCTION_POINTER ERR_UNKNOWN_COMMAND ERR_NOT_INITIALIZED_ARRAY ERR_STRING_FUNCTION_INTERNAL ERR_TRADE_ERROR 4001 4014 4016 4052 4067 At calling of an internal function, a wrong function pointer has been detected Unknown instruction Not initialized array Invalid parameters count passed into built -in function String function internal error Trade function internal error

ERR_INVALID_FUNCTION_PARAMSCNT 4050

ERR_SOME_OBJECT_ERROR 4207 Object function internal error There are some functions that always change the last_error variable value. Function Error codes ERR_STRING_PARAMETER_EXPECTED (4062), ERR_INTEGER_PARAMETER_EXPECTED (4063), AccountFreeMarginCheck ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_UNKNOWN_SYMBOL (4106), ERR_NOT_ENOUGH_MONEY (134) ERR_CUSTOM_INDICATOR_ERROR (4055), ERR_STRING_PARAMETER_EXPECTED (4062), ERR_INTEGER_PARAMETER_EXPECTED (4063), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INVALID_PRICE_PARAM (4107), ERR_UNKNOWN_SYMBOL (4106), ERR_TRADE_NOT_ALLOWED (4109), ERR_LONGS_NOT_ALLOWED (4110), ERR_SHORTS_NOT_ALLOWED (4111), code returned by trade server ERR_CUSTOM_INDICATOR_ERROR (4055), ERR_INTEGER_PARAMETER_EXPECTED (4063), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INVALID_PRICE_PARAM (4107), ERR_INVALID_TICKET (4108), ERR_UNKNOWN_SYMBOL (4106), ERR_TRADE_NOT_ALLOWED (4109), code returned by trade server ERR_CUSTOM_INDICATOR_ERROR (4055), ERR_INTEGER_PARAMETER_EXPECTED (4063), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INVALID_TICKET (4108), ERR_UNKNOWN_SYMBOL (4106), ERR_TRADE_NOT_ALLOWED (4109), code returned by trade server ERR_CUSTOM_INDICATOR_ERROR (4055), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INVALID_TICKET (4108), ERR_UNKNOWN_SYMBOL (4106), ERR_TRADE_NOT_ALLOWED (4109), code returned by trade server ERR_CUSTOM_INDICATOR_ERROR (4055), ERR_INTEGER_PARAMETER_EXPECTED (4063), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INVALID_PRICE_PARAM (4107), ERR_INVALID_TICKET (4108), ERR_UNKNOWN_SYMBOL (4106), ERR_T RADE_NOT_ALLOWED (4109), code returned by trade server

OrderSend

OrderClose

OrderCloseBy

OrderDelete

OrderModify

GetLastError ERR_NO_ERROR (0) Some functions change value of the last_error variable only if an error occurs. Function ArrayBsearch ArrayCopy ArrayCopyRates

Error codes

ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INCOMPATIBLE_ARRAYS (4056), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INCOMPATIBLE_ARRAYS (4056), ERR_STRING_PARAMETER_EXPECTED (4062), ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INCORRECT_SERIESARRAY_USING (4054), ERR_INCOMPATIBLE_ARRAYS (4056), ERR_STRING_PARAMETER_EXPECTED (4062), ERR_HISTORY_WILL_UPDATED (4066), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INVALID_FUNCTION_PARAMVALUE (4051)

ArrayCopySeries ArrayDimension ArrayGetAsSeries ArrayInitialize ArrayIsSeries ArrayMaximum ArrayMinimum

ArrayRange ArrayResize ArraySetAsSeries ArraySize ArraySort FileClose FileDelete FileFlush FileIsEnding FileIsLineEnding FileOpen

ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INTEGER_PARAMETER_EXPECTED (4063), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053), ERR_INCORRECT_SERIESARRAY_USING (4054), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_WRONG_FILE_NAME (4101), ERR_SOME_FILE_ERROR (4100) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_TOO_MANY_OPENED_FILES (4102), ERR_WRONG_FILE_NAME (4101), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_SOME_FILE_ERROR (4100), ERR_CANNOT_OPEN_FILE (4103) ERR_TOO_MANY_OPENED_FILES (4102), ERR_WRONG_FILE_NAME (4101), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_SOME_FILE_ERROR (4100), ERR_CANNOT_OPEN_FILE (4103) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCOMPATIBLE_FILEACCESS (4104), ERR_SOME_ARRAY_ERROR (4053), ERR_SOME_FILE_ERROR (4100), ERR_END_OF_FILE (4099) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCOMPATIBLE_FILEACCESS (4104), ERR_END_OF_FILE (4099) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCOMPATIBLE_FILEACCESS (4104), ERR_END_OF_FILE (4099) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCOMPATIBLE_FILEACCESS (4104), ERR_SOME_FILE_ERROR (4100), ERR_END_OF_FILE (4099) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCOMPATIBLE_FILEACCESS (4104), ERR_SOME_FILE_ERROR (4100), ERR_TOO_LONG_STRING (4011), ERR_END_OF_FILE (4099) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_SOME_FILE_ERROR (4100) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCOMPATIBLE_FILEACCESS (4104), ERR_SOME_FILE_ERROR (4100) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCOMPATIBLE_FILEACCESS (4104), ERR_SOME_FILE_ERROR (4100) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCOMPATIBLE_FILEACCESS (4104), ERR_SOME_FILE_ERROR (4100), ERR_STRING_PARAMETER_EXPECTED (4062) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCOMPATIBLE_FILEACCESS (4104), ERR_SOME_FILE_ERROR (4100), ERR_STRING_PARAMETER_EXPECTED (4062) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_GLOBAL_VARIABLES_PROCESSING (4057) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_GLOBAL_VARIABLE_NOT_FOUND (4058) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_GLOBAL_VARIABLES_PROCESSING (4057) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_GLOBAL_VARIABLES_PROCESSING (4057), ERR_GLOBAL_VARIABLE_NOT_FOUND (4058) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_HISTORY_WILL_UPDATED (4066) ERR_ARRAY_AS_PARAMETER_EXPECTED (4065), ERR_SOME_ARRAY_ERROR (4053) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_INVALID_FUNCTION_PARAMVALUE (4051)

FileOpenHistory FileReadArray FileReadDouble FileReadInteger FileReadNumber FileReadString FileSeek FileSize FileTell FileWrite FileWriteDouble FileWriteInteger FileWriteString FileWriteArray GlobalVariableCheck GlobalVariableDel GlobalVariableGet GlobalVariablesDeleteAll GlobalVariableSet

GlobalVariableSetOnCondition ERR_STRING_PARAMETER_EXPECTED (4062), ERR_GLOBAL_VARIABLE_NOT_FOUND (4058) iCustom technical indicators, series access functions technical indicators OnArray IndicatorBuffers IndicatorDigits IndicatorShortName

MarketInfo MathArccos MathArcsin MathMod MathSqrt MessageBox ObjectCreate ObjectDelete ObjectDescription ObjectFind ObjectGet ObjectGetFiboDescription ObjectGetShiftByValue ObjectGetValueByShift ObjectMove ObjectName ObjectSet ObjectSetText

ERR_STRING_PARAMETER_EXPECTED (4062), ERR_FUNC_NOT_ALLOWED_IN_TESTING (4059), ERR_UNKNOWN_SYMBOL (4106), ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_ZERO_DIVIDE (4013) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_FUNC_NOT_ALLOWED_IN_TESTING (4059), ERR_CUSTOM_INDICATOR_ERROR (4055), ERR_STRING_PARAMETER_EXPECTED (4062) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_UNKNOWN_OBJECT_TYPE (4203), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_OBJECT_ALREADY_EXISTS (4200), ERR_NO_SPECIFIED_SUBWINDOW (4206) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_OBJECT_DOES_NOT_EXIST (4202) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_OBJECT_DOES_NOT_EXIST (4202) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_OBJECT_DOES_NOT_EXIST (4202), ERR_UNKNOWN_OBJECT_PROPERTY (4201) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_OBJECT_DOES_NOT_EXIST (4202), ERR_UNKNOWN_OBJECT_TYPE (4203), ERR_UNKNOWN_OBJECT_PROPERTY (4201) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_OBJECT_DOES_NOT_EXIST (4202), ERR_OBJECT_COORDINATES_ERROR (4205) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_OBJECT_DOES_NOT_EXIST (4202), ERR_OBJECT_COORDINATES_ERROR (4205) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_OBJECT_DOES_NOT_EXIST (4202) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_ARRAY_INDEX_OUT_OF_RANGE (4002) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_OBJECT_DOES_NOT_EXIST (4202), ERR_UNKNOWN_OBJECT_PROPERTY (4201) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_OBJECT_DOES_NOT_EXIST (4202) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_STRING_PARAMETER_EXPECTED (4062), ERR_OBJECT_DOES_NOT_EXIST (4202), ERR_UNKNOWN_OBJECT_TYPE (4203), ERR_UNKNOWN_OBJECT_PROPERTY (4201) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NO_OBJECT_NAME (4204), ERR_OBJECT_DOES_NOT_EXIST (4202) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105) ERR_NO_ORDER_SELECTED (4105)

ObjectSetFiboDescription

ObjectType OrderClosePrice OrderCloseTime OrderComment OrderCommission OrderExpiration OrderLots OrderMagicNumber OrderOpenPrice OrderOpenTime OrderPrint OrderProfit OrderStopLoss OrderSwap OrderSymbol OrderTakeProfit OrderTicket OrderType

PlaySound SendFTP SendMail SetIndexArrow SetIndexBuffer SetIndexDrawBegin SetIndexEmptyValue SetIndexLabel SetIndexShift SetIndexStyle SetLevelValue Sleep StringFind StringGetChar StringLen StringSetChar StringSubstr StringTrimLeft StringTrimRight WindowIsVisible WindowFind WindowHandle

ERR_WRONG_FILE_NAME (4101) ERR_FUNC_NOT_ALLOWED_IN_TESTING (4059), ERR_CUSTOM_INDICATOR_ERROR (4055), ERR_STRING_PARAMETER_EXPECTED (4062) ERR_FUNC_NOT_ALLOWED_IN_TESTING (4059), ERR_STRING_PARAMETER_EXPECTED (4062), ERR_FUNCTION_NOT_CONFIRMED (4060), ERR_SEND_MAIL_ERROR (4061) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_INCORRECT_SERIESARRAY_USING (4054), ERR_INCOMPATIBLE_ARRAYS (4056) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_STRING_PARAMETER_EXPECTED (4062) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_INVALID_FUNCTION_PARAMVALUE (4051) ERR_CUSTOM_INDICATOR_ERROR (4055) ERR_STRING_PARAMETER_EXPECTED (4062) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NOT_INITIALIZED_STRING (4008), ERR_ARRAY_INDEX_OUT_OF_RANGE (4002) ERR_STRING_PARAMETER_EXPECTED (4062) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_INVALID_FUNCTION_PARAMVALUE (4051), ERR_NOT_INITIALIZED_STRING (4008), ERR_TOO_LONG_STRING (4011), ERR_ARRAY_INDEX_OUT_OF_RANGE (4002) ERR_STRING_PARAMETER_EXPECTED (4062), ERR_TOO_LONG_STRING (4011) ERR_STRING_PARAMETER_EXPECTED (4062) ERR_STRING_PARAMETER_EXPECTED (4062) ERR_FUNC_NOT_ALLOWED_IN_TESTING (4059) ERR_FUNC_NOT_ALLOWED_IN_TESTING (4059), ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NOT_INITIALIZED_STRING (4008) ERR_FUNC_NOT_ALLOWED_IN_TESTING (4059), ERR_STRING_PARAMETER_EXPECTED (4062), ERR_NOT_INITIALIZED_STRING (4008)

WindowScreenShot ERR_WRONG_FILE_NAME (4101), ERR_INVALID_FUNCTION_PARAMVALUE (4051) Other functions never change the last_error variable value. AccountBalance, AccountCompany, AccountCredit, AccountCurrency, AccountEquity, AccountFreeMargin, AccountLeverage, AccountMargin, AccountName, AccountNumber, AccountProfit, AccountServer, Alert, CharToStr, Comment, Day, DayOfWeek, DayOfYear, DoubleToStr, GetTickCount, HideTestIndicators, Hour, IndicatorCounted, IsConnected, IsDemo, IsDllsAllowed, IsExpertEnabled, IsLibrariesAllowed, IsOptimization, IsStopped, IsTesting, IsTradeAllowed, IsTradeContextBusy, IsVisualMode, MathAbs, MathArctan, MathCeil, MathCos, MathExp, MathFloor, MathLog, MathMax, MathMin, MathPow, MathRand, MathRound, MathSin, MathSrand, MathTan, Minute, Month, NormalizeDouble, ObjectsDeleteAll, ObjectsTotal, OrderSelect, OrdersHistoryTotal, Period, Print, RefreshRates, Seconds, SetLevelStyle, StringConcatenate, StrToTime, StrToDouble, Symbol, TerminalCompany, TerminalName, TerminalPath, TimeCurrent, TimeDay, TimeDayOfWeek, TimeDayOfYear, TimeHour, TimeLocal, TimeMinute, TimeMonth, TimeSeconds, TimeToStr, TimeYear, UninitializeReason, WindowBarsPerChart, WindowFirstVisibleBar, WindowPriceOnDropped, WindowRedraw, WindowTimeOnDropped, WindowsTotal, WindowOnDropped, WindowXOnDropped, WindowYOnDropped, Year A group of functions to access to the active account information. double AccountBalance() Returns balance value of the current account (the amount of money on the account). Sample: Print("Account balance = ",AccountBalance()); ) double AccountCredit( Returns credit value of the current account. Sample: Print("Account number ", AccountCredit()); ) string AccountCompany( Returns the brokerage company name where the current account was registered. 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. Equity calculation depends on trading server settings. Sample: Print("Account equity = ",AccountEquity()); ) double AccountFreeMargin( Returns free margin value of the current account. Sample: Print("Account free margin = ",AccountFreeMargin()); string symbol, int cmd, double volume) double AccountFreeMarginCheck( Returns free margin that remains after the specified position has been opened at the current price on the current account. If the free margin is insufficient, an error 134 (ERR_NOT_ENOUGH_MONEY) will be g enerated. Parameters: symbol - Symbol for trading operation. cmd - Operation type. It can be either OP_BUY or OP_SELL. volume - Number of lots. Sample: if(AccountFreeMarginCheck(Symbol(),OP_BUY,Lots)<=0 || GetLastError()==134) return; ) double AccountFreeMarginMode( Calculation mode of free margin allowed to open positions on the current account. The calculation mode can take the following values: 0 - floating profit/loss is not used for calculation; 1 - both floating profit and loss on open positions on the current account are used for free margin calculation; 2 - only profit value is used for calculation, the current loss on ope n positions is not considered; 3 - only loss value is used for calculation, the current loss on open positions is not considered. Sample: if(AccountFreeMarginMode()==0) Print("Floating Profit/Loss do not use."); ) 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()); ) string AccountServer( Returns the connected server name. Sample: Print("Server name is ", AccountServer()); ) int AccountStopoutLevel( Returns the value of the Stop Out level. Sample: Print("StopOut level = ", AccountStopoutLevel()); ) int AccountStopoutMode( Returns the calculation mode for the Stop Out level. Calculation mode can take the following values: 0 - calculation of percentage ratio between margin and equity; 1 - comparison of the free margin level to the absolute value. Sample: int level=AccountStopoutLevel(); if(AccountStopoutMode()==0) Print("StopOut level = ", level, "%");

else Print("StopOut level = ", level, " ", AccountCurrency()); A group of functions to work with arrays. Arrays are allowed to be maximum four -dimensional. Each dimension is indexed from 0 to dimension size-1. In a particular case of a one -dimensional array of 50 elements, calling of the first element will appear as array[0], of the last one - as array[49]. Using these functions (except for those which change quantitative and qualitative characteristics of the array) one can proce ss predefined time series Time[], Open[], High[], Low[], Close[], Volume[] int ArrayBsearch(double array[], double value, int count=WHOLE_ARRAY, int start=0, int direction=MODE_ASCEND) If the element with the specified value doesn't exist in the array, the function returns the index of the nearest smallest va lue of the elements between which the searched value is located. The function cannot be used with string arrays and series arrays (with the exception of the series array of the bar open time). Note: Binary search processes only sorted arrays. To sort numeric arrays use the ArraySort() function. Parameters: array[] - The numeric array to search for. value count start - The value to search for. - Count of elements to search for. By default, it searches in the whole array. - Starting index to search for. By default, the search starts at the first element.

direction - Search direction. It can be any of the following values: MODE_ASCEND searching in forward direction, MODE_DESCEND searching in backward direction. Sample: datetime daytimes[]; int shift=10,dayshift; // All the Time[] series 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(void 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[], a nd bool[] can be copied as arrays of the same type. Returns the amount of copied elements. Parameters: dest[] - Destination array. source[] start_dest - Source array. - 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]; // array2 is filled with some data ArrayCopyRates(array1); ArrayCopy(array2,array1,0,0,60); // array2 is having the first 10 bars from the history now (first bar considered as bar with index [Bars -1]) ArrayCopy(array2,array1,0,Bars*6-60,60); // array2 is having the last 10 bars from the history now (last bar considered as current bar, bar wit index [0]) int ArrayCopyRates(void dest_array[], string symbol=NULL, int timeframe=0) Copies rates to the two-dimensional array from chart RateInfo array and returns copied bars amount, or -1 if failed. First dimension of RateInfo array contains bars amount, second dimension has 6 elements: 0 - time, 1 - open, 2 - low, 3 - high, 4 - close, 5 - volume. If data (symbol name and/or timeframe differ from the current ones) are requested from another chart, the situation is possib le that the corresponding chart was not opened in the client terminal and the necessary data must be requested from the server. In this case, error ERR_HISTORY_WILL_UPDATED (4066 - the requested history data are under updating) will be placed in th e last_error variable, and one will has to re-request (see example of ArrayCopySeries()). Notes: This rates array is normally used to pass data to a DLL function. Memory is not really allocated for data array, and no real copying is performed. When such an array is accessed, the access w ill be redirected. Parameters:

dest_array[] - Reference to the two-dimensional destination array of double type . symbol - Symbol name (currency pair name) timeframe - Timeframe. It can be any of the listed timeframes values. Sample: double array1[][6]; ArrayCopyRates(array1,"EURUSD", PERIOD_H1); Print("Current bar ",TimeToStr(array1[0][0]),"Open", array1[0][1]); int ArrayCopySeries(void array[], int series_index, string symbol=NULL, int timeframe=0) Copies a series array to another one and returns the count of the copied elements. There is no real memory allocation for data array and nothing is copied. When such an array is accessed, the access is redire cted. Excluded are arrays that are assigned as indexed ones in custom indicators. In this case, data are really copied. If data are copied from another chart with different symbol and/or timeframe, it is possible that the necessary data will lac k. In this case, error ERR_HISTORY_WILL_UPDATED (4066 - requested history data under updating) will be placed into the last_error variable, and there will be necessary to retry copying after a certain period of time. Note: If series_index is MODE_TIME, the array to be passed to the function must be of the datetime type. Parameters: array[] - Reference to the destination one-dimensional numeric array. series_index - Series array identifier. It must be one of series array listed identifiers values. symbol - Symbol name (the name of the currency pair) timeframe - Timeframe of the chart. It can be any of Timeframe list values. Sample: datetime daytimes[]; int shift=10,dayshift,error; //---- the Time[] array was sroted in the descending order ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1); error=GetLastError(); if(error==4066) { //---- make two more attempts to read for(int i=0;i<2; i++) { Sleep(5000); ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1); //---- check the current daily bar time datetime last_day=daytimes[0]; if(Year()==TimeYear(last_day) && Month()==TimeMonth(last_day) && Day()==TimeDay(last_day)) break; } } if(Time[shift]>=daytimes[0]) dayshift=0; else { dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_AR RAY,0,MODE_DESCEND); if(Period()<PERIOD_D1) dayshift++; } Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ", TimeToStr(daytimes[dayshift])); int ArrayDimension( object array[]) Returns the multidimensional array rank. Parameters: array[] - Array for which the rank will be returned. Sample: int num_array[10][5]; int dim_size; dim_size=ArrayDimension(num_array); // dim_size=2 bool ArrayGetAsSeries( object array[]) Returns TRUE if array is organized as a series array (array elements are indexed from the last to the first one), otherwise r eturns FALSE. Parameters: array[] - Array to be checked. 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( void array[], double value) Sets all elements of a numeric array to the same value. Returns the count of initialized elements. Note: It is not recommended to initialize index buffers in the custom indicator init() function as such functions are initialized automatically with an "empty value" at allocation and re-allocation of buffers. Parameters:

array[] - Numeric array to be initialized. value - New value to be set. Sample: //---- initializing of all array elements with 2.1 double myarray[10]; ArrayInitialize(myarray,2.1); bool ArrayIsSeries( object array[]) Returns TRUE if the array under check is a series array (Time[],Open[],Close[],High[],Low[], or Volume[]), otherwise returns FALSE. Parameters: array[] - Array under 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 the element with maximum value. The function returns position of this maximum element in the array. Parameters: array[] - The numeric array to search in. count - The amount of elements to search in. start - Initial search 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 the element with minimum value. The function returns position of this minimum element in the array. Parameters: array[] - The numeric array to search in. count - The amount of elements to search in. start - Initial search index. Sample: double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9}; int minValueidx=ArrayMinimum(num_array); Print("Min value = ", num_array[minValueIdx]); int ArrayRange(object array[], int range_index) Returns the count of elements in the given 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( void array[], int new_size) Sets a new size for the first dimension. If executed successfully, it returns count of all elements contained in the array af ter resizing, otherwise, returns -1, and array is not resized. Note: Array declared at a local level in a function and resized will remain unchanged after the function has completed its op eration. After the function has been recalled, such array will have a size diffe ring from the declared one. Parameters: array[] - Array to resize. new_size - New size for the first dimension. Sample: double array1[][4]; int element_count=ArrayResize(array1, 20); // new size - 80 elements bool ArraySetAsSeries( void array[], bool set) Sets indexing direction of the array. If the set parameter has the TRUE value, the array will be indexed in a reversed order, i.e., the last element has a zero index. The FALSE value sets a standard indexing order. The function returns the previous status. Parameters: array[] - The numeric array to set. set - Array indexing order. 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. For a one -dimensional array, the value to be returned by the ArraySize function is equal to that of ArrayRange(array,0). Parameters: array[] - Array of any type. Sample: int count=ArraySize(array1); for(int i=0; i<count; i++) { // some calculations. } int ArraySort(void 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 be sorted. count start sort_dir - Count of elements to be sorted. - Starting index. - 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,WHOLE_ARRAY,0,MODE_DESCEND); // now array is sorted 9,6,4,3,1 A group of functions that allow determining of the current status of the client terminal, including the environment status of the MQL4 program. int GetLastError() The function returns the last occurred error, then the value of special last_error variable where the last error code is stored will be zeroized. So, the next call for GetLastError() will return 0. Sample: int err; int handle=FileOpen("somefile.dat", FILE_READ|FILE_BIN); if(handle<1) { err=GetLastError(); Print("error(",err,"): ",ErrorDescription(err)); return(0); } bool IsConnected() The function returns the status of the main connection between client terminal and server that performs data pumping. It retu rns TRUE if connection to the server was successfully established, otherwise, it returns FALSE. Sample: if(!IsConnected()) { Print("No connection!"); return(0); } // Expert body that needs the connection opened // ... bool IsDemo() Returns TRUE if the expert runs on a demo account, otherwise returns FALSE. Sample: if(IsDemo()) Print("I work at a demo account"); else Print("I work at a real account"); bool IsDllsAllowed( ) Returns TRUE if the function DLL 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 functio ns MessageBoxA(0,"an message","Message",MB_OK); ) bool IsExpertEnabled( Returns TRUE if expert adwisors are enabled for running, otherwise returns FALSE. Sample: while(!IsStopped()) { ... if(!IsExpertEnabled()) break; } bool IsLibrariesAllowed( ) Returns TRUE if the 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."); return(0); } // expert body that calls external DLL functions somefunc(); bool IsOptimization( ) Returns TRUE if expert runs in the strategy tester optimization mode, otherwise returns FALSE. Sample: if(IsOptimization()) return(0); bool IsStopped() Returns TRUE if the program (an expert or a script) has been commanded to stop its operation, otherwise returns FALSE. The pr ogram can continue operation for 2.5 seconds more before the client terminal stops its performing forcedly. Sample: while(expr!=false) { if(IsStopped()==true) return(0); // a long run-time 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 the expert is allowed to trade and a thread for trading is not occupied, otherwise returns FALSE. See also IsDllsAllowed() , IsLibrariesAllowed(), IsTradeContextBusy(). Sample: if(IsTradeAllowed()) Print("Trade allowed"); bool IsTradeContextBusy() Returns TRUE if a thread for trading is occupied by another expert advisor, otherwise returns FALSE. See also IsTradeAllowed(). Sample: if(IsTradeContextBusy()) Print("Trade context is busy. Please wait"); bool IsVisualMode( ) Returns TRUE if the expert is tested with checked "Visual Mode" button, otherwise returns FALSE. Sample: if(IsVisualMode()) Comment("Visual mode turned on"); int UninitializeReason( ) Returns the code of the uninitialization reason for the experts, custom indicators, and scripts. The returned values can be o nes of Uninitialize reason codes. This function can also be called in function init() to analyze the reasons for deinitialization of the previour launch. Sample: // this is example int deinit()

{ switch(UninitializeReason()) { case REASON_CHARTCLOSE: case REASON_REMOVE: CleanUp(); break; // cleaning up and deallocation of all resources. case REASON_RECOMPILE: case REASON_CHARTCHANGE: case REASON_PARAMETERS: case REASON_ACCOUNT: StoreData(); break; // prepare to restart } //... } Functions returning information about client terminal. string TerminalCompany() Returns the name of company owning the client terminal. Sample: Print("Company name is ",TerminalCompany()); string TerminalName() Returns client terminal name. Sample: Print("Terminal name is ",TerminalName()); string TerminalPath() Returns the directory, from which the client terminal was launched. Sample: Print("Working directory is ",TerminalPath()); General-purpose functions not included into any specialized groups. void Alert(...) Displays a dialog box containing the user -defined data. Parameters can be of any type. Amount of passed parameters cannot exceed 64. Arrays cannot be passed to the Alert function. Arrays should be output elementwise. Data of double type output with 4 decimal digits after point. To output with more precision use DoubleToStr() function. Data of bool, datetime and color types will be output as its numeric presentation. To output values of datetime type as string convert it by TimeToStr() function. See also Comment() and Print() functions. Parameters: ... - Any values, separated by commas. It can be up to 64 parameters. Sample: if(Close[0]>SignalLevel) Alert("Close price coming ", Close[0],"!!!"); void Comment(...) The function outputs the comment defined by the user in the left top corner of the chart. Parameters can be of any type. Amou nt of passed parameters cannot exceed 64. Arrays cannot be passed to the Comment() function. Arrays should be output elementwise. Data of double type output with 4 digits after the decimal point. To output with more precision, use the DoubleToStr() function. Data of bool, datetime and color types will be output as their numeric presentation. To output values of datetime type as strings, convert them with the TimeToStr() function. See also Alert() and Print() functions. Parameters: ... - =Any values separated by commas. It can be up to 64 parameters. Sample: double free=AccountFreeMargin(); Comment("Account free margin is ",DoubleToStr(free,2)," \n","Current time is ",TimeToStr(TimeCurrent())); int GetTickCount() The GetTickCount() function retrieves the number of milliseconds that have elapsed since the system was started. It is limite d to the resolution of the system timer. Sample: int start=GetTickCount(); // some hard calculations... Print("Calculation time is ", GetTickCount() -start, " milliseconds."); double MarketInfo( string symbol, int type) Returns various data about securities listed in the Market Watch window. A part of information about the current security is stored in predefined variables. Parameters: symbol - Security symbol. type - Request identifier that defines the type of information to be returned. Can be any of values of request identifiers. Sample:

double bid =MarketInfo("EURUSD",MODE_BID); double ask =MarketInfo("EURUSD",MODE_ASK); double point =MarketInfo("EURUSD",MODE_POINT); int digits=MarketInfo("EURUSD",MODE_DIGITS); int spread=MarketInfo("EURUSD",MODE_SPREAD); int MessageBox(string text=NULL, string caption=NULL, int flags=EMPTY) The MessageBox function creates, displays, and operates message box. The message box contains an application -defined message and header, as well as a random combination of predefined icons and push buttons. If the function succeeds, the returned value is o ne of the MessageBox return code values. The function cannot be called from custom indicators since they are executed within interface thread and may n ot decelerate it. Parameters: text - Optional text that contains the message to be displayed. caption - Optional text to be displayed in the header of the dialog box. If this parameter is NULL, the expert name will be displayed i n the header. flags - Optional flags that determine the type and behavior of the dialog box. They can represent a conbination of flags from the following groups. Sample: #include <WinUser32.mqh> if(ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045)==false) { int ret=MessageBox(" ObjectCreate() function returned the "+GetLastError()+" error \nContinue?", "Question", MB_YESNO|MB_ICONQUESTION); if(ret==IDNO) return(false); } // continue void PlaySound(string filename) Function plays a sound file. The file must be located in the terminal_dir\sounds directory or in its subdirectory. Parameters: filename - Path to the sound file. Sample: if(IsDemo()) PlaySound("alert.wav"); void Print(...) Prints a message to the experts log. Parameters can be of any type. Amount of passed parameters cannot exceed 64. Arrays cannot be passed to the Print() function. Arrays should be printed elementwise. Data of double type are printed with 4 decimal digits after point. To output more precisely, use the DoubleToStr() function. Data of bool, datetime and color types will be printed as their numeric presentation. To print values of datetime type as string, convert them with the TimeToStr() function. See also Alert() and Comment() functions. Parameters: ... - Any values separated by commas. It can be up to 64 parameters. Sample: Print("Account free margin is ", AccountFreeMargin()); Print("Current time is ", TimeToStr(TimeCurrent())); 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 SendFTP(string filename, string ftp_path=NULL) Sends the file to the FTP server set in the Tools ->Options->Publisher tab. If the attempt fails, it retuns FALSE. The function does not operate in the testing mode. This function cannot be called from custom indicators, ei ther. The file to be sent must be stored in the terminal_directory\experts\files folder or in its sub -folders. It will not be sent if there is no FTP address and/or access password specified in settings. Parameters: filename - File to be sent. ftp_path - FTP path. If the path has not been specified, the path described in settings will be used. Sample: int lasterror=0; if(!SendFTP("report.txt")) lasterror=GetLastError(); void SendMail(string subject, string some_text) Sends a message to the e-mail set in the Tools ->Options->EMail tab. The sending can be disabled in settings, or it can be omitted to specify the e -mail address. To get the detailed error information, one has to call the GetLastError() function. 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,Digits)); void Sleep(int milliseconds) The Sleep() function suspends execution of the current expert within the specified interval. The Sleep() function cannot be called from custom indicators since they calculate in the interface thread and may not decelerate it. The checking of the expert stop flag status every 0.1 second has been built into the function. Parameters: milliseconds - Sleeping interval in milliseconds. Sample: //---- wait for 10 seconds Sleep(10000); A group of functions that provide conversion of data from one format into another. The NormalizeDouble() function must be specially noted as it provides the necessary accuracy of the price presentation. In trading operations, no unnormalized prices may be used if their accuracy even a digit exceeds that required by the trade server. string CharToStr(int char_code) Conversion of the symbol code into a one-character string. Parameters: char_code - ASCII char code. Sample: string str="WORL" + CharToStr(44); // 44 is code for 'D' // the resulting string will be WORLD string DoubleToStr(double value, int digits) Returns text string with the specified numerical value converted into a specified precision format. Parameters: value - Floating point value. digits - Precision format, number of digits after decimal point (0 -8). Sample: string value=DoubleToStr(1.28473418, 5); // the value is "1.28473" double NormalizeDouble( double value, int digits) Rounds the floating point value to the given precision. Returns normalized value of the double type. The calculated StopLoss and TakeProfit values, as well as open price of pending orders must be normalized with a precision the value of which is stored in the pre-defined variable of Digits. Parameters: value - Floating point value. digits - Precision format, number of digits after decimal point (0 -8). Sample: double var1=0.123456789; Print(DoubleToStr(NormalizeDouble(var1,5),8)); // output: 0.12346000 double StrToDouble(string value) Converts string representation of number to double type (double -precision format with floating point). Parameters: value - String containing the number character representation format. Sample: double var=StrToDouble("103.2812"); int StrToInteger(string value) Converts string containing the value character representation into a value of the int (integer) type. Parameters: value - String containing the integer character representation format. Sample: int var1=StrToInteger("1024"); datetime StrToTime(string value) Converts string in the format "yyyy.mm.dd hh:mi" to datetime type (the amount of seconds that have passed since 1 Jan., 1970) . Parameters: value - String value of date/time format as "yyyy.mm.dd hh:mi". Sample: datetime var1; var1=StrToTime("2003.8.12 17:35"); var1=StrToTime("17:35"); // returns the current date with the given time var1=StrToTime("2003.8.12"); // returns the date with the midnight time of "00:00" string TimeToStr(datetime value, int mode=TIME_DATE|TIME_MINUTES)

Converts value containing time in seconds that has passed since January 1, 1970, into a string of "yyyy.mm.dd hh:mi" format. Parameters: value - Positive amount of seconds that have passed since 00:00, January 1, 1970 . mode - Optional data output mode can be one or combination of: TIME_DATE gets result as "yyyy.mm.dd", TIME_MINUTES gets result as "hh:mi", TIME_SECONDS gets result as "hh:mi:ss".

Sample: string var1=TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS); A group of functions used at producing of custom indicators. These functions cannot be used in experts and scripts. void IndicatorBuffers(int count) Allocates memory for buffers used for custom indicator calculations. The amount of buffers cannot exceed 8 or be less than th e value given in the indicator_buffers property. If custom indica tor requires additional buffers for counting, this function must be used for specifying of the total amount of buffers. Parameters: count - Amount of buffers to be allocated. Should be within the range between indicator_buffers and 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_DIGI TS)+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() The function returns the amount of bars not changed after the indicator had been launched last. The most calculated bars do not need any recalculation. In most cases, same count of index values do not need for recalculation. The function is used to optimize calculating. Note: The latest bar is not considered to be calculated and, in the most cases, it is necessary to r ecalculate only this bar. However, there occur some boundary cases where custom indicator is called from the expert at the first tick of the new bar. It is possible that the las t tick of the previous bar had not been processed (because the last-but-one tick was being processed when this last tick came), the custom indicator was not called and it was not calculated because of this. To avoid indicator calculation errors in such situations, the IndicatorCounted( ) function returns the count of bars minus one. Sample: int start() { int limit; int counted_bars=IndicatorCounted(); //---- check for possible errors if(counted_bars<0) return(-1); //---- the 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 precision format (the count of digits after decimal point) to visualize indicator values. The symbol price preicision is used by default, the indicator being attached to this symbol chart. Parameters: digits - Precision format, the count of digits after decimal point. Sample: int init() { //---- 2 additional buffers are used for counting. IndicatorBuffers(3); //---- setting of drawing parameters SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3); SetIndexDrawBegin(0,SignalSMA); IndicatorDigits(Digits+2); //---- 3 allocated buffers of an indicator SetIndexBuffer(0,ind_buffer1); SetIndexBuffer(1,ind_buffer2); SetIndexBuffer(2,ind_buffer3); //---- "short name" for DataWindow and indicator subwindow IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } void IndicatorShortName( string name) Sets the "short" name of a custom indicator to be shown in the DataWindow and in the chart subwindow. Parameters: name - New short name. Sample: 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 an arrow symbol for indicators line of the DRAW_ARROW type. Arrow codes out of range 33 to 255 cannot be used. Parameters: index - Line index. Must lie between 0 and 7. code - Symbol code from Wingdings font or Array constants. Sample: int init() { //---- 2 allocated indicator buffers SetIndexBuffer(0,ExtUppperBuffer); SetIndexBuffer(1,ExtLowerBuffer); //---- drawing parameters setting SetIndexStyle(0,DRAW_ARROW); SetIndexArrow(0,217); SetIndexStyle(1,DRAW_ARROW); SetIndexArrow(1,218); //---- displaying in the DataWindow SetIndexLabel(0,"Fractal Up"); SetIndexLabel(1,"Fractal Down"); //---- initialization done

return(0); } bool SetIndexBuffer(int index, double array[]) Binds the array variable declared at a global level to the custom indicator pre -defined buffer. The amount of buffers needed to calculate the indicator is set with the IndicatorBuffers() function and cannot exceed 8. If it succeeds, TRUE will be returned, otherwise, it will be FALSE. To get the extended information about the error, one has to call the GetLastError() function. Parameters: index - Line index. Must lie between 0 and 7. array[] - Array that stores calculated indicator values. Sample: double ExtBufferSilver[]; int init() { SetIndexBuffer(0, ExtBufferSilver); // first line buffer // ... } void SetIndexDrawBegin( int index, int begin) Sets the bar number (from the data beginning) from which the drawing of the given indicator line must start. The indicators a re drawn from left to right. The indicator array values that are to the left of the given bar will not be shown in the chart or in the DataWindow. 0 will be set as default, and all data will be drawn. Parameters: index - Line index. Must lie between 0 and 7. begin - First drawing bar position number. Sample: 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. Empty values are not drawn or shown in the DataWindow. By default, empty value is EMPTY_VALUE. Parameters: index - Line index. Must lie between 0 and 7. value - New "empty" value. Sample: int init() { //---- 2 allocated indicator buffers SetIndexBuffer(0,ExtUppperBuffer); SetIndexBuffer(1,ExtLowerBuffer); //---- drawing parameters setting SetIndexStyle(0,DRAW_ARROW); SetIndexArrow(0,217); SetIndexStyle(1,DRAW_ARROW); SetIndexArrow(1,218); //---- 0 value will not be displayed SetIndexEmptyValue(0,0.0); SetIndexEmptyValue(1,0.0); //---- displaying in DataWindow SetIndexLabel(0,"Fractal Up"); SetIndexLabel(1,"Fractal Down"); //---- initialization done return(0); } void SetIndexLabel(int index, string text) Sets drawing line description for showing in the DataWindow and in the tooltip. Parameters:

index - Line index. Must lie between 0 and 7. text - Label text. NULL means that index value is not shown 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 the drawing line. For positive values, the line drawing will be shifted to the right, otherwise it will be sh ifted to the left. I.e., the value calculated on the current bar will be drawn shifted relatively to the current bar. Parameters: index - Line index. Must lie between 0 and 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 the new type, style, width and color for a given indicator line. Parameters: index - Line index. Must lie between 0 and 7. type style - Shape style. Can be one of Drawing shape styles listed. - Drawing style. It is used for one -pixel thick lines. It can be one of the Drawing shape styles listed. EMPTY value means that the style will not be changed.

width - Line width. Valid values are: 1,2,3,4,5. EMPTY value means that width will not be changed. clr - Line color. Absence of this parameter means that the color will not be changed. Sample: SetIndexStyle(3, DRAW_LINE, EMPTY, 2, Red); void SetLevelStyle( int draw_style, int line_width, color clr=CLR_NONE) The function sets a new style, width and color of horizontal levels of indicator to be output in a separate window. Parameters: draw_style - Drawing style. Can be one of the Drawing shape styles listed. EMPTY value means that the style will not be changed. line_width - Line width. Valid values are 1,2,3,4,5. EMPTY value indicates that the width will not be changed. clr - Line color. Empty value CLR_NONE means that the color will not be changed. Sample: //---- show levels as thick red lines SetLevelStyle(STYLE_SOLID,2,Red) void SetLevelValue(int level, double value) The function sets a value for a given horizontal level of the indicator to be output in a separate window. Parameters: level - Level index (0-31). value - Value for the given indicator level. Sample: SetLevelValue(1,3.14); A group of functions providing the working with data of the datetime type (integer representing the amount of seconds elapsed from midnight, 1 Jan uary, 1970). int Day() Returns the current day of the month, i.e., the day of month of the last known server time. Note: At the testing, the last known server time is modelled. 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) of the last known server time. Note: At the testing, the last known ser ver time is modelled. Sample: // does not work on holidays. if(DayOfWeek()==0 || DayOfWeek()==6) return(0); int DayOfYear() Returns the current day of the year (1 means 1 January,..,365(6) does 31 December), i.e., the day of year of the last known server time. Note: At the testing, the last known server time is modelled. Sample: if(DayOfYear()==245) return(true); int Hour() Returns the hour (0,1,2,..23) of the last known server time by the moment of the program start (this value will not change within the time of the program execution). Note: At the testing, the last known server time is modelled. Sample: bool is_siesta=false;

if(Hour()>=12 || Hour()<17) is_siesta=true; int Minute() Returns the current minute (0,1,2,..59) of the last known server time by the moment of the program start (this value will not change within the time of the program execution). Sample: if(Minute()<=15) return("first quarter"); int Month() Returns the current month as number (1 -January,2,3,4,5,6,7,8,9,10,11,12), i.e., the number of month of the last known server time. Note: At the testing, the last known server time is modelled. Sample: if(Month()<=5) return("the first half year"); int Seconds() Returns the amount of seconds elapsed from the beginning of the current minute of the last known server time by the moment of the program start (this value will not change within the time of the program execution). Sample: if(Seconds()<=15) return(0); datetime TimeCurrent() Returns the last known server time (time of incoming of the latest quote) as number of seconds elapsed from 00:00 January 1, 1970. Note: At the testing, the last known server time is modelled. Sample: if(TimeCurrent()-OrderOpenTime()<360) return(0); int TimeDay(datetime date) Returns day of month (1 - 31) for the specified date. Parameters: date - Datetime as 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 the zero-based day of week (0 means Sunday,1,2,3,4,5,6) for the specified date. Parameters: date - Datetime as 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 means 1 January,..,365(6) does 31 December) of year for the specified date. Parameters: date - Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample: int day=TimeDayOfYear(TimeCurrent()); int TimeHour(datetime time) Returns the hour for the specified time. Parameters: time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample: int h=TimeHour(TimeCurrent()); datetime TimeLocal() Returns local computer time as number of seconds elapsed from 00:00 January 1, 1970. Note: At the testing, local time is modelled and is the same as the modelled last known server time. Sample: if(TimeLocal()-OrderOpenTime()<360) return(0); int TimeMinute(datetime time) Returns the minute for the specified time. Parameters: time - Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample: int m=TimeMinute(TimeCurrent());

int TimeMonth(datetime time) Returns the month number for the specified time. Parameters: time - Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample: int m=TimeMonth(TimeCurrent()); int TimeSeconds(datetime time) Returns the amount of seconds elapsed from the beginning of the minute for the specified time. Parameters: time - Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample: int m=TimeSeconds(TimeCurrent()); int TimeYear(datetime time) Returns year for the specified date. The returned value can be within the range of 1970 to 2037. Parameters: time - Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. Sample: int y=TimeYear(TimeCurrent()); int Year() Returns the current year, i.e., the year of the last known server time. Note: At the testing, the last known server time is modelled. Sample: // return if the date is within the range from 1 Jan. to 30 Apr., 2006. if(Year()==2006 && Month()<5) return(0); A group of functions for working with files. There are three directories (with subdirectories) where working files can be placed: y /HISTORY/<current broker> - especially for the FileOpenHistory function; y /EXPERTS/FILES - common case; y /TESTER/FILES - especially for testing. Working with files from other directories is prohibited. void FileClose( int handle) Closes file previously opened by the FileOpen() function. Parameters: handle - File handle returned by the FileOpen() function Sample: int handle=FileOpen("filename", FILE_CSV|FILE_READ); if(handle>0) { // working with file ... FileClose(handle); } void FileDelete( string filename) Removes specified file name. To get the detailed error information, call GetLastError(). Files can only be deleted if they are in the terminal_dir\experts\files directory (terminal_directory\tester\files, in case of testing) or its subdirectories. Parameters: filename - Path to the file. Sample: // file my_table.csv will be deleted from terminal_dir \experts\files directory int lastError; FileDelete("my_table.csv"); lastError=GetLastError(); if(laseError!=ERR_NOERROR) { Print("An error ocurred while (",lastError,") deleting file my_table.csv"); return(0); } void FileFlush(int handle) Flushes all data stored in the file buffer to the disk. Notes: The FileFlush() function must be called between operations of file reading and writing in the file. At file closing, the data are flushed to the disk automatically, so there is no need to call the FileFlush() function before calling of the FileClose() function. 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 informatio n, call GetLastError() function. If the file end is reached during reading, the GetLastError() function will return error ERR_END_OF_FILE (4099). 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 err or 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 or -1 (if the function fails). To get the detailed error information, call GetLastError() function. Notes: Files can only be opened in the terminal_directory\experts\files folder (terminal_directory\tester\files if for expert testing) or in its subfolders. FILE_BIN and FILE_CSV modes cannot be used simultaneously. If FILE_WRITE does not combine with FILE_READ, a zero-length file will be opened. If even the file containd some data, they will be deleted. If there is a need to add data to an existing file, it must be opened using combination of FILE_READ | FILE_WRITE. If FILE_READ does not combine with FILE_WRITE, the file will be opened only if it already exists. If the file does not exist, it can be created using the FILE_WRITE mode. No more than 32 files can be opened within an executable module simultaneously. Handles of files opened in the same module ca nnot be passed to other modules (libraries). Parameters: filename - Filename. mode - Opening mode. It can be one or combination of values: FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE. delimiter - Delimiter character for csv files. By default, the ';' symbol applies. 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 ( terminal_directory\history\server_name) or in its subfolders. Returns the file handle for the opened file. If the function fails, the returned value is -1. To get the detailed error informati on, call the GetLastError() function. Notes: Client terminal can connect to servers of different brokerage companies. History data (HST files) for each brokerage c ompany are stored in the corresponding subfolder of the terminal_directory\history folder. The function can be useful to form own history data for a non -standard symbol and/or period. The file formed in the history folder can be opened offline, not data pumping is needed to chart it. Parameters: filename - Filename. mode - Opening mode. Can be one or combination of values: FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE. delimiter - Delimiter for csv files. By default, the ';' symbol will be passed. 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, void array[], int start, int count) Reads the specified amount of elements from the binary file into array. Before reading, make sure that the array is large eno ugh. Returns the amount of actually read elements. To get the detailed error information, call the GetLastError() function. Parameters: handle - File handle returned by the FileOpen() function. array[] - Array where data will be stored. start - Starting position for storing in array. count - Count of elements to be 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); } double FileReadDouble(int handle, int size=DOUBLE_VALUE) Reads the double-precision number with floating point from the current binary file position. The number format size can be 8 bytes (double) or 4 bytes (float). To get the error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the FileOpen() function. size - Number format size. Can be DOUBLE_VALUE(8 bytes) or FLOAT_VALUE(4 bytes). Sample: int handle; double value; handle=FileOpen("mydata.dat",FILE_BIN); if(handle>0) { value=FileReadDouble(handle,DOUBLE_VALUE); FileClose(handle); } int FileReadInteger(int handle, int size=LONG_VALUE) The function reads the integer from the current binary file position. The integer format size can be 1, 2 or 4 bytes. If the format size is not specified, the system tries to read the 4 -bytes value. To get the detailed error information, one has to call th e GetLastError() function. Parameters: handle - File handle returned by the 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 before the delimiter. Only for CSV files. To get the detailed error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the 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) The function reads the string from the current file position. Applies to both CSV and binary files. For text files, the strin g will be read before the delimiter. For binary file, the given count of characters will be read to the string. To get the detailed error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the FileOpen() function. length - Amount of characters for reading. 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) The function moves the file pointer to a new position that is an offset, in bytes, from the beginning, the end or the current file position. The next reading or writing are made at a new position. If file pointer has been moved successfully, the function returns TRUE, otherwise, it returns F ALSE. To get the detailed error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the FileOpen() functions. offset origin - Offset, in bytes, from origin. - Initial position. Value can be one of the following 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|FILE_WRITE, ';'); if(handle>0) { FileSeek(handle, 0, SEEK_END); //---- add data to the end of file FileWrite(handle, data1, data2); FileClose(handle); handle=0; } int FileSize(int handle) The function returns file size in bytes. To get the detailed error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the 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 FileTell(int handle) Returns the current position of the file pointer. To get the detailed error information, one has to call GetLastError() function. Parameters: handle - File handle returned by the FileOpen() function. Sample: int handle; int pos; handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ); // reading some data pos=FileTell(handle); Print("current position is ", pos); int FileWrite(int handle, ...) The function is intended for writing of data into a CSV file, delimiter being inserted automatically. After writing into the file, the line end character "\r\n" will be added. Numbers will be converted into a text at output (see the Print() function).

Returns the count of written characters or a negative number if an error occurs. To get the detailed error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the FileOpen() function. ... - User data to write, separated by commas. It can be up to 63 parameters. Data of int and double types are automatically converted into a string, but those of color, datetime and bool typesare not automatically converted and will be written to file as they are (as integers). Arrays cannot be passed as a parameter, they can be output elementwise.

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) The function writes the array to a binary file. Arrays of int, bool, datetime and color types will be written elementwise, as 4-bytes integers. Arrays of double type will be written elementwise, as 8 -bytes floating point numbers. Arrays of string type will be written by strings, the line end character " \r\n" to be added at each string automatically. Returns the number of written elements or a negative value if an error occurs. To get the detailed error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the FileOpen() function. array[] - Array to write. start - Starting index in the array (the first written element number). count - Count of elements to be written. 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) The function writes a double value with floating point to a binary file. If the format is specified as FLOAT_VALUE, the value will be written as a 4 -bytes floating point number (of the float type), otherwise, it will be written in the 8 -bytes floating point format (of the double type). Returns the actually written bytes count or a negative value if an error occurs. To get the detailed error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the FileOpen() function. value size - Double precision value. - 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) The function writes the integer value to a binary file. If the size is SHORT_VALUE, the value will be written as a 2 -byte integer (the short type), if the size is CHAR_VALUE, the value will be written as a 1 -byte integer (the char type), and if the size is LONG_VALUE, the value will be written as a 4 byte integer (the long int type).

Returns the actually written bytes count or a negative value if an error occurs. To get the detailed error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the FileOpen() function. value size - Value to be written. - 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) The function writes the string to a binary file from the current file position. Returns the actually written bytes count or a negative value if an error occurs. To get the detailed error information, one has to call the GetLastError() function. Parameters: handle - File handle returned by the FileOpen() function. value length - String to be written. - The length of the string to be written. If the string length exceeds the given value, it will be truncated. If it is shorter, it will be extended by binary 0s up to the given length.

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(handle, str, 8); FileClose(handle); A group of functions intended for working with global variables. Global variables of the client terminal should not be mixed up with variables declared in the global scope of the MQL4 program. Global variables are kept in the client terminal within 4 weeks since the last access, then they will be deleted automaticall y. An access to a global variable is not only setting of a new value, but reading of the global variable value, as well. Global variables of the client terminal are accessible simultaneously from all MQL4 progra ms launched in the client terminal. bool GlobalVariableCheck( string name) Returns TRUE if the global variable exists, otherwise, returns FALSE. To get the detailed error information, one has to call the GetLastError() function. Parameters: name - Global variable name. Sample: // check variable before use if(!GlobalVariableCheck("g1")) GlobalVariableSet("g1",1); bool GlobalVariableDel( string name) Deletes the global variable. If the function succeeds, the returned value will be TRUE, otherwise, it will be FALSE. To get t he detailed error information, one has to call the GetLastError() function. Parameters: name - Global variable name. Sample: // deleting of the global variable named "gvar_1" GlobalVariableDel("gvar_1"); double GlobalVariableGet( string name) Returns the value of an existing global variable or 0 if an error occurs. To get the detailed error information, one has to c all the GetLastError() function. Parameters: name - Global variable name.

Sample: double v1=GlobalVariableGet("g1"); //---- check function call result if(GetLastError()!=0) return(false); //---- continue processing string GlobalVariableName( int index) The function returns the name of a global variable by its index in the list of global variables. To get the detailed error in formation, one has to call the GetLastError(). Parameters: index - Index in the list of global variables. It must exceed or be equal to 0 and be less than GlobalVariablesTotal(). Sample: int var_total=GlobalVariablesTotal(); string name; for(int i=0;i<var_total;i++) { name=GlobalVariableName(i); Print(i,": Global variable name - ",name); } datetime GlobalVariableSet( string name, double value) Sets a new value of the global variable. If it does not exist, the system creates a new gloabl variable. If the function succ eeds, the returned value will be the last access time. Otherwise, the returned value will be 0. To get the detailed error informati on, one has to call the GetLastError() function. Parameters: name - Global variable name. value - The new numeric value. 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 existing global variable if the current value equals to the third parameter check_value. If there is no global variable, the function will generate error ERR_GLOBAL_VARIABLE_NOT_FOUND (4058) and return FALSE. When successfully executed, the function returns TRUE, otherwise, it returns FALSE. To get the detailed error information, one has to call the GetLastError() function. If the current value of the global variable differs from the check_value, the function will return FALSE. The function provides atomic access to the global variable, this is why it can be used for providing of a semaphore at intera ction of several experts working simultaneously within one client terminal. Parameters: name - Global variable name. value - New value. check_value - Value to be compared to 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 the variable be deleted? if(GetLastError()==ERR_GLOBAL_VARIABLE_NOT_FOUND) return(0); //---- sleeping Sleep(500); } //---- resource locked // ... do some work //---- unlock resource GlobalVariableSet("DATAFILE_SEM",0); } int GlobalVariablesDeleteAll( string prefix_name=NULL) Deletes global variables. If the name prefix is not specified, all global variables will be deleted. Otherwise, only those va riables will be deleted, the names of which begin with the specified prefix. The function returns the count of deleted variables. Parameters:

prefix_name - Name prefix of the global variables to be deleted. Sample: Print(GlobalVariablesDeleteAll("test_")," test globals deleted"); int GlobalVariablesTotal( ) The function returns the total count of global variables. Sample: Print(GlobalVariablesTotal()," global variables detected"); A set of mathematical and trigonometric functions. 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 within the range 0 to (indeterminate value). Parameters: x - Value between -1 and 1 the arccosine of which to 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 (in radians). If x is less than -1 or exceeds 1, the MathArccos returns NaN

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 exceeds 1, the arcsine returns NaN (indeterminate value). Parameters: x - Value the arcsine of which to 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 within the range of - /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 exceeds or equals 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 the value of e raised to the power of d. At overflow, the function returns INF (infinity), and it returns 0 at underflow. Parameters: d - A number specifying the 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 function returns the natural logarithm of x if successful. If x is negative, these functions return NaN (indeterminate value). If x is 0, they return INF (infinity). Parameters: x - Value logarithm of which 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 the maximum value of two numeric values. Parameters: value1 - The first numeric value. value2 - The second numeric value. Sample: double result=MathMax(1.08,Bid); double MathMin(double value1, double value2) Returns the minimum value of two numeric values. Parameters: value1 - The first numeric value. value2 - The second numeric value. Sample: double result=MathMin(1.08,Ask); double MathMod(double value, double value2) The function returns the floating-point remainder of division of two numbers. The MathMod function calculates the floating-point remainder f of x / y such that x = i * y + f , where i is an integer, f has the same sign as x, and the absolute value of f is less than the absolute value of y. Parameters: value - Dividend value.

value2 - Divisor 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 the base expression raised to the specified power (exponent value). 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 within the range of 0 to 32767. The MathSrand function must be used to seed the pseudorandom number generator before calling MathRand. Sample: MathSrand(TimeLocal()); // 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 be rounded. 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 genera tor, 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 w ith seed passed as 1. Parameters: seed - Seed for random-number generation.

Sample: MathSrand(TimeLocal()); // 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 A group of functions intended for working with graphical objects related to the current chart. bool string name, int type, int window, datetime time1, double price1, datetime time2=0, double price2=0, datetime time3=0, ObjectCreate( double price3=0) Creation of an object with the specified name, type and initial coordinates in the specified window. Count of coordinat es related to the object can be from 1 to 3 depending on the object type. If the function succeeds, the returned value will be TRUE. Otherwise, it will be FALSE. To get the detailed error information, one has to call the GetLastError() function. Objects of the OBJ_LABEL type ignore the coordinates. Use the function of ObjectSet() to set up the OBJPROP_XDISTANCE and OBJPROP_YDISTANCE properties. Notes: The chart sub-windows (if there are sub -windows with indicators in the chart) are numbered starting from 1. The chart main window always exists and has the 0 index. Coordinates must be passed in pairs: time and price. For example, the OBJ_VLINE object needs only time, but price (any value) must be passed, as well. Parameters: name - Object unique name. type window time1 price1 time2 price2 time3 - Object type. It can be any of the Object type enumeration values. - Index of the window where the object will be added. Window index must exceed or equal to 0 and be less than WindowsTotal(). - Time part of the first point. - Price part of the first point. - Time part of the second point. - Price part of the second point. - Time part of the third point.

price3 - Price part of the 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 having the specified name. If the function succeeds, the returned value will be TRUE. Otherwise, it will be FALSE. To get the detailed error information, one has to call the GetLastError() function. Parameters: name - Name of the object to be deleted. Sample: ObjectDelete("text_object"); string ObjectDescription( string name) Return object description. For objects of OBJ_TEXT and OBJ_LABEL types, the text drawn by these objects will be returned. To get the detailed error information, one has to call the GetLastError() function. See also ObjectSetText() function. Parameters: name - Object name. Sample: // writing the chart objects 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) Search for an object having the specified name. The function returns index of the windows that contains the object to be foun d. If it fails, the returned value will be -1. To get the detailed error information, one has to call the GetLastError() function. The chart sub-windows (if there are sub -windows with indicators in the chart) are numbered starting from 1. The chart main window always exists and has the 0 index. Parameters: name - Object name to search for. Sample: if(ObjectFind("line_object2")!=win_idx) return(0); double ObjectGet( string name, int index) The function returns the value of the specified object property. To check errors, one has to call the GetLastError() function. See also ObjectSet() 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) The function returns the level description of a Fibonacci object. The amount of Fibonacci levels depends on the object type. The maximum amount of Fibonacci levels is 32. To get the detailed error information, one has to call the GetLastError() function. See also ObjectSetFiboDescription() function. Parameters: name - Fibonacci object name. index - Index of the Fibonacci level (0-31). Sample: #include <stdlib.mqh> ... string text; for(int i=0;i<32;i++) { text=ObjectGetFiboDescription(MyObjectName,i); //---- checking whether the objects has less than 32 levels if(GetLastError()!=ERR_NO_ERROR) break; Print(MyObjectName,"level: ",i," description: ",text); } int ObjectGetShiftByValue( string name, double value) The function calculates and returns bar index (shift related to the current bar) for the given price. The bar index is calcul ated by the first and second coordinates using a linear equation. Applied to trendlines and similar objects. To get the detailed er ror information, one has to call the GetLastError() function. See also ObjectGetValueByShift() function. Parameters: name - Object name. value - Price value. Sample: int shift=ObjectGetShiftByValue("MyTrendLine#123", 1.34); double ObjectGetValueByShift( string name, int shift) The function calculates and returns the price value for the specified bar (shift related to the current bar). The price value is calculated by the first and second coordinates using a linear equation. Applied to trendlines and similar objects. To get the d etailed error information, one has to call the GetLastError() function. See also ObjectGetShiftByValue() function. Parameters: name - Object name shift - Bar index. Sample:

double price=ObjectGetValueByShift("MyTrendLine#123", 11); bool ObjectMove( string name, int point, datetime time1, double price1) The function moves an object coordinate in the chart. Objects can have from one to three coordinates depending on their types. If the function succeeds, the returned value will be TRUE. Otherwise, it wil l be FALSE. To get the detailed error information, one has to call the GetLastError() function. The object coordinates are numbered starting from 0. Parameters: name - Object name. point time1 - Coordinate index (0-2). - New time value.

price1 - New price value. Sample: ObjectMove("MyTrend", 1, D'2005.02.25 12:30', 1.2345); string ObjectName( int index) The function returns the object name by its index in the objects list. To get the detailed error information, one has to call the GetLastError() function. Parameters: index - Object index in the objects list. Object index must exceed or equal to 0 and be 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=EMPTY, int type=EMPTY) Removes all objects of the specified type and in the specified sub -window of the chart. The function returns the count of removed objects. To get the detailed error information, one has to call the GetLastError() function. Notes: The chart sub-windows (if there are sub -windows with indicators in the chart) are numbered starting from 1. The chart main window always exists and has the 0 index. If the window index is missing or it has the value of -1, the objects will be removed from the entire chart. If the type value equals to -1 or this parameter is missing, all objects will be removed from the specified sub -window. Parameters: window - Optional parameter. Index of the window in which the objects will be deleted. Must exceed or equal to -1 (EMPTY, the default value) and be less than WindowsTotal(). type - Optional parameter. An object type to be deleted. 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); // all horizontal lines are removed from the 2nd sub -window. ObjectsDeleteAll(2); // all objects are removed from the 2nd sub -window. ObjectsDeleteAll(); // all objects are removed from the chart . bool ObjectSet(string name, int index, double value) Changes the value of the specified object property. If the function succeeds, the returned value will be TRUE. Otherwise, it will be FALSE. To get the detailed error information, one has to call the GetLastError() function. See also ObjectGet() function. Parameters: name - Object name. index - Object value index. It can be any of Object properties enumeration values. value - New value of the given property. Sample: // moving the first coord to the last bar time ObjectSet("MyTrend", OBJPROP_TIME1, Time[0]); // setting the 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) The function assigns a new description to a level of a Fibonacci object. The amount of Fibonacci levels depends on the object type. The maximum amount of Fibonacci levels is 32. To get the detailed error information, one has to call the GetLastError() function. Parameters: name - Object name. index - Index of the Fibonacci level (0-31). text - New description of the level. Sample: ObjectSetFiboDescription("MyFiboObject",2,"Second line");

bool ObjectSetText(string name, string text, int font_size, string font=NULL, color text_color=CLR_NONE) Changes the object description. For objects of OBJ_TEXT and OBJ_LABEL, this description is shown as a text line in the chart. If the function succeeds, the returned value will be TRUE. Otherwise, it is FALSE. To get the detailed error information, one has to call the GetLastError() function. Parameters of font_size, font_name and text_color are used for objects of OBJ_TEXT and OBJ_LABEL only. For objects of other types, these parameters are ignored. See also ObjectDescription() function. Parameters: name - Object name. text font_size font - A text describing the object. - Font size in points. - Font name.

text_color - Text color. Sample: ObjectSetText("text_object", "Hello world!", 10, "Times New Roman", Green); int ObjectsTotal(int type=EMPTY) Returns total amount of objects of the specified type in the chart. Parameters: type - Optional parameter. An object type to be counted. It can be any of the Object type enumeration values or EMPTY constant to count all objects with any types. Sample: int obj_total=ObjectsTotal(); string name; for(int i=0;i<obj_total;i++) { name=ObjectName(i); Print(i,"Object name for object #",i," is " + name); } int ObjectType(string name) The function returns the object type value. To get the detailed error information, one has to call the GetLastError() function. Parameters: name - Object name. Sample: if(ObjectType("line_object2")!=OBJ_HLINE) return(0); A group of functions intended for working with data of the string type. string StringConcatenate(...) Forms a string of the data passed and returns it. Parameters can be of any type. Amount of passed parameters cannot exceed 64. Parameters are transformed into strings according the same rules as those used in functions of Print(), Alert() and Comment(). The returned string is obtained as a result of concatenate of strings converted from the function parameters. The StringConcatenate() works faster and more memory -saving than when strings are concatenated usi ng addition operations (+). Parameters: ... - Any values separated by commas. It can be up to 64 parameters. Sample: string text; text=StringConcatenate("Account free margin is ", AccountFreeMargin(), "Current time is ", TimeToStr(TimeCurrent())); // slow text="Account free margin is " + AccountFreeMargin() + "Current time is " + TimeToStr(TimeCurrent()) Print(text); int StringFind(string text, string matched_text, int start=0) Search for a substring. Returns the position in the string from which the searched substring begins, or -1 if the substring has not been found. Parameters: text - String to search in. matched_text - Substring to search for. start - Position in the string to start search from. Sample: string text="The quick brown dog jumps over the lazy fox"; int index=StringFind(text, "dog jumps over", 0); if(index!=16) Print("oops!"); int StringGetChar(string text, int pos) Returns character (code) from the specified position in the string. Parameters: text - String pos - Char position in the string. Can be from 0 to StringLen(text)-1. Sample: int char_code=StringGetChar("abcdefgh", 3);

// char code 'c' is 99 int StringLen(string text) Returns character count in a string. Parameters: text - String where the length must be calculated. Sample: string str="some text"; if(StringLen(str)<5) return(0); string StringSetChar(string text, int pos, int value) Returns the string copy with changed character in the specified position. Parameters: text - String where character will be changed. pos - The character position in the string. Can be from 0 to StringLen(text). 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 length=0) Extracts a substring from text string starting from the given position. The function returns a copy of the extracted substring if possible, otherwise, it returns an empty string. Parameters: text - String from which the substring will be extracted. start - Substring starting index. Can be from 0 to StringLen(text)-1. length - Length of the substring extracted. If the parameter value exceeds or equals to 0 or the parameter is not specified, the substring will be extracted starting from the given position and up to the end of the string. Sample: string text="The quick brown dog jumps over the lazy fox"; string substr=StringSubstr(text, 4, 5); // subtracted string is the "quick" word string StringTrimLeft(string text) The function cuts line feed characters, spaces and tabs in the left part of the string. The function returns a copy of the tr immed string, if possible. Otherwise, it returns an empty string. Parameters: text - String to be trimmed at the left. Sample: string str1=" Hello world "; string str2=StringTrimLeft(str); // after trimming the str2 variable will be "Hello World " string StringTrimRight(string text) The function cuts line feed characters, spaces and tabs in the right part of the string. The function returns a copy of the t rimmed string, if possible. Otherwise, it returns an empty string. Parameters: text - String to be trimmed at the right. Sample: string str1=" Hello world "; string str2=StringTrimRight(str); // after trimming the str2 variable will be " Hello World" A group of functions intended for calculation of standard and custom indicators. For an expert (or any other MQL4 program) to take up the value of any indicator, it is not necessary that this indicator is present in the chart. The requested indicator will be loaded and calculated in the thread of the module that has called it. Any indicator can be calculated on the data of not only current chart, but also on the data of any available symbol/period. If data (symbol name and/or timeframe differ from the current ones) are requested from another chart, the situation is possible that the corresponding ch art was not opened in the client terminal and the necessary data must be requested from the server. In this case, error ERR_HISTORY_WILL_UPDATED (4066 - the requested history data are under updating) will be placed in the last_error variable, and one will has to re -request (see example of ArrayCopySeries()). double iAC(string symbol, int timeframe, int shift) Calculates the Bill Williams' Accelerator/Decelerator oscillator. Parameters: symbol - Symbol name of the security on the data of which the indicator will be calculated. NULL means the current symbol. timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: double result=iAD(NULL, 0, 1); double 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, iAlligator( 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 jaw_period jaw_shift teeth_period teeth_shift lips_period lips_shift ma_method applied_price mode - Timeframe. It can be one of Timeframe enumeration values. 0 means the current chart timeframe. - Blue line averaging period (Alligator's Jaw). - Blue line shift relative to the chart. - Red line averaging period (Alligator's Teeth). - Red line shift relative to the chart. - Green line averaging period (Alligator's Lips). - Green line shift relative to the chart. - MA method. It can be any of Moving Average methods. - Applied price. It can be any of Applied price enumeration values. - Data source, identifier of a line of the indicator. 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 period applied_price mode - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period for calculation. - Applied price. It can be any of Applied price enumeration values. - Indicator line index. It can be any of the Indicators line identifiers enumeration value.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 period - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period for calculation.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 period applied_price - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period for calculation. - Applied price. It can be any of Applied price enumeration values.

shift - Index of the value taken from the indicator buffer (shift relative to the curren t bar the given amount of periods ago). 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 the indicator. NULL means the current symbol. timeframe period deviation bands_shift applied_price mode - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period to calculate the main line. - Deviation from the main line. - The indicator shift relative to the chart. - Applied price. It can be any of Applied price enumeration values. - Indicator line index. It can be any of the Indicators line identifiers enumeration value.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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, int deviation, int bands_shift, int mode, int shift) Calculation of the Bollinger Bands indicator on data stored in a numeric array. Unlike iBands(...), the iBandsOnArray functio n does not take data by symbol name, timeframe, the applied price. The price data must be previously prepared. The indicator is cal culated from left to right. To access to the array elements as to a series array (i.e., from right to left), one has to use the ArraySetAsSeries function. Parameters: array[] - Array with data. total period deviation bands_shift mode - The number of items to be counted. 0 means the whole array. - Averaging period for calculation of main line. - Deviation from main line. - The indicator shift relative to the chart. - Indicator line index. It can be any of the Indicators line identifiers enumeration value.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 period applied_price - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period for calculation. - Applied price. It can be any of Applied price enumeration values.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 period applied_price - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period for calculation. - Applied price. It can be any of Applied price enumeration values.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: if(iCCI(NULL,0,12,PRICE_TYPICAL,0)>iCCI(NULL,0,20,PRICE_TYPICAL,0)) return(0); double iCCIOnArray( double array[], int total, int period, int shift)

Calculation of the Commodity Channel Index on data stored in a numeric array. Unlike iCCI(...), the iCCIOnArray function does not take data by symbol name, timeframe, the applied price. The price data must be previously prepared. The indicator is calculated from left to righ t. To access to the array elements as to a series array (i.e., from right to left), one has to use the ArraySetAsSeries function. Parameters: array[] - Array with data. total period - The number of items to be counted. - Averaging period for calculation.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: if(iCCIOnArray(ExtBuffer,total,12,0)>iCCI(NULL,0,20,PRICE_TYPICAL, 0)) return(0); double iCustom(string symbol, int timeframe, string name, ..., int mode, int shift) Calculates the specified custom indicator and returns its value. The custom indicator must be compiled (*.EX4 file) and be in the terminal_directory\experts\indicators directory. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means current symbol. timeframe name ... mode - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Custom indicator compiled program name. - Parameters set (if necessary). The passed parameters and their order must correspond with the desclaration order and the type of extern variables of the custom indicator. - Line index. Can be from 0 to 7 and must correspond with the index used by one of SetIndexBuffer functions.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 period - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period for calculation.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 ma_period ma_method ma_shift applied_price deviation mode - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period for calculation of the main line. - MA method. It can be any of Moving Average method enumeration value. - MA shift. Indicator line offset relate to the chart by timeframe. - Applied price. It can be any of Applied price enumeration values. - Percent deviation from the main line. - Indicator line index. It can be any of Indicators line identifiers enumeration value.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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) Calculation of the Envelopes indicator on data stored in a numeric array. Unlike iEnvelopes(...), the iEnvelopesOnArray funct ion does not take data by symbol name, timeframe, the applied price. The price data must be previously prepared. The indicator is c alculated from left to right. To access to the array elements as to a series array (i.e., from right to left), one has to use the ArraySetAsSeries function. Parameters: array[] - Array with data. total ma_period ma_shift deviation mode - The number of items to be counted. - Averaging period for calculation of the main line. - MA shift. Indicator line offset relate to the chart by timeframe. - Percent deviation from the main line. - Indicator line index. It can be any of Indicators line identifiers enumeration value.

ma_method - MA method. It can be any of Moving Average method enumeration value.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 period ma_method applied_price - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period for calculation. - MA method. It can be any of Moving Average method enumeration value. - Applied price. It can be any of Applied price enumeration values.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 mode - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Indicator line index. It can be any of the Indicators line identifiers enumeration value.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: double val=iFractals(NULL, 0, MODE_UPPER, 3); double 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) iGator( Gator oscillator calculation. The oscillator displays the difference between the Alligator red and blue lines (the upper histogram) and that between red and green lines (the lower histogram). Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe jaw_period jaw_shift teeth_period teeth_shift lips_period lips_shift ma_method applied_price mode - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Blue line averaging period (Alligator's Jaw). - Blue line shift relative to the chart. - Red line averaging period (Alligator's Teeth). - Red line shift relative to the chart. - Green line averaging period (Alligator's Lips). - Green line shift relative to the chart. - MA method. It can be any of Moving Average method enumeration value. - Applied price. It can be any of Applied price enumeration values. - Indicator line index. It can be any of Indicators line identifiers enumeration value.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 tenkan_sen kijun_sen mode - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Tenkan Sen averaging period. - Kijun Sen averaging period. - Source of data. It can be one of the Ichimoku Kinko Hyo mode enumeration .

senkou_span_b - Senkou SpanB averaging period. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 timeframe

- Symbol the data of which should be used to calculate indicator. NULL means the current symbol. - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 period applied_price - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Period (amount of bars) for calculation of price changes. - Applied price. It can be any of Applied price enumeration values.

shift - Index of the value taken from the indicator buffer (shift relati ve to the current bar the given amount of periods ago). 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) Calculation of the Momentum indicator on data stored in a numeric array. Unlike iMomentum(...), the iMomentumOnArray function does not take data by symbol name, timeframe, the applied price. The price data must be previously prepared. The indicator is calc ulated from left to right. To access to the array elements as to a series array (i.e., from right to left), one has to use the ArraySetAsSeries function. Parameters: array[] - Array with data. total period - The number of items to be counted. - Period (amount of bars) for calculation of price changes.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 period - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Period (amount of bars) for calculation of the indicator.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 period ma_shift ma_method applied_price - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Averaging period for calculation. - MA shift. Indicators line offset relate to the chart by timeframe. - MA method. It can be any of the Moving Average method enumeration value. - Applied price. It can be any of Applied price enumeration values.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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) Calculation of the Moving Average on data stored in a numeric array. Unlike iMA(...), the iMAOnArray function does not take d ata by symbol name, timeframe, the applied price. The price data must be previously prepared. The indicator is calculated from left to right. To access to the array elements as to a series array (i.e., from right to left), one has to use the ArraySetAsSeries function. Parameters: array[] - Array with data. total period ma_shift shift - The number of items to be counted. 0 means whole array. - Averaging period for calculation. - MA shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago).

ma_method - MA method. It can be any of the Moving Average method enumeration value.

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. Sometimes called MACD Histogram in some systems. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe fast_ema_period signal_period applied_price - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Number of periods for fast moving average calculation. - Number of periods for signal moving average calculation. - Applied price. It can be any of Applied price enumeration values.

slow_ema_period - Number of periods for slow moving average calculation.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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. In the systems where OsMA is called MACD Histogr am, this indicator is displayed as two lines. In the Client Terminal, the Moving Average Convergence/Divergence is drawn as a histo gram. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe fast_ema_period signal_period applied_price mode - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Number of periods for fast moving average calculation. - Number of periods for signal moving average calculation. - Applied price. It can be any of Applied price enumeration values. - Indicator line index. It can be any of the Indicators line identifiers enumeration value.

slow_ema_period - Number of periods for slow moving average calculation.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: if(iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0)>iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_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 applied_price - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Applied price. It can be any of Applied price enumeration values.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: double val=iOBV(NULL, 0, PRICE_CLOSE, 1); double iSAR(string symbol, int timeframe, double step, double maximum, int shift) Calculates the Parabolic Stop 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 step maximum - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Increment, usually 0.02. - Maximum value, usually 0.2.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: if(iSAR(NULL,0,0.02,0.2,0)>Close[0]) return(0); double iRSI(string symbol, int 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 period - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Number of periods for calculation.

applied_price

- Applied price. It can be any of Applied price enumeration values.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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) Calculation of the Relative Strength Index on data stored in a numeric array. Unlike iRSI(...), the iRSIOnArray function does not take data by symbol name, timeframe, the applied price. The price data must be previously prepared. The indicator is calculate d from left to right. To access to the array elements as to a series array (i.e., from right to left), one has to use the ArraySetAsSeries function. Parameters: array[] - Array with data. total period - The number of items to be counted. - Number of periods for calculation.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: if(iRSIOnArray(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 period mode - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Number of periods for calculation. - Indicator line index. It can be any of Indicators line identifiers enumeration value.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: double val=iRVI(NULL, 0, 10,MODE_MAIN,0); double iStdDev( string symbol, int timeframe, int ma_period, int ma_shift, int ma_method, 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 ma_period ma_shift ma_method applied_price - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - MA period. - MA shift. - MA method. It can be any of Moving Average method enumeration value. - Applied price. It can be any of Applied price enumeration values.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: double val=iStdDev(NULL,0,10,0,MODE_EMA,PRICE_CLOSE,0); double iStdDevOnArray( double array[], int total, int ma_period, int ma_shift, int ma_method, int shift) Calculation of the Standard Deviation indicator on data stored in a numeric array. Unlike iStdDev(...), the iStdDevOnArray fu nction does not take data by symbol name, timeframe, the applied price. The price data must be previously prepared. The indicator i s calculated from left to right. To access to the array elements as to a series array (i.e., from right to left), one has to use the ArraySetAsSeries function. Parameters: array[] - Array with data. total ma_period ma_shift - The number of items to be counted. - MA period. - MA shift.

ma_method - MA method. It can be any of Moving Average method enumeration value. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: double val=iStdDevOnArray(ExtBuffer,100,10,0,MODE_EMA,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 %Dperiod slowing - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - %D line period. - Slowing value. %Kperiod - %K line period.

method price_field mode

- MA method. It can be any ofMoving Average method enumeration value. - Price field parameter. Can be one of this values: 0 - Low/High or 1 - Close/Close. - Indicator line index. It can be any of the Indicators line identifiers enumeration value.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: if(iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,0)>iStochastic(NULL,0,5,3,3,MODE_SMA,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 period - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Number of periods for calculation.

shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: if(iWPR(NULL,0,14,0)>iWPR(NULL,0,14,1)) return(0); A group of functions intended for access to price data of any available symbol/period. If data (symbol name and/or timeframe differ from the current ones) are requested from another chart, the situation is possib le that the corresponding chart was not opened in the client terminal and the necessary data must be requested from the server. In this case, error ERR_HISTORY_WILL_UPDATED (4066 - the requested history data are under updating) will be placed in the last_error variable, and one will h as to re-request (see example of ArrayCopySeries()). At the testing, price data of the same symbol but of another timeframe are modelled exactly, with the exception of volumes. V olumes of another timeframe are not modelled. Price data of other symbols are not modelled, either. In all cases, the amount of bars in time series is modelled exactly. int iBars(string symbol, int timeframe) Returns the number of bars on the specified chart. For the current chart, the information about the amount of bars is in the predefined variable named Bars. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. 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 ope n time is missing, the function will return -1 or the nearest bar shift depending on the exact. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe time - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - 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. For the current chart, the information about close prices is in the predefined array named Close[]. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). Sample: Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",P ERIOD_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. For the current chart, the information about high prices is in the predefined array named High[]. Parameters: symbol - Symbol on that data need to calculate indicator. NULL means current symbol. timeframe shift - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago).

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 iHighest(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 type count - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Series array identifier. It can be any of the Series array identifier enumeration values. - 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 on the 20 consequtive bars in the range // from the 4th to the 23rd index inclusive on the current chart val=High[iHighest(NULL,0,MODE_HIGH,20,4)]; 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. For the current chart, the information about low prices is in the predefined array named Low[]. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 iLowest(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 type count - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. - Series array identifier. It can be any of Series array identifier enumeration values. - 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: // calculating the lowest value on the 10 consequtive bars in the range // from the 10th to the 19th index inclusive on the current chart double val=Low[iLowest(NULL,0,MODE_LOW,10,10)]; 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. For the current chart, the information about open prices is in the predefined array named Open[]. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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. For the current chart, the information about bars open times is in the predefined array named Time[]. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago). 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 Tick Volume value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function returns 0. For the current chart, the information about bars tick volumes is in t he predefined array named Volume[]. Parameters: symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol. timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. shift - Index of the value taken from the indicator buffer (shift relative to the current bar the gi ven amount of periods ago). 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)); A group of functions intended for trading management. Trading functions of OrderSend(), OrderClose, OrderCloseBy, OrderDelete, and OrderModify cannot be called from custom indicators. Trading functions can be used in experts and scripts. Trading functions can be called only if the "Allow live trading" proper ty of this particular expert is checked. To trade from experts and scripts, only one thread was provided that was launched in the program trade context (context of automated trading from experts and scripts). This is why, if this context is occupied with an expert trading operation, another expert or script can not call trading functions at that moment due to error 146 (ERR_TRADE_CONTEXT_BUSY). To check whether it is possible to trade or not, one has to use the IsTradeAllowed() function. To make a clear sharing of access to the trading context, one can use a semaphore on the basis of a global variable the value of which must be changed using the GlobalVariableSetOnCondition() function. Any trading operation (functions of OrderSend(), OrderClose, OrderCloseBy, OrderDelete or OrderModify) can fail, for a number of reasons, and return either negative ticket number or FALSE. One can find out about the reason for fail by calling of the GetLastError() function. Every error must be processed in a special way. The most common recommen dations are given below. Error codes returned from trade server. Constant Value Description ERR_NO_ERROR ERR_NO_RESULT 0 1 Trade operation succeeded. OrderModify attempts to replace the values already set with the same values. One or more values must be changed, then modification attempt can be repeated. Common error. All attempts to trade must be stopped until reasons are clarified. Restart of operation system and client terminal will possibly be needed. Invalid parameters were passed to the trading function, for example, wrong symbol, unknown trade operation, negative slippage, non-existing ticket number, etc. The program logic must be changed. Trade server is busy. The attempt can be repeated after a rather long period of time (over several minutes). Old version of the client terminal. The latest version of the client terminal must be installed. No connection to the trade server. It is necessary to make sure that connection has not been broken (for example, using the IsConnected function) and repeat the attempt after a certain period of time (over 5 seconds). Requests are too frequent. The frequency of requesting must be reduced, the program logic must be changed. The account was disabled. All attempts to trade must be stopped. The account number is invalid. All attempts to trade must be stopped. Timeout for the trade has been reached. Before retry (at least, in 1 minute time), it is necessary to make sure that trading operation has not really succeeded (a new position has not been opened, or the existing order has not been modified or deleted, or the existing position has not been closed) Invalid bid or ask price, perhaps, unnormalized price. After 5 second (or more) delay, it is necessary to refresh data using the RefreshRates function and make a retry. If the error does not disappear, all attempts to trade must be stopped, the program logic must be changed. Stops are too close, or prices a re ill-calculated or unnormalized (or in the open price of a pending order). The attempt can be repeated only if the error occurred due to the price obsolescense. After 5 second (or more) delay, it is necessary to refresh data using the

ERR_COMMON_ERROR

ERR_INVALID_TRADE_PARAMETERS

ERR_SERVER_BUSY ERR_OLD_VERSION

4 5

ERR_NO_CONNECTION

ERR_TOO_FREQUENT_REQUESTS ERR_ACCOUNT_DISABLED ERR_INVALID_ACCOUNT

8 64 65

ERR_TRADE_TIMEOUT

128

ERR_INVALID_PRICE

129

ERR_INVALID_STOPS

130

RefreshRates function and make a retry. If the error does not disappear, all attempts to trade must be stopped, the program logic must be changed. ERR_INVALID_TRADE_VOLUME ERR_MARKET_CLOSED ERR_TRADE_DISABLED 131 132 133 Invalid trade volume, error in the volume granularity. All attempts to trade must be stopped, and the program logic must be changed. Market is closed. The attempt can be repeated after a rather long period of time (over several minutes). Trade is disabled. All attempts to trade must be stopped. Not enough money to make an operation. The trade with the same parameters must not be repeated. After 5 -second (or more) delay, the attempt can be repeated with a smaller volume, but it is necessary to make sure that there is enough money to complete the operation. The price has changed. The data can be refreshed without any delay using the RefreshRates function and make a retry. No quotes. The broker has not supplied with prices or refused, for any reason (for example, no prices at the session start, unconfirmed prices, fast market). After 5 -second (or more) delay, it is necessary to refresh data using the RefreshRates function and make a retry. The requested price has become out of date or bid and ask prices have been mixed up. The data can be refreshed without any delay using the RefreshRates function and make a retry. If the error does not disappear, all attempts to trade must be stopped, the program logic must be changed. The order has been locked and under processing. All attempts to make trading operations must be stopped, and the program logic must be changed. Only buying operation is allowed. The SELL operation must not be repeated. Too many requests. The frequency of requesting must be reduced, the program logic must be changed. The order has been enqueued. It is not an error but an interaction code between the client terminal and the trade server. This code can be got rarely, when the disconnection and the reconnection happen during the execution of a trade operation. This code should be processed in the same way as error 128. The order was accepted by the dealer for execution. It is an interaction code between the client terminal and the trade server. It can appear for the same reason as code 142. This code should be processed in the same way as error 128. The order was discarded by the client during manual confirmation. It is an interaction code between the client terminal and the trade server. Modifying has been denied since the order is too close to market and locked for possible soon execution. The data can be refreshed after more than 15 seconds using the RefreshRates function, and a retry can be made. The trade thread is busy. Retry only after the IsTradeContextBusy function has returned FALSE. The use of pending order expiration date has been denied by the broker. The operation can only be repeated if the expiration parameter has been zeroized. The amount of open and pending orders has reached the limit set by the broker. New open positions and pending orders can be placed only after the existing positions or orders have been closed or deleted. An attempt to open a position opposite to the existing one when hedging is disabled. First the existing opposite position should be closed, all attempts of such trade operations must be stopped, or the program logic must be changed. An attempt to close a symbol position contravening the FIFO rule. First earlier existing position(s) should be closed, all attempts of such trade operations must be stopped, or the program logic must be changed.

ERR_NOT_ENOUGH_MONEY

134

ERR_PRICE_CHANGED

135

ERR_OFF_QUOTES

136

ERR_REQUOTE

138

ERR_ORDER_LOCKED ERR_LONG_POSITIONS_ONLY_ALLOWED ERR_TOO_MANY_REQUESTS

139 140 141

142

143

144

ERR_TRADE_MODIFY_DENIED

145

ERR_TRADE_CONTEXT_BUSY ERR_TRADE_EXPIRATION_DENIED

146 147

ERR_TRADE_TOO_MANY_ORDERS

148

ERR_TRADE_HEDGE_PROHIBITED

149

ERR_TRADE_PROHIBITED_BY_FIFO

150

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 price slippage - Number of lots. - Preferred closing price. - Value of the maximum price slippage in points.

Color - Color of the closing arrow on the chart. If the parameter is missing 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 an 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 missing 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: The order must be previously selected by the 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. Open and pending orders close time is equal to 0. Note: The order must be previously selected by the 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: The order must be previously selected by the 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: The order must be previously selected by the 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, color Color=CLR_NONE) Deletes previously opened pending order. If the function succeeds, the return value is true. If the function fails, the retur n value is false. To get the detailed error information, call GetLastError(). Parameters: ticket - Unique number of the order ticket. Color - Color of the arrow on the chart. If the parameter is missing or has CLR_NONE value arrow will not be drawn on the chart. Sample: if(Ask>var1) { OrderDelete(order_ticket); return(0); } datetime OrderExpiration( ) Returns expiration date for the selected pending order. Note: The order must be previously selected by the OrderSelect() function. Sample: if(OrderSelect(10, SELECT_BY_TICKET)==true) Print("Order expiration for the order #10 is ",OrderExpiration()); else Print("OrderSelect returned error of ",GetLastError()); double OrderLots() Returns amount of lots for the selected order. Note: The order must be previously selected by the OrderSelect() function. Sample: if(OrderSelect(10,SELECT_BY_POS)==true) Print("lots for the order 10 ",OrderLots( )); else Print("OrderSelect returned error of ",GetLastError()); int OrderMagicNumber() Returns an identifying (magic) number for the currently selected order. Note: The order must be previously selected by the OrderSelect() function. Sample: if(OrderSelect(10,SELECT_BY_POS)==true) Print("Magic number for the order 10 ", OrderMagicNumber()); else Print("OrderSelect returned error of ",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 pending orders. If the function succeeds, the returned value will be TRUE. If the function fails, the returned value will be FALSE. To get the detailed error information, call GetLastError() function. Notes: Open price and expiration time can be changed only for pending orders. If unchanged values are passed as the function parameters, the error 1 (ERR_NO_RESULT) will be generated. Pending order expiration time can be disabled in some trade servers. In this case, when a non -zero value is specified in the expiration parameter, the error 147 (ERR_TRADE_EXPIRATION_DENIED) will be generated. Parameters: ticket - Unique number of the order ticket. price stoploss takeprofit expiration - New open price of the pending order. - New StopLoss level. - New TakeProfit level. - Pending order expiration time.

arrow_color - Arrow color for StopLoss/TakeProfit modifications in the chart. If the parameter is missing or has CLR_NONE value, the arrows will not be shown in the chart. Sample: if(TrailingStop>0) { OrderSelect(12345,SELECT_BY_TICKET); if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(),OrderOpenPrice(),Bid -Point*TrailingStop,OrderTakeProfit(),0,Blue); return(0); } } }

double OrderOpenPrice( ) Returns open price for the currently selected order. Order must be first selected by the OrderSelect() function. Sample: if(OrderSelect(10, SELECT_BY_POS)==true) Print("open price for the order 10 ",OrderOpenPrice()); else Print("OrderSelect returned the error of ",GetLastError()); datetime OrderOpenTime( ) Returns open time for the currently selected o rder. Note: The order must be previously selected by the OrderSelect() function. Sample: if(OrderSelect(10, SELECT_BY_POS)==true) Print("open time for the order 10 ",OrderOpenTime()); else Print("OrderSelect returned error of ",GetLastError()); void OrderPrint() Prints information about the selected order in the log in the following format: ticket number; open time; trade operation; amount of lots; open price; Stop Loss; Take Profit; close time; close price; commission; swap; profit; comment; magic number; pending order expiration date. Order must be selected by the OrderSelect() function. Sample: if(OrderSelect(10, SELECT_BY_TICKET)==true) OrderPrint(); else Print("OrderSelect failed error code is",GetLastError()); double OrderProfit( ) Returns the net profit value (without swaps or commissions) for the selected order. For open positions, it is the current unrealized profit. For closed orders, it is the fixed profit. Returns profit for the currently selected order. Note: The order must be previously selected by the OrderSelect() function. Sample: if(OrderSelect(10, SELECT_BY_POS)==true) Print("Profit for the order 10 ",OrderProfit()); else Print("OrderSelect returned the error of ",GetLastError()); bool OrderSelect(int index, int select, int pool=MODE_TRADES) The function selects an order for further processing. It returns TRUE if the function succeeds. It returns FALSE if the funct ion fails. To get the error information, one has to call the GetLastError() function. The pool parameter is ignored if the order is selected by the ticket number. The ticket number is a unique order identifier. To find o ut from what list the order has been selected, its close time must be analyzed. If the order close time equals to 0, the order is open or pending and taken from the terminal open positions list. One can distinguish an open position from a pend ing order by the order type. If the order close time does not equal to 0, the order is a closed order or a deleted pending order and was selected from the terminal history. They also differ from each other by their order types. Parameters: index - Order index or order ticket depending on the 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 the selected 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 returned the error of ",GetLastError()); int string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, OrderSend( datetime expiration=0, color arrow_color=CLR_NONE) The main function used to open a position or place a pending order. Returns number of the ticket assigned to the order by the trade server or -1 if it fails. To get additional error information, one has to call the GetLastError() function. Notes: At opening of a market order (OP_SELL or OP_BUY), only the latest prices of Bid (for selling) or Ask (for buying) can be used as open price. If operation is performed with a security differing from the current one, the MarketInfo() function must be used with MODE_BID or MODE_ASK parameter for the latest quotes for this security to be obtained. Calculated or unnormalized price cannot be applied. If ther e has not been the requested open price in the price thread or it has not been normalized according to the amount of digits after decimal point , the error 129 (ERR_INVALID_PRICE) will be generated. If the requested open price is fully out of date, the error 138 (ERR_REQUOTE) will be generated independently on the slippage

parameter. If the requested price is out of date, but present in the thread, the position will be opened at the current price and only if the current price lies within the range of price+-slippage. StopLoss and TakeProfit levels cannot be too close to the market. The minimal distance of stop levels in points can be obtain ed using the MarketInfo() function with MODE_STOPLEVEL parameter. In the case of erroneous or unnormalized stop levels, the error 130 (ERR_INVALID_STOPS) will be generated. At placing of a pending order, the open price cannot be too close to the market. The minimal distance of the pending price from the current market one in points can be obtained using the MarketInfo() function with the MODE_STOPLEVEL parameter. In case of false open price of a pending order, the error 130 (ERR_INVALID_STOPS) will be generated. Applying of pending order expiration time can be disabled in some trade servers. In this case, wh en a non-zero value is specified in the expiration parameter, the error 147 (ERR_TRADE_EXPIRATION_DENIED) will be generated. On some trade servers, the total amount of open and pending orders can be limited. If this limit has been exceeded, no new position will be opened (or no pending order will be placed) and trade server will return error 148 (ERR_TRADE_TOO_MANY_ORDERS). Parameters: symbol - Symbol for trading. cmd volume price slippage stoploss takeprofit comment magic expiration - Operation type. It can be any of the Trade operation enumeration. - Number of lots. - Preferred price of the trade. - Maximum price slippage for buy or sell orders. - Stop loss level. - Take profit level. - Order comment text. Last part of the comment may be changed by server. - Order magic number. May be used as user defined identifier. - Order expiration time (for pending orders only).

arrow_color - Color of the opening arrow on the chart. If parameter is missing 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); } } int OrdersHistoryTotal( ) Returns the number of closed orders in the account history loaded into the terminal. The history list size depends on the cur rent settings of the "Account history" tab of the terminal. Sample: // retrieving info from trade history int i,hstTotal=OrdersHistoryTotal(); 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 } double OrderStopLoss() Returns stop loss value for the currently selected order. Note: The order must be previously selected by the 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(),OrderLots()); } FileClose(handle); double OrderSwap() Returns swap value for the currently selected order. Note: The order must be previously selected by the 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: The order must be previously selected by the OrderSelect() function. Sample: if(OrderSelect(12, SELECT_BY_POS)==true) Print("symbol of order #", OrderTicket(), " is ", OrderSymbol()); else Print("OrderSelect failed error code is",GetLa stError()); double OrderTakeProfit() Returns take profit value for the currently selected order. Note: The order must be previously selected by the OrderSelect() function. Sample: if(OrderSelect(12, SELECT_BY_POS)==true) Print("Order #",OrderTicket()," profit: ", OrderTakeProfit()); else Print("OrderSelect() returns error - ",GetLastError()); int OrderTicket() Returns ticket number for the currently selected order. Note: The order must be previously selected by the 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()); A group of functions intended for working with the cur rent chart window. void HideTestIndicators(bool hide) The function sets a flag hiding indicators called by the Expert Advisor. After the expert has been tested and the appropriate chart opened, the flagged indicators will not be drawn in the testing chart. Every indicator called will first be flagged with the current hiding flag. It must be noted that only those indicators can be drawn in the testing chart that are directly called from the expert under test. Parameters: hide - TRUE, if there is a need to hide indicators, or else FALSE. Sample: HideTestIndicators(true); MaCurrent=iMA(NULL,0,56,0,MODE_EMA,PRICE_CLOSE,0); MaPrevious=iMA(NULL,0,56,0,MODE_EMA,PRICE_CLOSE,1); HideTestIndicators(false);

int Period() Returns the amount of minutes determining the used period (chart timeframe). Sample: Print("Period is ", Period()); bool RefreshRates() Refreshing of data in pre-defined variables and series arrays . This function is used when expert advisor has been calculating for a long time and needs data refreshing. Returns TRUE if data are refreshed, otherwise returns F ALSE. The only reason for data cannot be refreshed is that they are the current data of the client terminal. Experts and scripts operate with their own copy of history data. Data of the current symbol are copied at the first launch of the expert or script. At each subsequent launch of the expert (remember that script is executed only once and does not depend on incoming ticks), the initial copy will be updated. One or more new ticks can income while the expe rt or script is operating, and data can become out of date. 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(); //---- not enough money if(error==134) break; //---- 10 seconds wait Sleep(10000); //---- refresh price data RefreshRates(); break; } else { OrderSelect(ticket,SELECT_BY_TICKET); OrderPrint(); break; } } 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 because the order may be closed or deleted at this time! if(OrderSelect(pos, SELECT_BY_POS)==false) continue; if(OrderType()>OP_SELL || OrderSymbol()!=Symbol()) continue; // performs some processing... } int WindowBarsPerChart() Function returns the amount of bars visible on the chart. Sample: // work with visible bars. int bars_count=WindowBarsPerChart(); int bar=WindowFirstVisibleBar(); for(int i=0; i<bars_count; i++,bar--) { // ... } string WindowExpertName() Returns name of the executed expert, script, custom indicator, or library, depending on the MQL4 program, from which this fun ction has been called. Sample: string name=WindowExpertName(); GlobalVariablesDeleteAll(name); int WindowFind(string name) If indicator with name was found, the function returns the window index containing this specified indicator, otherwise it returns -1. Note: WindowFind() returns -1 if custom indicator searches itself when init() function works. Parameters: name - Indicator short name. Sample: int win_idx=WindowFind("MACD(12,26,9)"); int WindowFirstVisibleBar( )

The function returns the first visible bar number in the current chart window. It must be taken into consideration that price bars are numbered in the reverse order, from the last to the first one. The current bar, the latest in the price array, is indexed as 0. The oldest bar is indexed as Bars-1. If the first visible bar number is 2 or more bars less than the amount of visible bars in the chart, it means that the chart window has not been fully filled out and there is a space to the left. Sample: // work with visible bars. int bars_count=WindowBarsPerChart(); int bar=WindowFirstVisibleBar(); for(int i=0; i<bars_count; i++, bar--) { // ... } int WindowHandle(string symbol, int timeframe) Returns the system window handler containing the given chart. If the chart of symbol and timeframe has not been opened by the moment of function calling, 0 will be returned. Parameters: symbol - symbol name. timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. 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. The chart subwindow can be hidden due to the visibil ity properties of the indicator placed in it. 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, cust om indicator or script was dropped. This value is valid if the expert, custom indicator or script was dropped by mouse. Note: For custom indicators being initialized (call from the init() function), this index is not defined. The returned index is the number of window (0-chart main menu, subwindows of indicators are numbered starting from 1) where the custom indicator is working. A custom indicator can create its own new subwindow during its work, and the number of this subwindow will differ fr om that of the window where the indicator was really dropped in. See also WindowXOnDropped(), WindowYOnDropped() Sample: if(WindowOnDropped()!=0) { Print("Indicator 'MyIndicator' must be applied to main chart window!"); return(false); } double WindowPriceMax( int index=0) Returns maximal value of the vertical scale of the specified subwindow of the current chart (0 -main chart window, the indicators' subwindows are numbered starting from 1). If the subwindow index has not been specified, the maximal value of the price scale of the main ch art window is returned. See also WindowPriceMin(), WindowFirstVisibleBar(), WindowBarsPerChart() Parameters: index - Chart subwindow index (0 - main chart window). Sample: double top=WindowPriceMax(); double bottom=WindowPriceMin(); datetime left=Time[WindowFirstVisibleBar()]; int right_bound=WindowFirstVisibleBar() -WindowBarsPerChart(); if(right_bound<0) right_bound=0; datetime right=Time[right_bound]+Period()*60; //---ObjectCreate("Padding_rect",OBJ_RECTANGLE,0,left,top,right,bottom); ObjectSet("Padding_rect",OBJPROP_BACK,true); ObjectSet("Padding_rect",OBJPROP_COLOR,Blue); WindowRedraw(); double WindowPriceMin(int index=0) Returns minimal value of the vertical scale of the specified subwindow of the current chart (0 -main chart window, the indicators' subwindows are numbered starting from 1). If the subwindow index has not been specified, the minimal value of the price scale of the main chart window is returned. See also WindowPriceMax(), WindowFirstVisibleBar(), WindowBarsPerChart()

Parameters: index - Chart subwindow index (0 - main chart window). Sample: double top=WindowPriceMax(); double bottom=WindowPriceMin(); datetime left=Time[WindowFirstVisibleBar()]; int right_bound=WindowFirstVisibleBar() -WindowBarsPerChart(); if(right_bound<0) right_bound=0; datetime right=Time[right_bound]+Period()*60; //---ObjectCreate("Padding_rect",OBJ_RECTANGLE,0,left,top,right,bottom); ObjectSet("Padding_rect",OBJPROP_BACK,true); ObjectSet("Padding_rect",OBJPROP_COLOR,Blue); WindowRedraw(); double WindowPriceOnDropped() Returns the price part of the chart point where expert or script was dropped. This value is only valid if the expert or script was dropped by mouse. Note: For custom indicators, this value is undefined. Sample: double drop_price=WindowPriceOnDropped(); datetime drop_time=WindowTimeOnDropped(); //---- 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); } void WindowRedraw() Redraws the current chart forcedly. It is normally used after the objects properties have been changed . Sample: //---- set new properties for some objects ObjectMove(object_name1, 0, Time[index], price); ObjectSet(object_name1, OBJPROP_ANGLE, angle*2); ObjectSet(object_name1, OBJPROP_FONTSIZE, fontsize); ObjectSet(line_name, OBJPROP_TIME2, time2); ObjectSet(line_name, OBJPROP_ANGLE, line_angle); //---- now redraw all WindowRedraw(); bool WindowScreenShot(string filename, int size_x, int size_y, int start_bar=-1, int chart_scale=-1, int chart_mode=-1) Saves current chart screen shot as a GIF file. Returns FALSE if it fails. To get the error code, one has to use the GetLastError() function. The screen shot is saved in the terminal_dir\experts\files (terminal_dir\tester\files in case of testing) directory or its subdirectories. Parameters: filename - Screen shot file name. size_x size_y start_bar chart_scale chart_mode - Screen shot width in pixels. - Screen shot height in pixels. - Index of the first visible bar in the screen shot. If 0 value is set, the current first visible bar will be shot. If no value or negative value has been set, the end-of-chart screen shot will be produced, indent being taken into consideration. - Horizontal chart scale for screen shot. Can be in the range from 0 to 5. If no value or negative value has been set, the curr ent chart scale will be used. - Chart displaying mode. It can take the following values: CHART_BAR (0 is a sequence of bars), CHART_CANDLE (1 is a sequence of candlesticks), CHART_LINE (2 is a close prices line). If no value or negative value has been set, the chart will be shown in its current mode.

Sample: int lasterror=0; //---- tester has closed one or more trades if(IsTesting() && ExtTradesCounter<TradesTotal()) { //---- make WindowScreenShot for further checking if(!WindowScreenShot("shots\\tester"+ExtShotsCounter+".gif",640,480)) lasterror=GetLastError(); else ExtShotsCounter++; ExtTradesCounter=TradesTotal(); } datetime WindowTimeOnDropped() Returns the time part of the chart point where expert or script was dropped. This value is only valid if the expert or script was dropped by mouse. Note: For custom indicators, this value is undefined. Sample: double drop_price=WindowPriceOnDropped(); datetime drop_time=WindowTimeOnDropped(); //---- 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 WindowsTotal() Returns count of indicator windows on the chart (including main chart). Sample: Print("Windows count = ", WindowsTotal()); int WindowXOnDropped() Returns the value at X axis in pixels for the chart window client area point at which the expert or script was dropped. The value will be true only if the expert or script were moved with the mouse ("Drag'n'Drop") technique. See also WindowYOnDropped(), WindowOnDropped() Sample: Print("Expert dropped point x=",WindowXOnDropped()," y=",WindowYOnDropped()); int WindowYOnDropped() Returns the value at Y axis in pixels for the chart window client ar ea point at which the expert or script was dropped. The value will be true only if the expert or script were moved with the mouse ("Drag'n'Drop") technique. See also WindowXOnDropped(), WindowPriceOnDropped(), WindowOnDropped() Sample: Print"Expert was attached to the window in the point x=",WindowXOnDropped()," y=", WindowYOnDropped()); In further development of MQL4, some functions were renamed and moved from one group to another in order to systematize them better. The old function names are not highlighted or linked to the MetaEditor Dictionary. The old function na mes can be used since the compiler will accept them in a proper way. However, we strongly recommend to use the new names. Old Name New Name BarsPerWindow ClientTerminalName CurTime CompanyName FirstVisibleBar Highest HistoryTotal LocalTime Lowest ObjectsRedraw PriceOnDropped ScreenShot ServerAddress TimeOnDropped WindowBarsPerChart TerminalName TimeCurrent TerminalCompany WindowFirstVisibleBar iHighest OrdersHistoryTotal TimeLocal iLowest WindowRedraw, WindowPriceOnDropped WindowScreenShot AccountServer WindowTimeOnDropped

Vous aimerez peut-être aussi