Professional Documents
Culture Documents
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.
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
no address arithmetic;
complex assignments are impossible; for example, val1=val2=0; arr[i++]=val; cond=(cnt=OrdersTotal)>0; etc.;
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:
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.
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.
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
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:
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 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.
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'
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.
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
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
Assignment operation
The value of the expression that includes the given operation is the value of the left operand after assignment.
The following operations unite arithmetic or bitwise operations with operation of assignment:
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).
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.
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).
Bitwise operations
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.
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;
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.
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;
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 (see above) can be
considered as an example.
Example:
for(i=0,j=99; i<100; i++,j--) Print(array[i][j]);
Precedence rules
Each 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.
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.
Operators
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 operator
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;
}
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_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;
Continue operator
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.
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;
// 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.
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.
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];
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.
Function call
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.
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
When calling a function, one may not skip parameters, even those having default values:
Special functions
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
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.
Examples:
string MessageBox;
int Orders;
double SymbolPrice;
bool bLog;
Additional types:
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
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.
Static variables
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.
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.
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 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.
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.
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.
Constant declaration
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:
The constant identifier conforms to the same rules as those regulating names of variables. The value can be of any type:
...
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.
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.
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.
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.
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.
Series arrays
Series array identifier used with ArrayCopySeries(), iHighest() and iLowest() functions.
It can be any of the following values:
Timeframes
Timeframe of the chart (chart period). It can be any of the following values:
Trade operations
Operation type for the OrderSend() function. It can be any of the following values:
Price constants
MarketInfo
Market information identifiers, used with MarketInfo() function.
It can be any of the following values:
Drawing styles
Drawing shape style enumeration for SetIndexStyle() function.
Arrow codes
Predefined Arrow codes enumeration. Arrows code constants. It can be one of the following values:
2
Downwards arrow with tip rightwards (↳).
Wingdings
Wingdings font symbols used with Arrow objects.
32 33
34 35 36 ֠ 37 38 39 40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55 56 ! 57 " 58 # 59 $ 60 % 61 & 62 ' 63
( 64 ) 65 * 66 67 68 + 69 , 70 - 71 . 72 / 73 ☺ 74 1 75 2 76 3 77 4 78 5 79
6 80 7 81 8 82 9 83 : 84 ; 85 < 86 = 87 > 88 ? 89 @ 90 ☯ 91 B 92 C 93 D 94 E 95
F 96 G 97 H 98 I 99 J 100 K 101 L 102 M 103 N 104 O 105 P 106 Q 107 R 108 S 109 T 110 U 111
V 112 W 113 X 114 Y 115 Z 116 [ 117 \ 118 ] 119 120 ִ 121 ` 122 a 123 b 124 c 125 d 126 127
f 128 g 129 h 130 i 131 j 132 k 133 l 134 m 135 n 136 o 137 p 138 q 139 r 140 s 141 t 142 u 143
v 144 w 145 x 146 y 147 z 148 { 149 | 150 } 151 ~ 152 153 154 155 156 157 158
159
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
176 177 178 179 180 181 182 183 184 185 186 187 188 ¡ 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
Ô 240 241 242 Õ 243 Ö 244 × 245 Ø 246 Ù 247 Ú 248 Û 249 Ü 250 251 252 Ý 253 Þ 254 ß 255
Web colors
Indicator lines
Indicator line identifiers used in iMACD(), iRVI() and iStochastic() indicators.
It can be one of the following values:
Ichimoku Kinko Hyo identifiers used in iIchimoku() indicator call as source of requested data.
It can be one of the following values:
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:
MessageBox
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
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.
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.
Object value index used with ObjectGet() and ObjectSet() functions. It can be any of the following values:
Timeframes where object may be shown. Used in ObjectSet() function to set OBJPROP_TIMEFRAMES property.
Uninitialize reason codes returned by UninitializeReason() function. It can be any one of the following values:
Special constants
Special constants used to indicate parameters and variables states. It can be one of the following values:
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));
}
Predefined variables
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.
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.
Ask
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;
}
Bars
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]);
}
Bid
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);
}
Close
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 the last in the array is indexed as
0. The oldest bar, the first in the chart, is indexed as Bars-1.
Digits
int Digits
Number of digits after decimal point for the current symbol prices.
See also MarketInfo().
Sample:
Print(DoubleToStr(Close[0], Digits));
High
double High[]
Series array that contains the highest 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 the last in the array is indexed as
0. The oldest bar, the first in the chart, is indexed as Bars-1.
Low
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 the last in the array is indexed as
0. The oldest bar, the first in the chart, is indexed as Bars-1.
Open
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 the last in the array is indexed as
0. The oldest bar, the first in the chart, is indexed as Bars-1.
Point
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);
Time
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 since 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.
Volume
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 the last in the array is indexed as
0. The oldest bar, the first in the chart, is indexed as Bars-1.
Program Run
For an MQL4 program to work, it must be compiled (the "Compile" button or F5). It must be compiled without any errors (warnings 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 "Navigator" 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 expert.
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 attached 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 not 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.
Program Run
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
have been changed from the window of expert or custom indicator settings. An expert will also be initialized after the account has been changed.
Every program attached to a chart completes its work with the deinit() function. The deinit() function runs at the client terminal shutdown, at chart
closing, immediately before the symbol and/or chart period is changed, at successful recompiling 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() function. The deinit()
function must be executed within 2.5 seconds. If the function has not completed its execution within this time period, it will 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 context 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 the program was
being executed are skipped by the program until the current execution of the start() function 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, change 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 stop working command was
given, the time remaining for its work is 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 calling program
thread, as well.
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 expert, for example, or from
another client terminal launched at the same time), the library already loaded will be referenced to. Otherwise, the searching 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 PATH 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 copy 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 functions. To provide such a
convention, the key word __stdcall specific for compilers of Microsoft(r) company is used in the source codes of programs written 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 parameters 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 message 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.
Runtime errors
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 4001 At calling of an internal function, a wrong function pointer has been detected
ERR_NO_MEMORY_FOR_CALL_STACK 4003 At calling of an internal function, it is impossible to reallocate memory for the function
calls stack
ERR_RECURSIVE_STACK_OVERFLOW 4004 The data stack is overflowed at the recursive function call
ERR_NO_MEMORY_FOR_PARAM_STRING 4006 At calling of an internal function, it is impossible to allocate memory for passing the
string as a function parameter
ERR_NO_MEMORY_FOR_TEMP_STRING 4007 It is impossible to allocate the temporary buffer for string operations
ERR_NO_MEMORY_FOR_ARRAYSTRING 4010 At assignment, it is impossible to reallocate memory for a string in an array
ERR_TOO_LONG_STRING 4011 At assignment, too long resulting string to be placed into the service buffer (no
possibility to reallocate for the service buffer)
ERR_REMAINDER_FROM_ZERO_DIVIDE 4012 Dividing by 0 when taking the remainder of the division
ERR_ZERO_DIVIDE 4013 Dividing by 0
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 start 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.
There is a number of errors which are possible only as a result of software or hardware failure.If any errors described below occur repeatedly, one
should contact the developers.
There are some functions that always change the last_error variable value.
Some functions change value of the last_error variable only if an error occurs.
AccountBalance
double AccountBalance()
Returns balance value of the current account (the amount of money on the account).
Sample:
Print("Account balance = ",AccountBalance());
AccountCredit
double AccountCredit()
Returns credit value of the current account.
Sample:
Print("Account number ", AccountCredit());
AccountCompany
string AccountCompany()
Returns the brokerage company name where the current account was registered.
Sample:
Print("Account company name ", AccountCompany());
AccountCurrency
string AccountCurrency()
Returns currency name of the current account.
Sample:
Print("account currency is ", AccountCurrency());
AccountEquity
double AccountEquity()
Returns equity value of the current account. Equity calculation depends on trading server settings.
Sample:
Print("Account equity = ",AccountEquity());
AccountFreeMargin
double AccountFreeMargin()
Returns free margin value of the current account.
Sample:
Print("Account free margin = ",AccountFreeMargin());
AccountFreeMarginCheck
AccountFreeMarginMode
double AccountFreeMarginMode()
Calculation mode of free margin allowed to open positions on the current account. The calculation mode can take the following values:
AccountLeverage
int AccountLeverage()
Returns leverage of the current account.
Sample:
Print("Account #",AccountNumber(), " leverage is ", AccountLeverage());
AccountMargin
double AccountMargin()
Returns margin value of the current account.
Sample:
Print("Account margin ", AccountMargin());
AccountName
string AccountName()
Returns the current account name.
Sample:
Print("Account name ", AccountName());
AccountNumber
int AccountNumber()
Returns the number of the current account.
Sample:
Print("account number ", AccountNumber());
AccountProfit
double AccountProfit()
Returns profit value of the current account.
Sample:
Print("Account profit ", AccountProfit());
AccountServer
string AccountServer()
Returns the connected server name.
Sample:
Print("Server name is ", AccountServer());
AccountStopoutLevel
int AccountStopoutLevel()
Returns the value of the Stop Out level.
Sample:
Print("StopOut level = ", AccountStopoutLevel());
AccountStopoutMode
int AccountStopoutMode()
Returns the calculation mode for the Stop Out level. Calculation mode can take the following values:
Array functions
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 process predefined time series
Time[], Open[], High[], Low[], Close[], Volume[]
ArrayBsearch
int double array[], double value, int count=WHOLE_ARRAY, int start=0, int
ArrayBsearch( direction=MODE_ASCEND)
Returns the index of the first occurrence of a value in the first dimension of array if possible, or the nearest one, if the occurrence is not found.
The function cannot be used with string arrays and 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 - The value to search for.
count - Count of elements to search for. By default, it searches in the whole array.
start - Starting index to search for. By default, the search starts 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]));
ArrayCopy
If data (symbol name and/or timeframe differ from the current ones) are requested from another chart, the situation is possible 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 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 will 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]);
ArrayCopySeries
There is no real memory allocation for data array and nothing is copied. When such an array is accessed, the access is redirected. 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 lack. 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_ARRAY,0,MODE_DESCEND);
if(Period()<PERIOD_D1) dayshift++;
}
Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ",
TimeToStr(daytimes[dayshift]));
ArrayDimension
ArrayGetAsSeries
ArrayInitialize
int ArrayInitialize(double&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);
ArrayIsSeries
ArrayMinimum
ArrayRange
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);
ArrayResize
ArraySetAsSeries
ArraySize
Sample:
int count=ArraySize(array1);
for(int i=0; i<count; i++)
{
// some calculations.
}
ArraySort
Checkup
A group of functions that allow determining of the current status of the client terminal, including the environment status of the MQL4 program.
GetLastError
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);
}
IsConnected
bool IsConnected()
The function returns the status of the main connection between client terminal and server that performs data pumping. It returns 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
// ...
IsDemo
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");
IsDllsAllowed
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 functions
MessageBoxA(0,"an message","Message",MB_OK);
IsExpertEnabled
bool IsExpertEnabled()
Returns TRUE if expert adwisors are enabled for running, otherwise returns FALSE.
Sample:
while(!IsStopped())
{
...
if(!IsExpertEnabled()) break;
}
IsLibrariesAllowed
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();
IsOptimization
bool IsOptimization()
Returns TRUE if expert runs in the strategy tester optimization mode, otherwise returns FALSE.
Sample:
if(IsOptimization()) return(0);
IsStopped
bool IsStopped()
Returns TRUE if the program (an expert or a script) has been commanded to stop its operation, otherwise returns FALSE. The program 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
// ...
}
IsTesting
bool IsTesting()
Returns TRUE if expert runs in the testing mode, otherwise returns FALSE.
Sample:
if(IsTesting()) Print("I am testing now");
IsTradeAllowed
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");
IsTradeContextBusy
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");
IsVisualMode
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");
UninitializeReason
int UninitializeReason()
Returns the code of the uninitialization reason for the experts, custom indicators, and scripts. The returned values can be ones 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
}
//...
}
Client terminal
TerminalCompany
string TerminalCompany()
Returns the name of company owning the client terminal.
Sample:
Print("Company name is ",TerminalCompany());
TerminalName
string TerminalName()
Returns client terminal name.
Sample:
Print("Terminal name is ",TerminalName());
TerminalPath
string TerminalPath()
Returns the directory, from which the client terminal was launched.
Sample:
Print("Working directory is ",TerminalPath());
Common functions
Alert
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],"!!!");
Comment
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. Amount 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()));
GetTickCount
int GetTickCount()
The GetTickCount() function retrieves the number of milliseconds that have elapsed since the system was started. It is limited to the resolution of the
system timer.
Sample:
int start=GetTickCount();
// some hard calculations...
Print("Calculation time is ", GetTickCount()-start, " milliseconds.");
MarketInfo
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);
MessageBox
PlaySound
Print
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]);
SendFTP
SendMail
Sleep
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);
Conversion functions
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.
CharToStr
DoubleToStr
NormalizeDouble
StrToDouble
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");
StrToInteger
StrToTime
TimeToStr
Custom indicators
A group of functions used at producing of custom indicators.
IndicatorBuffers
IndicatorCounted
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 recalculate 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 last 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);
}
IndicatorDigits
IndicatorShortName
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);
}
SetIndexArrow
SetIndexBuffer
Sample:
double ExtBufferSilver[];
int init()
{
SetIndexBuffer(0, ExtBufferSilver); // first line buffer
// ...
}
SetIndexDrawBegin
SetIndexEmptyValue
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);
}
SetIndexLabel
SetIndexShift
SetIndexStyle
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 - Shape style. Can be one of Drawing shape styles listed.
style - 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);
SetLevelStyle
SetLevelValue
A group of functions providing the working with data of the datetime type (integer representing the amount of seconds elapsed from midnight, 1
January, 1970).
Day
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);
DayOfWeek
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 server time is modelled.
Sample:
// does not work on holidays.
if(DayOfWeek()==0 || DayOfWeek()==6) return(0);
DayOfYear
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);
Hour
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;
Minute
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");
Month
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");
Seconds
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);
TimeCurrent
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.
TimeDay
TimeDayOfWeek
TimeDayOfYear
TimeHour
TimeLocal
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);
TimeMinute
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());
TimeMonth
TimeSeconds
TimeYear
Year
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);
File functions
There are three directories (with subdirectories) where working files can be placed:
FileClose
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);
}
FileDelete
FileFlush
FileIsEnding
bool FileIsEnding(int handle)
Returns logical true if file pointer is at the end of the file, otherwise returns false. To get the detailed error information, call GetLastError() function. 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);
}
FileIsLineEnding
FileOpen
FileOpenHistory
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 information, call the GetLastError() function.
Notes: Client terminal can connect to servers of different brokerage companies. History data (HST files) for each brokerage company 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);
FileReadArray
FileReadDouble
Sample:
int handle;
double value;
handle=FileOpen("mydata.dat",FILE_BIN);
if(handle>0)
{
value=FileReadDouble(handle,DOUBLE_VALUE);
FileClose(handle);
}
FileReadInteger
FileReadNumber
FileReadString
Sample:
int handle;
string str;
handle=FileOpen("filename.csv", FILE_CSV|FILE_READ);
if(handle>0)
{
str=FileReadString(handle);
FileClose(handle);
}
FileSeek
FileSize
FileTell
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);
FileWrite
FileWriteArray
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);
}
FileWriteDouble
FileWriteInteger
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);
FileWriteString
Global variables
Global variables are kept in the client terminal within 4 weeks since the last access, then they will be deleted automatically. 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 programs launched in the client terminal.
GlobalVariableCheck
GlobalVariableDel
GlobalVariableGet
GlobalVariableName
Sample:
int var_total=GlobalVariablesTotal();
string name;
for(int i=0;i<var_total;i++)
{
name=GlobalVariableName(i);
Print(i,": Global variable name - ",name);
}
GlobalVariableSet
GlobalVariableSetOnCondition
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);
}
GlobalVariablesDeleteAll
nt GlobalVariablesDeleteAll(string prefix_name=NULL)
Deletes global variables. If the name prefix is not specified, all global variables will be deleted. Otherwise, only those variables 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");
GlobalVariablesTotal
int GlobalVariablesTotal()
The function returns the total count of global variables.
Sample:
Print(GlobalVariablesTotal()," global variables detected");
MathAbs
MathArccos
double MathArccos(double x)
The MathArccos function returns the arccosine of x within the range 0 to π (in radians). If x is less than -1 or exceeds 1, the MathArccos returns NaN
(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
MathArcsin
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
MathArctan
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
MathCeil
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*/
MathCos
MathExp
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
MathFloor
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*/
MathLog
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
MathMax
MathMin
MathMod
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
MathPow
MathRand
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());
MathRound
MathSin
MathSqrt
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
MathSrand
MathTan
double MathTan(double x)
MathTan returns the tangent of x. If x is greater than or equal to 263, or less than or equal to -263, a loss of significance in the result occurs, in which
case the function returns an indefinite (same as a quiet NaN).
Parameters:
x - Angle in radians.
Sample:
double pi=3.1415926535;
double x,y;
x=MathTan(pi/4);
Print("MathTan(",pi/4," = ",x);
//Output: MathTan(0.7856)=1
Object functions
A group of functions intended for working with graphical objects related to the current chart.
ObjectCreate
bool string name, int type, int window, datetime time1, double price1, datetime
ObjectCreate( time2=0, double price2=0, datetime time3=0, double price3=0)
Creation of an object with the specified name, type and initial coordinates in the specified window. Count of coordinates 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 - Object type. It can be any of the Object type enumeration values.
window - Index of the window where the object will be added. Window index must exceed or equal to 0 and be less than
WindowsTotal().
time1 - Time part of the first point.
price1 - Price part of the first point.
time2 - Time part of the second point.
price2 - Price part of the second point.
time3 - 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);
ObjectDelete
ObjectDescription
ObjectFind
ObjectGet
ObjectGetFiboDescription
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);
}
ObjectGetShiftByValue
ObjectGetValueByShift
ObjectMove
ObjectName
ObjectsDeleteAll
ObjectSet
ObjectSetFiboDescription
ObjectSetText
bool string name, string text, int font_size, string font=NULL, color
ObjectSetText( 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 - A text describing the object.
font_size - Font size in points.
font - Font name.
text_color - Text color.
Sample:
ObjectSetText("text_object", "Hello world!", 10, "Times New Roman", Green);
ObjectsTotal
ObjectType
String functions
A group of functions intended for working with data of the string type.
StringConcatenate
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 using 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);
StringFind
StringGetChar
StringLen
StringSetChar
StringSubstr
StringTrimLeft
StringTrimRight
Technical indicators
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 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 has to re-request (see example of ArrayCopySeries()).
iAC
iAD
iAlligator
double string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int
iAlligator( teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price,
int mode, int shift)
Calculates the Bill Williams' Alligator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Timeframe. It can be one of Timeframe enumeration values. 0 means the current chart timeframe.
jaw_period - Blue line averaging period (Alligator's Jaw).
jaw_shift - Blue line shift relative to the chart.
teeth_period - Red line averaging period (Alligator's Teeth).
teeth_shift - Red line shift relative to the chart.
lips_period - Green line averaging period (Alligator's Lips).
lips_shift - Green line shift relative to the chart.
ma_method - MA method. It can be any of Moving Average methods.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - 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);
iADX
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - Averaging period for calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - 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);
iATR
iAO
iBearsPower
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - Averaging period 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:
double val=iBearsPower(NULL, 0, 13,PRICE_CLOSE,0);
iBands
double string symbol, int timeframe, int period, int deviation, int bands_shift, int
iBands( 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - Averaging period to calculate the main line.
deviation - Deviation from the main line.
bands_shift - The indicator shift relative to the chart.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - 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);
iBandsOnArray
double double array[], int total, int period, int deviation, int bands_shift, int
iBandsOnArray( mode, int shift)
Calculation of the Bollinger Bands indicator on data stored in a numeric array. Unlike iBands(...), the iBandsOnArray 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 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 - The number of items to be counted. 0 means the whole array.
period - Averaging period for calculation of main line.
deviation - Deviation from main line.
bands_shift - The indicator shift relative to the chart.
mode - 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);
iBullsPower
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - Averaging period 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:
double val=iBullsPower(NULL, 0, 13,PRICE_CLOSE,0);
iCCI
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - Averaging period 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(iCCI(NULL,0,12,PRICE_TYPICAL,0)>iCCI(NULL,0,20,PRICE_TYPICAL,0)) return(0);
iCCIOnArray
iCustom
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
name - 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.
mode - 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);
iDeMarker
iEnvelopes
double string symbol, int timeframe, int ma_period, int ma_method, int ma_shift, int
iEnvelopes( 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
ma_period - Averaging period for calculation of the main line.
ma_method - MA method. It can be any of Moving Average method enumeration value.
ma_shift - MA shift. Indicator line offset relate to the chart by timeframe.
applied_price - Applied price. It can be any of Applied price enumeration values.
deviation - Percent deviation from the main line.
mode - 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);
iEnvelopesOnArray
double double array[], int total, int ma_period, int ma_method, int ma_shift,
iEnvelopesOnArray( double deviation, int mode, int shift)
Calculation of the Envelopes indicator on data stored in a numeric array. Unlike iEnvelopes(...), the iEnvelopesOnArray 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 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 - The number of items to be counted.
ma_period - Averaging period for calculation of the main line.
ma_method - MA method. It can be any of Moving Average method enumeration value.
ma_shift - MA shift. Indicator line offset relate to the chart by timeframe.
deviation - Percent deviation from the main line.
mode - 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=iEnvelopesOnArray(ExtBuffer, 0, 13, MODE_SMA, 0.2, MODE_UPPER,0 );
iForce
double string symbol, int timeframe, int period, int ma_method, int applied_price, int
iForce( 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - Averaging period for calculation.
ma_method - MA method. It can be any of Moving Average method enumeration value.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - 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);
iFractals
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
mode - 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);
iGator
double string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int
iGator( teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price, int
mode, int shift)
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
jaw_period - Blue line averaging period (Alligator's Jaw).
jaw_shift - Blue line shift relative to the chart.
teeth_period - Red line averaging period (Alligator's Teeth).
teeth_shift - Red line shift relative to the chart.
lips_period - Green line averaging period (Alligator's Lips).
lips_shift - Green line shift relative to the chart.
ma_method - MA method. It can be any of Moving Average method enumeration value.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - Indicator line 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);
iIchimoku
double string symbol, int timeframe, int tenkan_sen, int kijun_sen, int senkou_span_b,
iIchimoku( 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
tenkan_sen - Tenkan Sen averaging period.
kijun_sen - Kijun Sen averaging period.
senkou_span_b - Senkou SpanB averaging period.
mode - Source of data. It can be one of the Ichimoku Kinko Hyo mode enumeration.
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);
iBWMFI
double iBWMFI(string symbol, int timeframe, int shift)
Calculates the Bill Williams Market Facilitation index and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - 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);
iMomentum
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - Period (amount of bars) for calculation of price changes.
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(iMomentum(NULL,0,12,PRICE_CLOSE,0)>iMomentum(NULL,0,20,PRICE_CLOSE,0)) return(0);
iMomentumOnArray
iMFI
iMA
double string symbol, int timeframe, int period, int ma_shift, int ma_method, int
iMA( 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - Averaging period for calculation.
ma_shift - MA shift. Indicators line offset relate to the chart by timeframe.
ma_method - MA method. It can be any of the Moving Average method enumeration value.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - 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);
iMAOnArray
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 data 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 - The number of items to be counted. 0 means whole array.
period - Averaging period for calculation.
ma_shift - MA shift
ma_method - MA method. It can be any of the 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 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");
iOsMA
double string symbol, int timeframe, int fast_ema_period, int slow_ema_period, int
iOsMA( 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
fast_ema_period - Number of periods for fast moving average calculation.
slow_ema_period - Number of periods for slow moving average calculation.
signal_period - Number of periods for signal moving average calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
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);
iMACD
double string symbol, int timeframe, int fast_ema_period, int slow_ema_period, int
iMACD( 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 Histogram, this indicator
is displayed as two lines. In the Client Terminal, the Moving Average Convergence/Divergence is drawn as a histogram.
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.
fast_ema_period - Number of periods for fast moving average calculation.
slow_ema_period - Number of periods for slow moving average calculation.
signal_period - Number of periods for signal moving average calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - Indicator line 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(iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0)>iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL
,0)) return(0);
iOBV
iSAR
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
step - Increment, usually 0.02.
maximum - 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);
iRSI
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - 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);
iRSIOnArray
iRVI
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
period - Number of periods for calculation.
mode - 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);
iStdDev
double string symbol, int timeframe, int ma_period, int ma_shift, int ma_method, int
iStdDev( 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
ma_period - MA period.
ma_shift - MA shift.
ma_method - MA method. It can be any of Moving Average method enumeration value.
applied_price - Applied price. It can be any of Applied price enumeration values.
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);
iStdDevOnArray
double double array[], int total, int ma_period, int ma_shift, int ma_method, int
iStdDevOnArray( shift)
Calculation of the Standard Deviation indicator on data stored in a numeric array. Unlike iStdDev(...), the iStdDevOnArray 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 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 - The number of items to be counted.
ma_period - MA period.
ma_shift - 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);
iStochastic
double string symbol, int timeframe, int %Kperiod, int %Dperiod, int slowing, int
iStochastic( 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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
%Kperiod - %K line period.
%Dperiod - %D line period.
slowing - Slowing value.
method - MA method. It can be any ofMoving Average method enumeration value.
price_field - Price field parameter. Can be one of this values: 0 - Low/High or 1 - Close/Close.
mode - Indicator line 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);
iWPR
Timeseries access
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 possible 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 has
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. Volumes 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.
iBars
iBarShift
iClose
iHigh
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 - 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));
iHighest
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
type - Series array identifier. It can be any of the Series array identifier enumeration values.
count - Number of periods (in direction from the start bar to the back one) on which the calculation is carried out.
start - Shift showing the bar, relative to the current bar, that the data should be taken from.
Sample:
double val;
// calculating the highest value 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)];
iLow
iLowest
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 - Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe.
type - Series array identifier. It can be any of Series array identifier enumeration values.
count - Number of periods (in direction from the start bar to the back one) on which the calculation is carried out.
start - Shift showing the bar, relative to the current bar, that the data should be taken from.
Sample:
// 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)];
iOpen
iTime
iVolume
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 the 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 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));
Trading functions
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" property 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 cannot 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.
Execution errors
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 recommendations are given below.
OrderClose
bool OrderClose(int ticket, double lots, double price, int slippage, color Color=CLR_NONE)
Closes opened order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error
information, call GetLastError().
Parameters:
ticket - Unique number of the order ticket.
lots - Number of lots.
price - Preferred closing price.
slippage - Value of the maximum price slippage in points.
Color - Color of the closing arrow on the chart. If the parameter is 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);
}
OrderCloseBy
OrderClosePrice
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());
OrderCloseTime
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());
OrderComment
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();
// ...
OrderCommission
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());
OrderDelete
OrderExpiration
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());
OrderLots
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());
OrderMagicNumber
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());
OrderModify
bool int ticket, double price, double stoploss, double takeprofit, datetime
OrderModify( 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 - New open price of the pending order.
stoploss - New StopLoss level.
takeprofit - New TakeProfit level.
expiration - 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);
}
}
}
OrderOpenPrice
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());
OrderOpenTime
datetime OrderOpenTime()
Returns open time 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("open time for the order 10 ",OrderOpenTime());
else
Print("OrderSelect returned error of ",GetLastError());
OrderPrint
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());
OrderProfit
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());
OrderSelect
OrderSend
int string symbol, int cmd, double volume, double price, int slippage, double stoploss,
OrderSend( double takeprofit, string comment=NULL, int magic=0, 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 there 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 obtained 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, when 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 - Operation type. It can be any of the Trade operation enumeration.
volume - Number of lots.
price - Preferred price of the trade.
slippage - Maximum price slippage for buy or sell orders.
stoploss - Stop loss level.
takeprofit - Take profit level.
comment - Order comment text. Last part of the comment may be changed by server.
magic - Order magic number. May be used as user defined identifier.
expiration - Order expiration time (for pending orders only).
arrow_color - Color of the opening arrow on the chart. If parameter is 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);
}
}
OrdersHistoryTotal
int OrdersHistoryTotal()
Returns the number of closed orders in the account history loaded into the terminal. The history list size depends on the current 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
}
OrderStopLoss
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());
OrdersTotal
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);
OrderSwap
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());
OrderSymbol
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",GetLastError());
OrderTakeProfit
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());
OrderTicket
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());
OrderType
int OrderType()
Returns order operation type for the currently selected order. It can be any of the following values:
OP_BUY - buying position,
OP_SELL - selling position,
OP_BUYLIMIT - buy limit pending position,
OP_BUYSTOP - buy stop pending position,
OP_SELLLIMIT - sell limit pending position,
OP_SELLSTOP - sell stop pending position.
Note: order must be selected by OrderSelect() function.
Sample:
int order_type;
if(OrderSelect(12, SELECT_BY_POS)==true)
{
order_type=OrderType();
// ...
}
else
Print("OrderSelect() returned error - ",GetLastError());
Window functions
A group of functions intended for working with the current chart window.
HideTestIndicators
Period
int Period()
Returns the amount of minutes determining the used period (chart timeframe).
Sample:
Print("Period is ", Period());
RefreshRates
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 FALSE. 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 expert 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;
}
}
Symbol
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...
}
WindowBarsPerChart
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--)
{
// ...
}
WindowExpertName
string WindowExpertName()
Returns name of the executed expert, script, custom indicator, or library, depending on the MQL4 program, from which this function has been called.
Sample:
string name=WindowExpertName();
GlobalVariablesDeleteAll(name);
WindowFind
WindowFirstVisibleBar
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--)
{
// ...
}
WindowHandle
WindowIsVisible
WindowOnDropped
int WindowOnDropped()
Returns window index where expert, custom 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 from 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);
}
WindowPriceMax
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();
WindowPriceMin
WindowPriceOnDropped
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);
}
WindowRedraw
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();
WindowScreenShot
bool string filename, int size_x, int size_y, int start_bar=-1, int
WindowScreenShot( 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 - Screen shot width in pixels.
size_y - Screen shot height in pixels.
start_bar - 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.
chart_scale - 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
current chart scale will be used.
chart_mode - 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();
}
WindowTimeOnDropped
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);
}
WindowsTotal
int WindowsTotal()
Returns count of indicator windows on the chart (including main chart).
Sample:
Print("Windows count = ", WindowsTotal());
WindowXOnDropped
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());
WindowYOnDropped
int WindowYOnDropped()
Returns the value at Y 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 WindowXOnDropped(), WindowPriceOnDropped(), WindowOnDropped()
Sample:
Print"Expert was attached to the window in the point x=",WindowXOnDropped(),"
y=",WindowYOnDropped());
Obsolete functions
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 names can be used since the compiler will accept them in
a proper way. However, we strongly recommend to use the new names.