MQL4 Reference
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. You can start learning the language using Sergey Kovalyov's book named Programming in Algorithmic Language MQL4 published and supported by MetaQuotes Software Corp. You can download the Book in .chm format at: http://www.mql4.com/files/mql4bookenglish.chm (size 2.0 Mb).
A large amount of functions necessary for analysis of the current and previously income 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:
Expert Advisor is a mechanical trading system (MTS) 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 displaying trading in-and-out points in the chart.
Experts are stored in terminal_directory\experts.
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.
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.
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.
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 experts, 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 Basics
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
Syntax of MQL4 is much a C-like syntax, apart from some features: no address arithmetic;
no operator do ... while; no operator goto ...;
no operation of [condition]?[expression 1]:[expression 2]; no compound data types (structures);
complex assignments are impossible; for example, val1=val2=0; arr[i++]=val; cond=(cnt=OrdersTotal)>0; etc.; calculation of a logical expression is always completed, never early terminated.
Comments
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 are possible and tolerate any number of spaces.
Examples:
// single comment /* multi-
line // nested single comment comment
*/
Identifiers
Identifiers are used as names of variables, functions, and data types. The length of an identifier cannot exceed 31 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), the symbol of underlining (_). The first symbol cannot be a number. The identifier must not coincide with any reserved word.
Examples:
NAME1 namel Total_5 Paper
Reserved words
The identifiers listed below are fixed reserved words. A certain action is assigned to each of them, and they cannot be used for other purposes:
Data types Memory classes Operators Other
bool extern break false
color static case true
datetime continue double default int else string for void if return switch while
Data types
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 data type is foreseen for price data in MQL 4.
Data of different types are processed with different 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 slower than the integer ones. String data are processed at the longest because of dynamic computer memory allocation/reallocation.
The main data types are: Integer (int) Boolean (bool) Literals (char) Strings (string)
Floating-point number (double) Color (color)
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.
Type casting
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.12500000" (the string containing 10 characters)
string s = NULL; // the constant of type int is cast 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.
Integer constants
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.
Literal constants
Any single character enclosed in single quotes or a hexadecimal ASCII-code of a character looking like '\x10' is a character constant of integer type. Some characters like a single quote ('), double quote (") a question mark (?), a reverse slash (\), and control characters can be represented as a combination of characters starting with a reverse slash (\) according to the table below:
line feed NL (LF) \n horizontal tab HT \t carriage return CR \r reverse slash \ \\ single quote ' \' double quote " \" hexadecimal ASCII-code hh \xhh
If a character different from those listed above follows the reverse slash, the result will not be defined: 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
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 number constants (double)
Floating-point constants consist of an integer part, a point (.), and a fractional part. The integer and the fractional parts 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 constants
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
Color constants can be represented in three ways: literally, 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. Numerical rate values of a color component lie in the range from 0 to 255.
Integer-valued representation is written in a form of hexadecimal or a decimal number. A hexadecimal number looks like 0x00BBGGRR where RR is the rate of the red color component, GG - of the green one, and BB - of the blue one. Decimal constants are not directly reflected in RGB. They represent 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
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 be skipped. Datetime constant can vary from Jan 1, 1970 to Dec 31, 2037.
Examples: D'2004.01.01 00:00' // New Year D'1980.07.19 12:30:27' D'19.07.1980 12:30:27' D'19.07.1980 12' //equal to D'1980.07.19 12:00:00' D'01.01.2004' //equal to D'01.01.2004 00:00:00'
D'12:30:27' //equal to D'[compilation date] 12:30:27' D'' //equal to D'[compilation date] 00:00:00'
Operations & Expressions
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 language elements from each other.
Expressions
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
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 left 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. The logical shift operation uses values of x less than 5 binary digits. The greater digits are rejected, so the shift is for the range of 0 to 31 bit. By %= operation (y value by module of x), the result sign is equal to the sign of divided number.
Operations of relation
The logical value FALSE is represented with an integer zero value, while the logical value TRUE is represented with any value differing from zero. The value of expressions containing operations of relation or logical operations is 0 (FALSE) or 1 (TRUE).
True if a equals b a == b; True if a does not equal b a != b; True if a is less than b a < b; True if a is greater than b a > b; True if a is less than or equals b a <= b; True if a is greater than or equals b a >= b;
Two unnormalized floating-point numbers cannot be linked by == or != operations. That is why it is necessary to subtract one from another, and the normalized outcome needs to be compared to null.
Boolean operations
Operand of logical negation (operation NOT displayed as exclamation mark) must be of arithmetic type. The result equals TRUE (1) if the operand value is FALSE (0); and it equals FALSE (0) if the operand differs from FALSE (0).
if(!a) Print("not 'a'");
Logical operation OR (||) of x and y values. The expression value is TRUE (1) if x or y value is true (not null). Otherwise, it is FALSE (0). Logical expressions are calculated completely, i.e., the so-called "short estimate" method does not apply to them.
if(x<0 || x>=max_bars) Print("out of range");
Logical operation AND (&&) of x and y values. The expression value is TRUE (1) if both x and y values are ture (not null). Otherwise, it is FALSE (0).
if(p!=x && p>y) Print("TRUE");
Complement of the variable value up to one. The value of the expression contains 1 in all digits where n contains 0, and it contains 0 in all digits where n contains 1.
b = ~n;
Binary-coded representation of x is shifted to the right by y digits. The right shift is 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 be 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. Other operations
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 measurement 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 separated by commas and must be inside of parentheses, the opening parenthesis to follow the name of the called function.
The expression value is the value returned by the function. If the returned value is of the void type, such function call cannot 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;
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 (see above) can be considered as an example.
Example:
for(i=0,j=99; i<100; i++,j--) Print(array[i][j]);
Precedence rulesEach group of operations in the table has the same priority. The higher is the priority, the higher is the position of the group 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!");
Compound operatorA 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; } Expression operator
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. Break 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); } Return operator
A return operator terminates the current function execution and returns the control to the calling program. A return(expression); operator terminates the current function execution with result transmission. The operator expression must be enclosed in parentheses and 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. Conditional operator if-else
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.
// The else part refers to the second if operator: if(x>1)
if(y==2) z=5; else z=6;
// The else part refers to the first if operator: if(x>l) { if(y==2) z=5; } else z=6; // Nested operators if(x=='a') { y=1; } else if(x=='b') { y=2; z=3; } else if(x=='c') { y = 4; }
Else Print ("ERROR");
Switch operator
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 not 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.
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; }
Cycle operator while
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++; }
Cycle operator for
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 ','.
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]; Functions
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 passed 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 string") {
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 contextually 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 to the function. The order of expressions calculation and that of values loading are guaranteed. During the execution, the system checks the number and type of arguments given to the function. Such way of addressing to the function is called a value call. Function 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 first 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.
Special functions
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 initialization.
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. Functions 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 used for them to be defined and for types to be declared. Description is not an operator.
The basic types are:
bool - boolean values of true and false; string - character strings;
double - double-precision numbers with floating point.
Examples: string MessageBox; int Orders; double SymbolPrice; bool bLog; Additional types:
color is an integer representing an RGB color;
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 is 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.
Local variables
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); } Formal parameters
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 function. 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. Parameters, 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 be 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 corresponding 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 passed 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 data 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, unlike 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 variable is declared, the value of this variable not getting lost.
Global variables
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 defined 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 its type. Global variables can be initialized only once after program loading 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. Defining extern variables
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.
Initialization of variables
Any variable can be initialized at its defining. Any variable is initialized with zero (0) if no other initial value is explicitly defined. Global and static variables can be initialized only by a constant of the corresponding type. Local variables can be initialized by any expression, not only constant. Global and static variables are initialized only once. Local variables are initialized every time by call of the corresponded functions.
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 the 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 initialized with constants only. External functions definition
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 block pointer). If there is a need to pass data of the int or double type, then the one-dimensional array of the corresponding type should 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
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 containing source codes of MQL4 programs. The possibility to assign mnemonic names to specific constants contributes to enhancement of the code readability.
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 character.
Using the #define construction, one can define the symbolic name or symbolic constant at the program start to be the specific symbol 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"); } Controlling compilation
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 Type Description
link string a link to the company website copyright string the company name
stacksize int stack size
library a library; no start function is assigned, non-referenced functions are not removed indicator_chart_window void show the indicator in the chart window
indicator_separate_window void show the indicator in a separate window indicator_buffers int the number of buffers for calculation, up to 8
indicator_minimum double the bottom scaling limit for a separate indicator window indicator_maximum double the top scaling limit for a separate indicator window indicator_colorN color the color for displaying line N, where N lies between 1 and 8 indicator_widthN int width of the line N, where N lies between 1 and 8
indicator_styleN int style of the line N, where N lies between 1 and 8
indicator_levelN double predefined level N for separate window custom indicator, where N lies between 1 and 8 indicator_levelcolor color level line color
indicator_levelwidth int level line width indicator_levelstyle int level line style
show_confirm void before script run message box with confirmation appears
show_inputs void before script run its property sheet appears; disables show_confirm property
#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. Including of files
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 source code is located). The standard directory is not searched in.
Importing of functions
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 description 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 different 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 to imported functions (both from EX4 and from DLL modules) cannot have values by default.
#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.
Standard constants
To simplify the program writing and to make program texts more convenient 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 arrays
Series array identifier used with ArrayCopySeries(), iHighest() and iLowest() functions. It can be any of the following values:
Constant Value Description
MODE_OPEN 0 Open price. MODE_LOW 1 Low price. MODE_HIGH 2 High price. MODE_CLOSE 3 Close price.
MODE_VOLUME 4 Volume, used in iLowest() and iHighest() functions. 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 1 1 minute. PERIOD_M5 5 5 minutes. PERIOD_M15 15 15 minutes. PERIOD_M30 30 30 minutes. PERIOD_H1 60 1 hour. PERIOD_H4 240 4 hour. PERIOD_D1 1440 Daily. PERIOD_W1 10080 Weekly. PERIOD_MN1 43200 Monthly.
0 (zero) 0 Timeframe used on the chart. Trade operations
Operation type for the OrderSend() function. It can be any of the following values:
Constant Value Description
OP_BUY 0 Buying position. OP_SELL 1 Selling position.
OP_BUYLIMIT 2 Buy limit pending position. OP_SELLLIMIT 3 Sell limit pending position. OP_BUYSTOP 4 Buy stop pending position. OP_SELLSTOP 5 Sell stop pending position. Price constants
Applied price constants. It can be any of the following values:
Constant Value Description
PRICE_CLOSE 0 Close price. PRICE_OPEN 1 Open price. PRICE_HIGH 2 High price. PRICE_LOW 3 Low price.
PRICE_MEDIAN 4 Median price, (high+low)/2. PRICE_TYPICAL 5 Typical price, (high+low+close)/3.
PRICE_WEIGHTED 6 Weighted close price, (high+low+close+close)/4.
Market information identifiers, used with MarketInfo() function. It can be any of the following values:
Constant Value Description
MODE_LOW 1 Low day price. MODE_HIGH 2 High day price.
MODE_TIME 5 The last incoming tick time (last known server time).
MODE_BID 9 Last incoming bid price. For the current symbol, it is stored in the predefined variable Bid
MODE_ASK 10 Last incoming ask price. For the current symbol, it is stored in the predefined variable Ask
MODE_POINT 11 Point size in the quote currency. For the current symbol, it is stored in the predefined variable
Point
MODE_DIGITS 12 Count of digits after decimal point in the symbol prices. For the current symbol, it is stored in the predefined variable Digits
MODE_SPREAD 13 Spread value in points. MODE_STOPLEVEL 14 Stop level in points.
MODE_LOTSIZE 15 Lot size in the base currency. MODE_TICKVALUE 16 Tick value in the deposit currency. MODE_TICKSIZE 17 Tick size in the quote currency. MODE_SWAPLONG 18 Swap of the long position. MODE_SWAPSHORT 19 Swap of the short position.
MODE_STARTING 20 Market starting date (usually used for futures). MODE_EXPIRATION 21 Market expiration date (usually used for futures). MODE_TRADEALLOWED 22 Trade is allowed for the symbol.
MODE_MINLOT 23 Minimum permitted amount of a lot. MODE_LOTSTEP 24 Step for changing lots.
MODE_MAXLOT 25 Maximum permitted amount of a lot.
MODE_SWAPTYPE 26 Swap calculation method. 0 - in points; 1 - in the symbol base currency; 2 - by interest; 3 - in the margin currency.
MODE_PROFITCALCMODE 27 Profit calculation mode. 0 - Forex; 1 - CFD; 2 - Futures.
MODE_MARGINCALCMODE 28 Margin calculation mode. 0 - Forex; 1 - CFD; 2 - Futures; 3 - CFD for indices. MODE_MARGININIT 29 Initial margin requirements for 1 lot.
MODE_MARGINMAINTENANCE 30 Margin to maintain open positions calculated for 1 lot. MODE_MARGINHEDGED 31 Hedged margin calculated for 1 lot.
MODE_MARGINREQUIRED 32 Free margin required to open 1 lot for buying.
MODE_FREEZELEVEL 33 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.
Drawing shape style enumeration for SetIndexStyle() function.
It can be any of the following values:
Constant Value Description
DRAW_LINE 0 Drawing line. DRAW_SECTION 1 Drawing sections. DRAW_HISTOGRAM 2 Drawing histogram. DRAW_ARROW 3 Drawing arrows (symbols).
DRAW_ZIGZAG 4 Drawing sections between even and odd indicator buffers. DRAW_NONE 12 No drawing.
Drawing style. Valid when width=1. It can be any of the following values:
Constant Value Description
STYLE_SOLID 0 The pen is solid. STYLE_DASH 1 The pen is dashed. STYLE_DOT 2 The pen is dotted.
STYLE_DASHDOT 3 The pen has alternating dashes and dots. STYLE_DASHDOTDOT 4 The pen has alternating dashes and double dots. Arrow codes
Predefined Arrow codes enumeration. Arrows code constants. It can be one of the following values:
Constant Value Description
SYMBOL_THUMBSUP 67 Thumb up symbol (
). SYMBOL_THUMBSDOWN 68 Thumb down symbol (). SYMBOL_ARROWUP 241 Arrow up symbol (). SYMBOL_ARROWDOWN 242 Arrow down symbol (). SYMBOL_STOPSIGN 251 Stop sign symbol (). SYMBOL_CHECKSIGN 252 Check sign symbol (
).
Special Arrow codes that exactly points to price and time. It can be one of the following values:
Constant Value Description
1
Upwards arrow with tip rightwards (
↱
).2
Downwards arrow with tip rightwards (
↳
). 3 Left pointing triangle (◄
).4 En Dash symbol (–). SYMBOL_LEFTPRICE 5 Left sided price label. SYMBOL_RIGHTPRICE 6 Right sided price label.
Wingdings font symbols used with Arrow objects. 32
33 34
35
36
֠
3738
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
!
57"
58#
59$
60%
61&
62'
63(
64)
65*
6667
68
+
69,
70-
71.
72/
73☺
741
752
763
774
785
796
807
818
829
83:
84;
85<
86=
87>
88?
89@
90☯
91B
92C
93D
94E
95F
96G
97H
98I
99J
100K
101L
102M
103N
104O
105P
106Q
107R
108S
109T
110U
111V
112W
113X
114Y
115Z
116[
117\
118]
119
120ִ
121`
122a
123b
124c
125d
126
127f
128g
129h
130i
131j
132k
133l
134m
135n
136o
137p
138q
139r
140s
141t
142u
143v
144w
145x
146y
147z
148{
149|
150}
151~
152
153
154
155
156
157
158159
160
161
162
163
164
165
166167
168
169
170
171
172 173
174
175
176
177
178
179
180
181
182
183
184
185
186
187188
¡
189¢
190£
191¤
192¥
193¦
194§
195¨
196©
197ª
198«
199¬
200
201®
202¯
203°
204±
205²
206³
207´
208µ
209¶
210·
211¸
212
213
214»
215¼
216½
217¾
218¿
219À
220Á
221Â
222Ã
223Ä
224Å
225Æ
226Ç
227È
228É
229Ê
230Ë
231Ì
232Í
233Î
234Ï
235Ð
236Ñ
237Ò
238Ó
239Ô
240241
242
Õ
243Ö
244×
245Ø
246Ù
247Ú
248Û
249Ü
250251
252
Ý
253Þ
254ß
255 Web colorscolor type supported color constants.
Black DarkGreen DarkSlateGray Olive Green Teal Navy Purple
Maroon Indigo MidnightBlue DarkBlue DarkOliveGreen SaddleBrown ForestGreen OliveDrab
SeaGreen DarkGoldenrod DarkSlateBlue Sienna MediumBlue Brown DarkTurquoise DimGray
LightSeaGreen DarkViolet FireBrick MediumVioletRed MediumSeaGreen Chocolate Crimson SteelBlue
Goldenrod MediumSpringGreen LawnGreen CadetBlue DarkOrchid YellowGreen LimeGreen OrangeRed
DarkOrange Orange Gold Yellow Chartreuse Lime SpringGreen Aqua
DeepSkyBlue Blue Magenta Red Gray SlateGray Peru BlueViolet
LightSlateGray DeepPink MediumTurquoise DodgerBlue Turquoise RoyalBlue SlateBlue DarkKhaki
IndianRed MediumOrchid GreenYellow MediumAquamarine DarkSeaGreen Tomato RosyBrown Orchid
MediumPurple PaleVioletRed Coral CornflowerBlue DarkGray SandyBrown MediumSlateBlue Tan
DarkSalmon BurlyWood HotPink Salmon Violet LightCoral SkyBlue LightSalmon
Plum Khaki LightGreen Aquamarine Silver LightSkyBlue LightSteelBlue LightBlue
PaleGreen Thistle PowderBlue PaleGoldenrod PaleTurquoise LightGray Wheat NavajoWhite
Moccasin LightPink Gainsboro PeachPuff Pink Bisque LightGoldenrod BlanchedAlmond
LemonChiffon Beige AntiqueWhite PapayaWhip Cornsilk LightYellow LightCyan Linen
Lavender MistyRose OldLace WhiteSmoke Seashell Ivory Honeydew AliceBlue
LavenderBlush MintCream Snow White
Indicator line identifiers used in iMACD(), iRVI() and iStochastic() indicators. It can be one of the following values:
Constant Value Description
MODE_MAIN 0 Base indicator line. MODE_SIGNAL 1 Signal line. Indicator line identifiers used in iADX() indicator.
Constant Value Description
MODE_MAIN 0 Base indicator line. MODE_PLUSDI 1 +DI indicator line. MODE_MINUSDI 2 -DI indicator line.
Indicator line identifiers used in iBands(), iEnvelopes(), iEnvelopesOnArray(), iFractals() and iGator() indicators.
Constant Value Description
MODE_UPPER 1 Upper line. MODE_LOWER 2 Lower line. Ichimoku Kinko Hyo
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 1 Tenkan-sen. MODE_KIJUNSEN 2 Kijun-sen. MODE_SENKOUSPANA 3 Senkou Span A. MODE_SENKOUSPANB 4 Senkou Span B. MODE_CHINKOUSPAN 5 Chinkou Span. Moving Average methods
Moving Average calculation method used with iAlligator(), iEnvelopes(), iEnvelopesOnArray, iForce(), iGator(), iMA(), iMAOnArray(), iStdDev(), iStdDevOnArray(), iStochastic() indicators.
It can be any of the following values:
Constant Value Description
MODE_SMA 0 Simple moving average, MODE_EMA 1 Exponential moving average, MODE_SMMA 2 Smoothed moving average, MODE_LWMA 3 Linear weighted moving average.
The MessageBox() function return codes.
If a message box has a Cancel button, the function returns the IDCANCEL value if either the ESC key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing ESC has no effect.
Note: MessageBox return codes defined in the WinUser32.mqh file
Constant Value Description
IDOK 1 OK button was selected. IDCANCEL 2 Cancel button was selected. IDABORT 3 Abort button was selected. IDRETRY 4 Retry button was selected. IDIGNORE 5 Ignore button was selected. IDYES 6 Yes button was selected. IDNO 7 No button was selected. IDTRYAGAIN 10 Try Again button was selected. IDCONTINUE 11 Continue button was selected.
The MessageBox function flags specify the contents and behavior of the dialog box. This value can be a combination of flags from the following groups of flags.
To indicate the buttons displayed in the message box, specify one of the following values.
Constant Value Description
MB_OK 0x00000000 The message box contains one push button: OK. This is the default. MB_OKCANCEL 0x00000001 The message box contains two push buttons: OK and Cancel.
MB_ABORTRETRYIGNORE 0x00000002 The message box contains three push buttons: Abort, Retry, and Ignore. MB_YESNOCANCEL 0x00000003 The message box contains three push buttons: Yes, No, and Cancel. MB_YESNO 0x00000004 The message box contains two push buttons: Yes and No.
MB_RETRYCANCEL 0x00000005 The message box contains two push buttons: Retry and Cancel.
MB_CANCELTRYCONTINUE 0x00000006 Windows 2000: The message box contains three push buttons: Cancel, Try Again, Continue. Use this message box type instead of MB_ABORTRETRYIGNORE.
To display an icon in the message box, specify one of the following values.
Constant Value Description
MB_ICONSTOP, MB_ICONERROR, MB_ICONHAND
0x00000010 A stop-sign icon appears in the message box.
MB_ICONQUESTION 0x00000020 A question-mark icon appears in the message box. MB_ICONEXCLAMATION,
MB_ICONWARNING
0x00000030 An exclamation-point icon appears in the message box. MB_ICONINFORMATION,
MB_ICONASTERISK
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 types
Object type identifier constants used with ObjectCreate(), ObjectsDeleteAll() and ObjectType() functions. It can be any of the following values: Objects can have 1-3 coordinates related to type.
Constant Value Description
OBJ_VLINE 0 Vertical line. Uses time part of first coordinate. OBJ_HLINE 1 Horizontal line. Uses price part of first coordinate. OBJ_TREND 2 Trend line. Uses 2 coordinates.
OBJ_TRENDBYANGLE 3 Trend by angle. Uses 1 coordinate. To set angle of line use ObjectSet() function. OBJ_REGRESSION 4 Regression. Uses time parts of first two coordinates.
OBJ_CHANNEL 5 Channel. Uses 3 coordinates.
OBJ_STDDEVCHANNEL 6 Standard deviation channel. Uses time parts of first two coordinates. OBJ_GANNLINE 7 Gann line. Uses 2 coordinate, but price part of second coordinate ignored. OBJ_GANNFAN 8 Gann fan. Uses 2 coordinate, but price part of second coordinate ignored. OBJ_GANNGRID 9 Gann grid. Uses 2 coordinate, but price part of second coordinate ignored. OBJ_FIBO 10 Fibonacci retracement. Uses 2 coordinates.
OBJ_FIBOTIMES 11 Fibonacci time zones. Uses 2 coordinates. OBJ_FIBOFAN 12 Fibonacci fan. Uses 2 coordinates. OBJ_FIBOARC 13 Fibonacci arcs. Uses 2 coordinates. OBJ_EXPANSION 14 Fibonacci expansions. Uses 3 coordinates. OBJ_FIBOCHANNEL 15 Fibonacci channel. Uses 3 coordinates. OBJ_RECTANGLE 16 Rectangle. Uses 2 coordinates. OBJ_TRIANGLE 17 Triangle. Uses 3 coordinates. OBJ_ELLIPSE 18 Ellipse. Uses 2 coordinates.
OBJ_PITCHFORK 19 Andrews pitchfork. Uses 3 coordinates. OBJ_CYCLES 20 Cycles. Uses 2 coordinates.
OBJ_TEXT 21 Text. Uses 1 coordinate. OBJ_ARROW 22 Arrows. Uses 1 coordinate.
Object properties
Object value index used with ObjectGet() and ObjectSet() functions. It can be any of the following values:
Constant Value Type Description
OBJPROP_TIME1 0 datetime Datetime value to set/get first coordinate time part. OBJPROP_PRICE1 1 double Double value to set/get first coordinate price part. OBJPROP_TIME2 2 datetime Datetime value to set/get second coordinate time part. OBJPROP_PRICE2 3 double Double value to set/get second coordinate price part. OBJPROP_TIME3 4 datetime Datetime value to set/get third coordinate time part. OBJPROP_PRICE3 5 double Double value to set/get third coordinate price part. OBJPROP_COLOR 6 color Color value to set/get object color.
OBJPROP_STYLE 7 int Value is one of STYLE_SOLID, STYLE_DASH, STYLE_DOT, STYLE_DASHDOT, STYLE_DASHDOTDOT constants to set/get object line style.
OBJPROP_WIDTH 8 int Integer value to set/get object line width. Can be from 1 to 5. OBJPROP_BACK 9 bool Boolean value to set/get background drawing flag for object. OBJPROP_RAY 10 bool Boolean value to set/get ray flag of object.
OBJPROP_ELLIPSE 11 bool Boolean value to set/get ellipse flag for fibo arcs. OBJPROP_SCALE 12 double Double value to set/get scale object property.
OBJPROP_ANGLE 13 double Double value to set/get angle object property in degrees.
OBJPROP_ARROWCODE 14 int Integer value or arrow enumeration to set/get arrow code object property.
OBJPROP_TIMEFRAMES 15 int Value can be one or combination (bitwise addition) of object visibility constants to set/get timeframe object property.
OBJPROP_DEVIATION 16 double Double value to set/get deviation property for Standard deviation objects. OBJPROP_FONTSIZE 100 int Integer value to set/get font size for text objects.
OBJPROP_CORNER 101 int Integer value to set/get anchor corner property for label objects. Must be from 0-3. OBJPROP_XDISTANCE 102 int Integer value to set/get anchor X distance object property in pixels.
OBJPROP_YDISTANCE 103 int Integer value is to set/get anchor Y distance object property in pixels. OBJPROP_FIBOLEVELS 200 int Integer value to set/get Fibonacci object level count. Can be from 0 to 32. OBJPROP_LEVELCOLOR 201 color Color value to set/get object level line color.
OBJPROP_LEVELSTYLE 202 int Value is one of STYLE_SOLID, STYLE_DASH, STYLE_DOT, STYLE_DASHDOT, STYLE_DASHDOTDOT constants to set/get object level line style.
OBJPROP_LEVELWIDTH 203 int Integer value to set/get object level line width. Can be from 1 to 5.