MQL4 Documentation
MQL4 Documentation
MQL4 REFERENCE
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.
1
BASICS
SYNTAX
• no address arithmetic;
• no operator do ... while;
• no operator goto ...;
• no operation of [condition]?[expression 1]:[expression 2];
• no compound data types (structures);
• complex assignments are impossible; for example, val1=val2=0; arr[i++]=val;
cond=(cnt=OrdersTotal)>0; etc.;
• calculation of a logical expression is always completed, never early terminated.
COMMENTS
Multiline comments start with /* symbols and end with */ symbols. Such comments cannot be
nested. Single comments start with // symbols, end with the symbol of a new line and can be
nested into multiline comments. Comments are allowed where blank spaces are possible and
tolerate any number of spaces.
Examples:
// single comment
/* multi-
line // nested single comment
comment
*/
IDENTIFIERS
Identifiers are used as names of variables, functions, and data types. The length of an identifier
cannot exceed 31 character.
Symbols you can use: numbers from 0 to 9, Latin capital and small letters a to z, A to Z
(recognized as different symbols), the symbol of underlining (_). The first symbol cannot be a
number. The identifier must not coincide with any reserved word.
Examples:
2
RESERVED WORDS
The identifiers listed below are fixed reserved words. A certain action is assigned to each of
them, and they cannot be used for other purposes:
DATA TYPES
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.
3
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:
Type casting is applied to not only constants, but also variables of corresponding types.
INTEGER CONSTANTS
Examples:
Examples:
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.
4
LITERAL CONSTANTS
If a character different from those listed above follows the reverse slash, the result will not be
defined:
int a = 'A';
int b = '$';
int c = '©'; // code 0xA9
int d = '\xAE'; // symbol code ®
Its internal representation is a long 4-byte integer number. Literal constants can assume values
from 0 to 255. If the constant exceeds this given range, the result is undefined.
BOOLEAN CONSTANTS
Boolean constants may have the value of true or false, numeric representation of them is 1 or 0,
respectively. True or TRUE, False or FALSE can be used, as well.
Examples:
bool a = true;
bool b = false;
bool c = 1;
Its internal representation is a long 4-byte integer number. Boolean constants can assume the
values of 0 or 1.
Floating-point 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;
5
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
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:
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.
Examples:
// symbol constants
C'128,128,128' // gray
C'0x00,0x00,0xFF' // blue
// named color
Red
Yellow
Black
// integer-valued representation
6
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:
Its internal representation is a long integer number of 4 bytes. The value represents the amount
of seconds elapse from 00:00 Jan 1, 1970.
Some characters and character sequences are of a special importance. These are so-called
operation symbols, for example:
+ - * / % symbols of arithmetic operations
&& || symbols of logic operations
= += *= symbols of assignment operations
Operation symbols are used in expressions and have sense when appopriate operands are given
them
Punctuation marks are emphasized, as well. These are parentheses, braces, comma, colon, and
semicolon.
Operation symbols, punctuation marks, spaces are used to separate 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) /
7
(w + 2) + 127;
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--;
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.
8
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;
BOOLEAN OPERATIONS
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;
9
The binary-coded representation of x is shifted to the right by y digits, the freed digits on the
right will be filled with zeroes.
x = x << y;
Bitwise operation AND of binary-coded x and y representations. The value of the expression
contains 1 (TRUE) in all digits where both x and y do not contain zero; and it contains 0
(FALSE) in all other digits.
b = x | y;
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:
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.
10
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:
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.
11
*= Assignment multiplication
/= Assignment division
%= Assignment module
>>= Assignment right shift
<<= Assignment left shift
&= Assignment bitwise AND
|= Assignment bitwise OR
^= Assignment exclusive OR
, Comma From left to right
Parentheses that have higher priority are applied to change the execution order of the operations.
Attention: Priority of performing operations in MQL4 differs to some extent from that
conventional in the C language.
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;
12
x=3;
y=x=3; // error
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:
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:
13
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:
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:
14
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 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");
15
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 ','.
16
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:
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:
17
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:
18
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.
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;
19
Additional types:
Additional data types make sense only at the declaration of input parameters for their more
convenient representation in the properties window.
Example:
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);
}
20
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:
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:
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:
21
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:
22
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:
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.
23
EXTERNAL FUNCTIONS DEFINITION
The type of external functions defined in another component of a program must be explicitly
described. The absence of such a definition may result in errors during the compilation, linkage,
or execution of the program. While describing an external object, the keyword of #import must
be used with the reference to the module.
#import "user32.dll"
int MessageBoxA(int hWnd ,string szText,string szCaption,int
nType);
int SendMessageA(int hWnd,int Msg,int wParam,int lParam);
#import "lib.ex4"
double round(double value);
#import
Import can be used to easily describe functions called from external DLLs or compiled EX4
libraries.
Pointers to variables can be passed to imported dll functions. Data of the string type are passed
as a pointer to the corresponding memory block (one should keep in mind that internal
representation of string data consists of two parts: the memory block length and the memory
block pointer). If there is a need to pass data of the int or double type, then the one-dimensional
array of the corresponding type should be passed by reference as a parameter.
Example:
#import "some_lib.dll"
void PassIntegerByref(int& OneInt[]);
#import
int start()
{
int array[1];
//...
PassIntegerByref(array);
Print(array[0]);
//...
}
PREPROCESSOR
Preprocessor is a special subsystem of MQL4 compiler that is intended for preparation of the
program source code immediately before the program is compiled.
Preprocessor allows enhancement of the source code readability. The code can be structured by
including of specific files containing source codes of MQL4 programs. The possibility to assign
mnemonic names to specific constants contributes to enhancement of the code readability.
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.
24
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.
25
indicator_styleN int style of the line N, where N lies between 1 and 8
predefined level N for separate window custom
indicator_levelN double
indicator, where N lies between 1 and 8
indicator_levelcolor color level line color
indicator_levelwidth int level line width
indicator_levelstyle int level line style
before script run message box with confirmation
show_confirm void
appears
before script run its property sheet appears; disables
show_inputs void
show_confirm property
Examples:
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.
26
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.
27
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:
28
TRADE OPERATIONS
Operation type for the OrderSend() function. It can be any of the following values:
PRICE CONSTANTS
MARKETINFO
29
predefined variable Ask
Point size in the quote currency. For
MODE_POINT 11 the current symbol, it is stored in the
predefined variable Point
Count of digits after decimal point in
the symbol prices. For the current
MODE_DIGITS 12
symbol, it is stored in the predefined
variable Digits
MODE_SPREAD 13 Spread value in points.
MODE_STOPLEVEL 14 Stop level in points.
MODE_LOTSIZE 15 Lot size in the base currency.
MODE_TICKVALUE 16 Tick value in the deposit currency.
MODE_TICKSIZE 17 Tick size in points.
MODE_SWAPLONG 18 Swap of the long position.
MODE_SWAPSHORT 19 Swap of the short position.
Market starting date (usually used for
MODE_STARTING 20
futures).
Market expiration date (usually used
MODE_EXPIRATION 21
for futures).
MODE_TRADEALLOWED 22 Trade is allowed for the symbol.
MODE_MINLOT 23 Minimum permitted amount of a lot.
MODE_LOTSTEP 24 Step for changing lots.
MODE_MAXLOT 25 Maximum permitted amount of a lot.
Swap calculation method. 0 - in
points; 1 - in the symbol base
MODE_SWAPTYPE 26
currency; 2 - by interest; 3 - in the
margin currency.
Profit calculation mode. 0 - Forex; 1 -
MODE_PROFITCALCMODE 27
CFD; 2 - Futures.
Margin calculation mode. 0 - Forex; 1
MODE_MARGINCALCMODE 28 - CFD; 2 - Futures; 3 - CFD for
indices.
MODE_MARGININIT 29 Initial margin requirements for 1 lot.
Margin to maintain open positions
MODE_MARGINMAINTENANCE 30
calculated for 1 lot.
MODE_MARGINHEDGED 31 Hedged margin calculated for 1 lot.
Free margin required to open 1 lot for
MODE_MARGINREQUIRED 32
buying.
Order freeze level in points. If the
MODE_FREEZELEVEL 33
execution price lies within the range
30
defined by the freeze level, the order
cannot be modified, cancelled or
closed.
DRAWING STYLES
Drawing style. Valid when width=1. It can be any of the following values:
ARROW CODES
Predefined Arrow codes enumeration. Arrows code constants. It can be one of the
following values:
31
Special Arrow codes that exactly points to price and time. It can be one of the following
values:
WINGDINGS
32
WEB COLORS
INDICATOR LINES
33
Constant Value Description
MODE_UPPER 1 Upper line.
MODE_LOWER 2 Lower line.
34
IDIGNORE 5 Ignore button was selected.
IDYES 6 Yes button was selected.
IDNO 7 No button was selected.
IDTRYAGAIN 10 Try Again button was selected.
IDCONTINUE 11 Continue button was selected.
MESSAGEBOX
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.
To display an icon in the message box, specify one of the following values.
35
MB_ICONEXCLAMATION, An exclamation-point icon appears in
0x00000030
MB_ICONWARNING the message box.
An icon consisting of a lowercase
MB_ICONINFORMATION,
0x00000040 letter i in a circle appears in the
MB_ICONASTERISK
message box.
MessageBox() function behavior flags are defined in the WinUser32.mqh file, this is
why this heading file must be included to programs through #include
<WinUser32.mqh>. Not all possible flags are listed here. For more details, please refer
to Win32 API description.
OBJECT TYPES
36
Gann fan. Uses 2 coordinate, but price part of
OBJ_GANNFAN 8
second coordinate ignored.
Gann grid. Uses 2 coordinate, but price part of
OBJ_GANNGRID 9
second coordinate ignored.
OBJ_FIBO 10 Fibonacci retracement. Uses 2 coordinates.
OBJ_FIBOTIMES 11 Fibonacci time zones. Uses 2 coordinates.
OBJ_FIBOFAN 12 Fibonacci fan. Uses 2 coordinates.
OBJ_FIBOARC 13 Fibonacci arcs. Uses 2 coordinates.
OBJ_EXPANSION 14 Fibonacci expansions. Uses 3 coordinates.
OBJ_FIBOCHANNEL 15 Fibonacci channel. Uses 3 coordinates.
OBJ_RECTANGLE 16 Rectangle. Uses 2 coordinates.
OBJ_TRIANGLE 17 Triangle. Uses 3 coordinates.
OBJ_ELLIPSE 18 Ellipse. Uses 2 coordinates.
OBJ_PITCHFORK 19 Andrews pitchfork. Uses 3 coordinates.
OBJ_CYCLES 20 Cycles. Uses 2 coordinates.
OBJ_TEXT 21 Text. Uses 1 coordinate.
OBJ_ARROW 22 Arrows. Uses 1 coordinate.
OBJ_LABEL 23 Text label. Uses 1 coordinate in pixels.
OBJECT PROPERTIES
Object value index used with ObjectGet() and ObjectSet() functions. It can be any of the
following values:
37
STYLE_DASH, STYLE_DOT,
STYLE_DASHDOT,
STYLE_DASHDOTDOT
constants to set/get object line
style.
Integer value to set/get object line
OBJPROP_WIDTH 8 int
width. Can be from 1 to 5.
Boolean value to set/get
OBJPROP_BACK 9 bool background drawing flag for
object.
Boolean value to set/get ray flag of
OBJPROP_RAY 10 bool
object.
Boolean value to set/get ellipse flag
OBJPROP_ELLIPSE 11 bool
for fibo arcs.
Double value to set/get scale object
OBJPROP_SCALE 12 double
property.
Double value to set/get angle object
OBJPROP_ANGLE 13 double
property in degrees.
Integer value or arrow enumeration
OBJPROP_ARROWCODE 14 int to set/get arrow code object
property.
Value can be one or combination
(bitwise addition) of object
OBJPROP_TIMEFRAMES 15 int
visibility constants to set/get
timeframe object property.
Double value to set/get deviation
OBJPROP_DEVIATION 16 double property for Standard deviation
objects.
Integer value to set/get font size for
OBJPROP_FONTSIZE 100 int
text objects.
Integer value to set/get anchor
OBJPROP_CORNER 101 int corner property for label objects.
Must be from 0-3.
Integer value to set/get anchor X
OBJPROP_XDISTANCE 102 int
distance object property in pixels.
Integer value is to set/get anchor Y
OBJPROP_YDISTANCE 103 int
distance object property in pixels.
Integer value to set/get Fibonacci
OBJPROP_FIBOLEVELS 200 int object level count. Can be from 0 to
32.
Color value to set/get object level
OBJPROP_LEVELCOLOR 201 color
line color.
OBJPROP_LEVELSTYLE 202 int Value is one of STYLE_SOLID,
38
STYLE_DASH, STYLE_DOT,
STYLE_DASHDOT,
STYLE_DASHDOTDOT
constants to set/get object level line
style.
Integer value to set/get object level
OBJPROP_LEVELWIDTH 203 int
line width. Can be from 1 to 5.
Integer value to set/get the value of
Fibonacci object level with index n.
OBJPROP_FIRSTLEVEL+n 210+n int
Index n can be from 0 (number of
levels -1), but not larger than 31.
OBJECT VISIBILITY
39
REASON_CHARTCHANGE 3 symbol or timeframe changed on the chart.
REASON_CHARTCLOSE 4 Chart closed.
REASON_PARAMETERS 5 Inputs parameters was changed by user.
REASON_ACCOUNT 6 Other account activated.
SPECIAL CONSTANTS
Special constants used to indicate parameters and variables states. It can be one of the
following values:
ERROR CODES
The GetLastError() function return codes. Error code constants defined at stderror.mqh
file. To print text messages use ErrorDescription() function defined at stdlib.mqh file.
#include <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));
}
40
Old version of the client
ERR_OLD_VERSION 5
terminal.
No connection with trade
ERR_NO_CONNECTION 6
server.
ERR_NOT_ENOUGH_RIGHTS 7 Not enough rights.
ERR_TOO_FREQUENT_REQUESTS 8 Too frequent requests.
Malfunctional trade
ERR_MALFUNCTIONAL_TRADE 9
operation.
ERR_ACCOUNT_DISABLED 64 Account disabled.
ERR_INVALID_ACCOUNT 65 Invalid account.
ERR_TRADE_TIMEOUT 128 Trade timeout.
ERR_INVALID_PRICE 129 Invalid price.
ERR_INVALID_STOPS 130 Invalid stops.
ERR_INVALID_TRADE_VOLUME 131 Invalid trade volume.
ERR_MARKET_CLOSED 132 Market is closed.
ERR_TRADE_DISABLED 133 Trade is disabled.
ERR_NOT_ENOUGH_MONEY 134 Not enough money.
ERR_PRICE_CHANGED 135 Price changed.
ERR_OFF_QUOTES 136 Off quotes.
ERR_BROKER_BUSY 137 Broker is busy.
ERR_REQUOTE 138 Requote.
ERR_ORDER_LOCKED 139 Order is locked.
Long positions only
ERR_LONG_POSITIONS_ONLY_ALLOWED 140
allowed.
ERR_TOO_MANY_REQUESTS 141 Too many requests.
Modification denied
ERR_TRADE_MODIFY_DENIED 145 because order too close to
market.
ERR_TRADE_CONTEXT_BUSY 146 Trade context is busy.
Expirations are denied by
ERR_TRADE_EXPIRATION_DENIED 147
broker.
The amount of open and
pending orders has
ERR_TRADE_TOO_MANY_ORDERS 148
reached the limit set by
the broker.
An attempt to open a
position opposite to the
ERR_TRADE_HEDGE_PROHIBITED 149
existing one when
hedging is disabled.
41
An attempt to close a
ERR_TRADE_PROHIBITED_BY_FIFO 150 position contravening the
FIFO rule.
42
not allowed.
Not enough memory for
ERR_NO_MEMORY_FOR_RETURNED_STR 4021 temp string returned
from function.
System is busy (never
ERR_SYSTEM_BUSY 4022
generated error).
Invalid function
ERR_INVALID_FUNCTION_PARAMSCNT 4050
parameters count.
Invalid function
ERR_INVALID_FUNCTION_PARAMVALUE 4051
parameter value.
String function internal
ERR_STRING_FUNCTION_INTERNAL 4052
error.
ERR_SOME_ARRAY_ERROR 4053 Some array error.
Incorrect series array
ERR_INCORRECT_SERIESARRAY_USING 4054
using.
ERR_CUSTOM_INDICATOR_ERROR 4055 Custom indicator error.
ERR_INCOMPATIBLE_ARRAYS 4056 Arrays are incompatible.
Global variables
ERR_GLOBAL_VARIABLES_PROCESSING 4057
processing error.
Global variable not
ERR_GLOBAL_VARIABLE_NOT_FOUND 4058
found.
Function is not allowed
ERR_FUNC_NOT_ALLOWED_IN_TESTING 4059
in testing mode.
Function is not
ERR_FUNCTION_NOT_CONFIRMED 4060
confirmed.
ERR_SEND_MAIL_ERROR 4061 Send mail error.
String parameter
ERR_STRING_PARAMETER_EXPECTED 4062
expected.
Integer parameter
ERR_INTEGER_PARAMETER_EXPECTED 4063
expected.
Double parameter
ERR_DOUBLE_PARAMETER_EXPECTED 4064
expected.
Array as parameter
ERR_ARRAY_AS_PARAMETER_EXPECTED 4065
expected.
Requested history data in
ERR_HISTORY_WILL_UPDATED 4066
updating state.
Some error in trading
ERR_TRADE_ERROR 4067
function.
ERR_END_OF_FILE 4099 End of file.
ERR_SOME_FILE_ERROR 4100 Some file error.
43
ERR_WRONG_FILE_NAME 4101 Wrong file name.
ERR_TOO_MANY_OPENED_FILES 4102 Too many opened files.
ERR_CANNOT_OPEN_FILE 4103 Cannot open file.
Incompatible access to a
ERR_INCOMPATIBLE_FILEACCESS 4104
file.
ERR_NO_ORDER_SELECTED 4105 No order selected.
ERR_UNKNOWN_SYMBOL 4106 Unknown symbol.
ERR_INVALID_PRICE_PARAM 4107 Invalid price.
ERR_INVALID_TICKET 4108 Invalid ticket.
Trade is not allowed.
Enable checkbox "Allow
ERR_TRADE_NOT_ALLOWED 4109
live trading" in the expert
properties.
Longs are not allowed.
ERR_LONGS_NOT_ALLOWED 4110 Check the expert
properties.
Shorts are not allowed.
ERR_SHORTS_NOT_ALLOWED 4111 Check the expert
properties.
ERR_OBJECT_ALREADY_EXISTS 4200 Object exists already.
Unknown object
ERR_UNKNOWN_OBJECT_PROPERTY 4201
property.
ERR_OBJECT_DOES_NOT_EXIST 4202 Object does not exist.
ERR_UNKNOWN_OBJECT_TYPE 4203 Unknown object type.
ERR_NO_OBJECT_NAME 4204 No object name.
ERR_OBJECT_COORDINATES_ERROR 4205 Object coordinates error.
ERR_NO_SPECIFIED_SUBWINDOW 4206 No specified subwindow.
Some error in object
ERR_SOME_OBJECT_ERROR 4207
function.
44
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);
45
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.
46
{
price=High[k];
if(max<price) max=price;
k--;
}
HighesBuffer[i]=max;
i--;
}
//----
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.
47
double open = Open[i];
double close = Close[i];
AccumulationBuffer[i] = (close-low) - (high-close);
if(AccumulationBuffer[i] != 0)
{
double diff = high - low;
if(0==diff)
AccumulationBuffer[i] = 0;
else
{
AccumulationBuffer[i] /= diff;
AccumulationBuffer[i] *= Volume[i];
}
}
if(i<Bars-1) AccumulationBuffer[i] += AccumulationBuffer[i+1];
i--;
}
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.
48
PBuffer[i] = P;
S1Buffer[i] = S1;
R1Buffer[i] = R1;
S2Buffer[i] = S2;
R2Buffer[i] = R2;
S3Buffer[i] = S3;
R3Buffer[i] = R3;
}
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.
49
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
50
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.
To import functions during execution of an mql4 program, the so-called late binding is
used. This means that, until the imported function is called, the corresponding module
(ex4 or dll) will not be loaded. MQL4 and DLL libraries are executed in the calling
module thread.
It is not recommended to use a fully qualified name of the module to be loaded like
Drive:\Directory\FileName.Ext. MQL4 libraries are loaded from the
terminal_dir\experts\libraries folder. If the library has not been found, there will be
made an attempt to load the library from the terminal_dir\experts folder.
System libraries (DLLs) are loaded by the rules of the operation system. If the library
has already been loaded (by another 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
51
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.
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.
52
Constant Value Description
At calling of an internal
function, a wrong
ERR_WRONG_FUNCTION_POINTER 4001
function pointer has been
detected
At calling of an internal
function, it is impossible
ERR_NO_MEMORY_FOR_CALL_STACK 4003
to reallocate memory for
the function calls stack
The data stack is
ERR_RECURSIVE_STACK_OVERFLOW 4004 overflowed at the
recursive function call
At calling of an internal
function, it is impossible
ERR_NO_MEMORY_FOR_PARAM_STRING 4006 to allocate memory for
passing the string as a
function parameter
It is impossible to allocate
ERR_NO_MEMORY_FOR_TEMP_STRING 4007 the temporary buffer for
string operations
At assignment, it is
impossible to reallocate
ERR_NO_MEMORY_FOR_ARRAYSTRING 4010
memory for a string in an
array
At assignment, too long
resulting string to be
placed into the service
ERR_TOO_LONG_STRING 4011
buffer (no possibility to
reallocate for the service
buffer)
Dividing by 0 when
ERR_REMAINDER_FROM_ZERO_DIVIDE 4012 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.
53
Constant Value Description
At calling of an imported
ERR_CANNOT_LOAD_LIBRARY 4018 function, loading error of
dll or ex4 library occurred
At calling of an imported
function, it was found out
ERR_CANNOT_CALL_FUNCTION 4019 that dll or ex4 library did
not contain the called
function
At calling of an imported
dll function, it was found
ERR_DLL_CALLS_NOT_ALLOWED 4017
out that dll imports were
not allowed
At calling of an ex4
function, it was found out
ERR_EXTERNAL_CALLS_NOT_ALLOWED 4020
that external ex4 imports
were not allowed
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.
54
Constant Value Description
At calling of an internal
ERR_WRONG_FUNCTION_POINTER 4001 function, a wrong function
pointer has been detected
ERR_UNKNOWN_COMMAND 4014 Unknown instruction
ERR_NOT_INITIALIZED_ARRAY 4016 Not initialized array
Invalid parameters count
ERR_INVALID_FUNCTION_PARAMSCNT 4050
passed into built-in function
String function internal
ERR_STRING_FUNCTION_INTERNAL 4052
error
Trade function internal
ERR_TRADE_ERROR 4067
error
Object function internal
ERR_SOME_OBJECT_ERROR 4207
error
There are some functions that always change the last_error variable value.
55
(4051), ERR_INVALID_TICKET (4108),
ERR_UNKNOWN_SYMBOL (4106),
ERR_TRADE_NOT_ALLOWED (4109), code
returned by trade server
ERR_CUSTOM_INDICATOR_ERROR (4055),
ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_INVALID_TICKET (4108),
OrderDelete
ERR_UNKNOWN_SYMBOL (4106),
ERR_TRADE_NOT_ALLOWED (4109), code
returned by trade server
ERR_CUSTOM_INDICATOR_ERROR (4055),
ERR_INTEGER_PARAMETER_EXPECTED (4063),
ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_INVALID_PRICE_PARAM (4107),
OrderModify
ERR_INVALID_TICKET (4108),
ERR_UNKNOWN_SYMBOL (4106),
ERR_TRADE_NOT_ALLOWED (4109), code
returned by trade server
GetLastError ERR_NO_ERROR (0)
Some functions change value of the last_error variable only if an error occurs.
56
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
ERR_ARRAY_AS_PARAMETER_EXPECTED
ArrayDimension
(4065), ERR_SOME_ARRAY_ERROR (4053)
ERR_ARRAY_AS_PARAMETER_EXPECTED
ArrayGetAsSeries
(4065), ERR_SOME_ARRAY_ERROR (4053)
ERR_ARRAY_AS_PARAMETER_EXPECTED
(4065), ERR_SOME_ARRAY_ERROR (4053),
ArrayInitialize
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
ERR_ARRAY_AS_PARAMETER_EXPECTED
ArrayIsSeries
(4065), ERR_SOME_ARRAY_ERROR (4053)
ERR_ARRAY_AS_PARAMETER_EXPECTED
(4065), ERR_SOME_ARRAY_ERROR (4053),
ArrayMaximum
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
ERR_ARRAY_AS_PARAMETER_EXPECTED
(4065), ERR_SOME_ARRAY_ERROR (4053),
ArrayMinimum
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
ERR_ARRAY_AS_PARAMETER_EXPECTED
(4065), ERR_SOME_ARRAY_ERROR (4053),
ERR_INTEGER_PARAMETER_EXPECTED
ArrayRange
(4063),
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
ERR_ARRAY_AS_PARAMETER_EXPECTED
(4065), ERR_SOME_ARRAY_ERROR (4053),
ArrayResize
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
ERR_ARRAY_AS_PARAMETER_EXPECTED
ArraySetAsSeries
(4065), ERR_SOME_ARRAY_ERROR (4053)
ERR_ARRAY_AS_PARAMETER_EXPECTED
ArraySize
(4065), ERR_SOME_ARRAY_ERROR (4053)
ERR_ARRAY_AS_PARAMETER_EXPECTED
(4065), ERR_SOME_ARRAY_ERROR (4053),
ERR_INCORRECT_SERIESARRAY_USING
ArraySort
(4054),
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
FileClose
(4051)
ERR_WRONG_FILE_NAME (4101),
FileDelete
ERR_SOME_FILE_ERROR (4100)
57
ERR_INVALID_FUNCTION_PARAMVALUE
FileFlush
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
FileIsEnding
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
FileIsLineEnding
(4051)
ERR_TOO_MANY_OPENED_FILES (4102),
ERR_WRONG_FILE_NAME (4101),
FileOpen ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_SOME_FILE_ERROR (4100),
ERR_CANNOT_OPEN_FILE (4103)
ERR_TOO_MANY_OPENED_FILES (4102),
ERR_WRONG_FILE_NAME (4101),
FileOpenHistory ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_SOME_FILE_ERROR (4100),
ERR_CANNOT_OPEN_FILE (4103)
ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_INCOMPATIBLE_FILEACCESS
FileReadArray (4104), ERR_SOME_ARRAY_ERROR (4053),
ERR_SOME_FILE_ERROR (4100),
ERR_END_OF_FILE (4099)
ERR_INVALID_FUNCTION_PARAMVALUE
FileReadDouble (4051), ERR_INCOMPATIBLE_FILEACCESS
(4104), ERR_END_OF_FILE (4099)
ERR_INVALID_FUNCTION_PARAMVALUE
FileReadInteger (4051), ERR_INCOMPATIBLE_FILEACCESS
(4104), ERR_END_OF_FILE (4099)
ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_INCOMPATIBLE_FILEACCESS
FileReadNumber
(4104), ERR_SOME_FILE_ERROR (4100),
ERR_END_OF_FILE (4099)
ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_INCOMPATIBLE_FILEACCESS
FileReadString (4104), ERR_SOME_FILE_ERROR (4100),
ERR_TOO_LONG_STRING (4011),
ERR_END_OF_FILE (4099)
ERR_INVALID_FUNCTION_PARAMVALUE
FileSeek
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
FileSize
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
FileTell
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
FileWrite
(4051), ERR_SOME_FILE_ERROR (4100)
58
ERR_INVALID_FUNCTION_PARAMVALUE
FileWriteDouble (4051), ERR_INCOMPATIBLE_FILEACCESS
(4104), ERR_SOME_FILE_ERROR (4100)
ERR_INVALID_FUNCTION_PARAMVALUE
FileWriteInteger (4051), ERR_INCOMPATIBLE_FILEACCESS
(4104), ERR_SOME_FILE_ERROR (4100)
ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_INCOMPATIBLE_FILEACCESS
FileWriteString (4104), ERR_SOME_FILE_ERROR (4100),
ERR_STRING_PARAMETER_EXPECTED
(4062)
ERR_INVALID_FUNCTION_PARAMVALUE
FileWriteArray (4051), ERR_INCOMPATIBLE_FILEACCESS
(4104), ERR_SOME_FILE_ERROR (4100),
ERR_STRING_PARAMETER_EXPECTED
GlobalVariableCheck
(4062)
ERR_STRING_PARAMETER_EXPECTED
(4062),
GlobalVariableDel
ERR_GLOBAL_VARIABLES_PROCESSING
(4057)
ERR_STRING_PARAMETER_EXPECTED
(4062),
GlobalVariableGet
ERR_GLOBAL_VARIABLE_NOT_FOUND
(4058)
ERR_STRING_PARAMETER_EXPECTED
(4062),
GlobalVariablesDeleteAll
ERR_GLOBAL_VARIABLES_PROCESSING
(4057)
ERR_STRING_PARAMETER_EXPECTED
(4062),
ERR_GLOBAL_VARIABLES_PROCESSING
GlobalVariableSet
(4057),
ERR_GLOBAL_VARIABLE_NOT_FOUND
(4058)
ERR_STRING_PARAMETER_EXPECTED
(4062),
GlobalVariableSetOnCondition
ERR_GLOBAL_VARIABLE_NOT_FOUND
(4058)
ERR_STRING_PARAMETER_EXPECTED
(4062),
iCustom
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
technical indicators, series
ERR_HISTORY_WILL_UPDATED (4066)
access functions
technical indicators OnArray ERR_ARRAY_AS_PARAMETER_EXPECTED
59
(4065), ERR_SOME_ARRAY_ERROR (4053)
ERR_INVALID_FUNCTION_PARAMVALUE
IndicatorBuffers
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
IndicatorDigits
(4051)
ERR_STRING_PARAMETER_EXPECTED
(4062),
IndicatorShortName
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
ERR_STRING_PARAMETER_EXPECTED
(4062),
ERR_FUNC_NOT_ALLOWED_IN_TESTING
MarketInfo
(4059), ERR_UNKNOWN_SYMBOL (4106),
ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
MathArccos
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
MathArcsin
(4051)
MathMod ERR_ZERO_DIVIDE (4013)
ERR_INVALID_FUNCTION_PARAMVALUE
MathSqrt
(4051)
ERR_FUNC_NOT_ALLOWED_IN_TESTING
(4059), ERR_CUSTOM_INDICATOR_ERROR
MessageBox (4055),
ERR_STRING_PARAMETER_EXPECTED
(4062)
ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NO_OBJECT_NAME (4204),
ERR_UNKNOWN_OBJECT_TYPE (4203),
ObjectCreate ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_OBJECT_ALREADY_EXISTS
(4200), ERR_NO_SPECIFIED_SUBWINDOW
(4206)
ERR_STRING_PARAMETER_EXPECTED
ObjectDelete (4062), ERR_NO_OBJECT_NAME (4204),
ERR_OBJECT_DOES_NOT_EXIST (4202)
ERR_STRING_PARAMETER_EXPECTED
ObjectDescription (4062), ERR_NO_OBJECT_NAME (4204),
ERR_OBJECT_DOES_NOT_EXIST (4202)
ERR_STRING_PARAMETER_EXPECTED
ObjectFind
(4062), ERR_NO_OBJECT_NAME (4204)
ERR_STRING_PARAMETER_EXPECTED
ObjectGet
(4062), ERR_NO_OBJECT_NAME (4204),
60
ERR_OBJECT_DOES_NOT_EXIST (4202),
ERR_UNKNOWN_OBJECT_PROPERTY (4201)
ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NO_OBJECT_NAME (4204),
ERR_INVALID_FUNCTION_PARAMVALUE
ObjectGetFiboDescription (4051), ERR_OBJECT_DOES_NOT_EXIST
(4202), ERR_UNKNOWN_OBJECT_TYPE
(4203),
ERR_UNKNOWN_OBJECT_PROPERTY (4201)
ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NO_OBJECT_NAME (4204),
ObjectGetShiftByValue
ERR_OBJECT_DOES_NOT_EXIST (4202),
ERR_OBJECT_COORDINATES_ERROR (4205)
ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NO_OBJECT_NAME (4204),
ObjectGetValueByShift
ERR_OBJECT_DOES_NOT_EXIST (4202),
ERR_OBJECT_COORDINATES_ERROR (4205)
ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NO_OBJECT_NAME (4204),
ObjectMove ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_OBJECT_DOES_NOT_EXIST
(4202)
ERR_INVALID_FUNCTION_PARAMVALUE
(4051),
ObjectName
ERR_ARRAY_INDEX_OUT_OF_RANGE
(4002)
ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NO_OBJECT_NAME (4204),
ObjectSet
ERR_OBJECT_DOES_NOT_EXIST (4202),
ERR_UNKNOWN_OBJECT_PROPERTY (4201)
ERR_STRING_PARAMETER_EXPECTED
ObjectSetText (4062), ERR_NO_OBJECT_NAME (4204),
ERR_OBJECT_DOES_NOT_EXIST (4202)
ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NO_OBJECT_NAME (4204),
ERR_INVALID_FUNCTION_PARAMVALUE
(4051),
ObjectSetFiboDescription ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_OBJECT_DOES_NOT_EXIST
(4202), ERR_UNKNOWN_OBJECT_TYPE
(4203),
ERR_UNKNOWN_OBJECT_PROPERTY (4201)
ERR_STRING_PARAMETER_EXPECTED
ObjectType (4062), ERR_NO_OBJECT_NAME (4204),
ERR_OBJECT_DOES_NOT_EXIST (4202)
61
OrderClosePrice ERR_NO_ORDER_SELECTED (4105)
OrderCloseTime ERR_NO_ORDER_SELECTED (4105)
OrderComment ERR_NO_ORDER_SELECTED (4105)
OrderCommission ERR_NO_ORDER_SELECTED (4105)
OrderExpiration ERR_NO_ORDER_SELECTED (4105)
OrderLots ERR_NO_ORDER_SELECTED (4105)
OrderMagicNumber ERR_NO_ORDER_SELECTED (4105)
OrderOpenPrice ERR_NO_ORDER_SELECTED (4105)
OrderOpenTime ERR_NO_ORDER_SELECTED (4105)
OrderPrint ERR_NO_ORDER_SELECTED (4105)
OrderProfit ERR_NO_ORDER_SELECTED (4105)
OrderStopLoss ERR_NO_ORDER_SELECTED (4105)
OrderSwap ERR_NO_ORDER_SELECTED (4105)
OrderSymbol ERR_NO_ORDER_SELECTED (4105)
OrderTakeProfit ERR_NO_ORDER_SELECTED (4105)
OrderTicket ERR_NO_ORDER_SELECTED (4105)
OrderType ERR_NO_ORDER_SELECTED (4105)
PlaySound ERR_WRONG_FILE_NAME (4101)
ERR_FUNC_NOT_ALLOWED_IN_TESTING
(4059), ERR_CUSTOM_INDICATOR_ERROR
SendFTP (4055),
ERR_STRING_PARAMETER_EXPECTED
(4062)
ERR_FUNC_NOT_ALLOWED_IN_TESTING
(4059),
SendMail ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_FUNCTION_NOT_CONFIRMED
(4060), ERR_SEND_MAIL_ERROR (4061)
ERR_INVALID_FUNCTION_PARAMVALUE
SetIndexArrow
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
(4051),
SetIndexBuffer ERR_INCORRECT_SERIESARRAY_USING
(4054), ERR_INCOMPATIBLE_ARRAYS
(4056)
ERR_INVALID_FUNCTION_PARAMVALUE
SetIndexDrawBegin
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
SetIndexEmptyValue
(4051)
62
ERR_INVALID_FUNCTION_PARAMVALUE
(4051),
SetIndexLabel
ERR_STRING_PARAMETER_EXPECTED
(4062)
ERR_INVALID_FUNCTION_PARAMVALUE
SetIndexShift
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
SetIndexStyle
(4051)
ERR_INVALID_FUNCTION_PARAMVALUE
SetLevelValue
(4051)
Sleep ERR_CUSTOM_INDICATOR_ERROR (4055)
ERR_STRING_PARAMETER_EXPECTED
StringFind
(4062)
ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NOT_INITIALIZED_STRING
StringGetChar (4008),
ERR_ARRAY_INDEX_OUT_OF_RANGE
(4002)
ERR_STRING_PARAMETER_EXPECTED
StringLen
(4062)
ERR_STRING_PARAMETER_EXPECTED
(4062),
ERR_INVALID_FUNCTION_PARAMVALUE
StringSetChar (4051), ERR_NOT_INITIALIZED_STRING
(4008), ERR_TOO_LONG_STRING (4011),
ERR_ARRAY_INDEX_OUT_OF_RANGE
(4002)
ERR_STRING_PARAMETER_EXPECTED
StringSubstr
(4062), ERR_TOO_LONG_STRING (4011)
ERR_STRING_PARAMETER_EXPECTED
StringTrimLeft
(4062)
ERR_STRING_PARAMETER_EXPECTED
StringTrimRight
(4062)
ERR_FUNC_NOT_ALLOWED_IN_TESTING
WindowIsVisible
(4059)
ERR_FUNC_NOT_ALLOWED_IN_TESTING
(4059),
WindowFind ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NOT_INITIALIZED_STRING
(4008)
ERR_FUNC_NOT_ALLOWED_IN_TESTING
(4059),
WindowHandle
ERR_STRING_PARAMETER_EXPECTED
(4062), ERR_NOT_INITIALIZED_STRING
63
(4008)
ERR_WRONG_FILE_NAME (4101),
WindowScreenShot ERR_INVALID_FUNCTION_PARAMVALUE
(4051)
64
ACCOUNT INFORMATION
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());
65
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());
66
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:
67
ARRAY FUNCTIONS
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
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]));
68
ARRAYCOPY
ARRAYCOPYRATES
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:
69
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.
70
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
71
ARRAYISSERIES
ARRAYMAXIMUM
ARRAYMINIMUM
ARRAYRANGE
72
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
73
ARRAYSIZE
ARRAYSORT
74
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"
75
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);
76
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");
77
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
}
//...
}
78
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());
79
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.
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()));
80
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
MESSAGEBOX
81
if(ret==IDNO) return(false);
}
// continue
PLAYSOUND
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
82
Parameters:
filename - File to be sent.
ftp_path - FTP path. If the path has not been specified, the path described in settings
will be used.
Sample:
int lasterror=0;
if(!SendFTP("report.txt"))
lasterror=GetLastError();
SENDMAIL
SLEEP
83
CONVERSION FUNCTIONS
A group of functions that provide conversion of data from one format into another.
CHARTOSTR
DOUBLETOSTR
NORMALIZEDOUBLE
84
STRTODOUBLE
STRTOINTEGER
STRTOTIME
TIMETOSTR
85
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,
86
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
87
//---- "short name" for DataWindow and indicator subwindow
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}
INDICATORSHORTNAME
SETINDEXARROW
88
return(0);
}
SETINDEXBUFFER
SETINDEXDRAWBEGIN
89
SETINDEXEMPTYVALUE
SETINDEXLABEL
90
SetIndexBuffer(2,SpanA_Buffer);
SetIndexDrawBegin(2,Kijun+a_begin-1);
SetIndexShift(2,Kijun);
//---- Up Kumo bounding line does not show in the DataWindow
SetIndexLabel(2,NULL);
SetIndexStyle(5,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(5,SpanA2_Buffer);
SetIndexDrawBegin(5,Kijun+a_begin-1);
SetIndexShift(5,Kijun);
SetIndexLabel(5,"Senkou Span A");
//----
SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_DOT);
SetIndexBuffer(3,SpanB_Buffer);
SetIndexDrawBegin(3,Kijun+Senkou-1);
SetIndexShift(3,Kijun);
//---- Down Kumo bounding line does not show in the DataWindow
SetIndexLabel(3,NULL);
//----
SetIndexStyle(6,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(6,SpanB2_Buffer);
SetIndexDrawBegin(6,Kijun+Senkou-1);
SetIndexShift(6,Kijun);
SetIndexLabel(6,"Senkou Span B");
//----
SetIndexStyle(4,DRAW_LINE);
SetIndexBuffer(4,Chinkou_Buffer);
SetIndexShift(4,-Kijun);
SetIndexLabel(4,"Chinkou Span");
//----
return(0);
}
SETINDEXSHIFT
91
SetIndexBuffer(2,ExtLimeBuffer);
//---- drawing settings
SetIndexStyle(0,DRAW_LINE);
SetIndexStyle(1,DRAW_LINE);
SetIndexStyle(2,DRAW_LINE);
//---- index labels
SetIndexLabel(0,"Gator Jaws");
SetIndexLabel(1,"Gator Teeth");
SetIndexLabel(2,"Gator Lips");
//---- initialization done
return(0);
}
SETINDEXSTYLE
SETLEVELSTYLE
92
SETLEVELVALUE
93
DATE & TIME FUNCTIONS
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).
94
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
95
date - Datetime as number of seconds elapsed since midnight (00:00:00), January 1,
1970.
Sample:
int weekday=TimeDayOfWeek(D'2004.11.2');
// day is 2 - Tuesday
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
96
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);
97
FILE FUNCTIONS
There are three directories (with subdirectories) where working files can be placed:
FILECLOSE
FileDelete
98
FILEFLUSH
FILEISENDING
FILEISLINEENDING
99
return(false);
}
FILEOPEN
FILEOPENHISTORY
100
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
101
FileClose(handle);
}
FILEREADINTEGER
FILEREADNUMBER
FILEREADSTRING
102
length - Amount of characters for reading.
Sample:
int handle;
string str;
handle=FileOpen("filename.csv", FILE_CSV|FILE_READ);
if(handle>0)
{
str=FileReadString(handle);
FileClose(handle);
}
FILESEEK
FILESIZE
103
size=FileSize(handle);
Print("my_table.dat size is ", size, " bytes");
FileClose(handle);
}
FILETELL
FILEWRITE
FILEWRITEARRAY
104
written elementwise, as 8-bytes floating point numbers. Arrays of string type will be
written by strings, the line end character "\r\n" to be added at each string automatically.
Returns the number of written elements or a negative value if an error occurs. To get the
detailed error information, one has to call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
array[] - Array to write.
start - Starting index in the array (the first written element number).
count - Count of elements to be written.
Sample:
int handle;
double BarOpenValues[10];
// copy first ten bars to the array
for(int i=0;i<10; i++)
BarOpenValues[i]=Open[i];
// writing array to the file
handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE);
if(handle>0)
{
FileWriteArray(handle, BarOpenValues, 3, 7); // writing last 7
elements
FileClose(handle);
}
FILEWRITEDOUBLE
105
FILEWRITEINTEGER
FILEWRITESTRING
106
GLOBAL VARIABLES
Global variables of the client terminal should not be mixed up with variables declared in
the global scope of the MQL4 program.
Global variables are kept in the client terminal within 4 weeks since the last access, then
they will be deleted 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
107
//---- continue processing
GLOBALVARIABLENAME
GLOBALVARIABLESET
GLOBALVARIABLESETONCONDITION
108
value - New value.
check_value - Value to be compared to the current global variable value.
Sample:
int init()
{
//---- create global variable
GlobalVariableSet("DATAFILE_SEM",0);
//...
}
int start()
{
//---- try to lock common resource
while(!IsStopped())
{
//---- locking
if(GlobalVariableSetOnCondition("DATAFILE_SEM",1,0)==true)
break;
//---- may the variable be deleted?
if(GetLastError()==ERR_GLOBAL_VARIABLE_NOT_FOUND) return(0);
//---- sleeping
Sleep(500);
}
//---- resource locked
// ... do some work
//---- unlock resource
GlobalVariableSet("DATAFILE_SEM",0);
}
GLOBALVARIABLESDELETEALL
GLOBALVARIABLESTOTAL
int GlobalVariablesTotal()
The function returns the total count of global variables.
Sample:
Print(GlobalVariablesTotal()," global variables detected");
109
MATH & TRIG
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
110
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.
111
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
112
MATHMIN
MATHMOD
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.
113
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
114
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
115
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,
ObjectCreate( datetime 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);
116
OBJECTDELETE
OBJECTDESCRIPTION
OBJECTFIND
117
OBJECTGET
OBJECTGETFIBODESCRIPTION
OBJECTGETSHIFTBYVALUE
118
OBJECTGETVALUEBYSHIFT
OBJECTMOVE
OBJECTNAME
119
OBJECTSDELETEALL
OBJECTSET
120
OBJECTSETFIBODESCRIPTION
OBJECTSETTEXT
OBJECTSTOTAL
121
name=ObjectName(i);
Print(i,"Object name for object #",i," is " + name);
}
OBJECTTYPE
122
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
123
Sample:
int char_code=StringGetChar("abcdefgh", 3);
// char code 'c' is 99
STRINGLEN
STRINGSETCHAR
STRINGSUBSTR
124
STRINGTRIMLEFT
STRINGTRIMRIGHT
125
TECHNICAL 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
126
IALLIGATOR
IADX
double string symbol, int timeframe, int period, int applied_price, int mode,
iADX( 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.
127
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,MO
DE_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.
128
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,
iBands( int applied_price, int mode, int shift)
Calculates the Bollinger bands indicator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate the indicator.
NULL means the current symbol.
timeframe - 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,
iBandsOnArray( int 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
129
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
130
array[] - Array with data.
total - The number of items to be counted.
period - Averaging period for calculation.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
if(iCCIOnArray(ExtBuffer,total,12,0)>iCCI(NULL,0,20,PRICE_TYPICAL, 0))
return(0);
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
131
IENVELOPES
IENVELOPESONARRAY
132
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,
iForce( int shift)
Calculates the Force index and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator.
NULL means current symbol.
timeframe - 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
IGATOR
double string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period,
iGator( int teeth_shift, int lips_period, int lips_shift, int ma_method,
int applied_price, int mode, int shift)
133
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
134
IBWMFI
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
135
if(iMomentumOnArray(mybuffer,100,12,0)>iMomentumOnArray(mubuffer,100,2
0,0)) return(0);
IMFI
IMA
double string symbol, int timeframe, int period, int ma_shift, int ma_method,
iMA( int applied_price, int shift)
Calculates the Moving average indicator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator.
NULL means the current symbol.
timeframe - 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 double array[], int total, int period, int ma_shift, int ma_method,
iMAOnArray( 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
136
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
137
IMACD
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:
138
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
139
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,
iStdDev( int applied_price, int shift)
Calculates the Standard Deviation indicator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator.
NULL means the current symbol.
timeframe - 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
140
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,
iStochastic( int method, int price_field, int mode, int shift)
Calculates the Stochastic oscillator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - 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
141
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.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
if(iWPR(NULL,0,14,0)>iWPR(NULL,0,14,1)) return(0);
142
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
143
Print("shift of bar with open time ",TimeToStr(some_time)," is
",shift);
ICLOSE
IHIGH
IHIGHEST
ILOW
ILOWEST
145
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
146
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));
IVOLUME
147
TRADING FUNCTIONS
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
148
passed to the trading
function, for example,
wrong symbol,
unknown trade operation,
negative slippage, non-
existing ticket number,
etc. The program logic
must be changed.
Trade server is busy. The
attempt can be repeated
ERR_SERVER_BUSY 4 after a rather long period
of time (over several
minutes).
Old version of the client
terminal. The latest
ERR_OLD_VERSION 5 version of the client
terminal must be
installed.
No connection to the
trade server. It is
necessary to make sure
that connection has not
been broken (for example,
ERR_NO_CONNECTION 6
using the IsConnected
function) and repeat the
attempt after a certain
period of time (over 5
seconds).
Requests are too frequent.
The frequency of
ERR_TOO_FREQUENT_REQUESTS 8 requesting must be
reduced, the program
logic must be changed.
The account was disabled.
ERR_ACCOUNT_DISABLED 64 All attempts to trade must
be stopped.
The account number is
ERR_INVALID_ACCOUNT 65 invalid. All attempts to
trade must be stopped.
Timeout for the trade has
been reached. Before
retry (at least, in 1-minute
time), it is necessary to
ERR_TRADE_TIMEOUT 128
make sure that trading
operation has not really
succeeded (a new position
has not been opened, or
149
the existing order has not
been modified or deleted,
or the existing position
has not been closed)
Invalid bid or ask price,
perhaps, unnormalized
price. After 5-second (or
more) delay, it is
necessary to refresh data
using the RefreshRates
ERR_INVALID_PRICE 129
function and make a retry.
If the error does not
disappear, all attempts to
trade must be stopped, the
program logic must be
changed.
Stops are too close, or
prices are ill-calculated or
unnormalized (or in the
open price of a pending
order). The attempt can be
repeated only if the error
occurred due to the price
obsolescense. After 5-
ERR_INVALID_STOPS 130 second (or more) delay, it
is necessary to
refresh data using
the RefreshRates function
and make a retry. If the
error does not disappear,
all attempts to trade must
be stopped, the program
logic must be changed.
Invalid trade volume,
error in the volume
granularity. All attempts
ERR_INVALID_TRADE_VOLUME 131
to trade must be stopped,
and the program logic
must be changed.
Market is closed. The
attempt can be repeated
ERR_MARKET_CLOSED 132 after a rather long period
of time (over several
minutes).
Trade is disabled. All
ERR_TRADE_DISABLED 133 attempts to trade must be
stopped.
150
Not enough money to
make an operation. The
trade with the same
parameters must not be
repeated. After 5-second
(or more) delay, the
ERR_NOT_ENOUGH_MONEY 134
attempt can be repeated
with a smaller volume,
but it is necessary to
make sure that there is
enough money to
complete the operation.
The price has changed.
The data can be refreshed
ERR_PRICE_CHANGED 135 without any delay using
the RefreshRates function
and make a retry.
No quotes. The broker
has not supplied with
prices or refused, for any
reason (for example, no
prices at the session start,
ERR_OFF_QUOTES 136 unconfirmed prices, fast
market). After 5-second
(or more) delay, it is
necessary to refresh data
using the RefreshRates
function and make a retry.
The requested price has
become out of date or bid
and ask prices have been
mixed up. The data can be
refreshed without any
delay using
ERR_REQUOTE 138
the RefreshRates function
and make a retry. If the
error does not disappear,
all attempts to trade must
be stopped, the program
logic must be changed.
The order has been locked
and under processing. All
attempts to make trading
ERR_ORDER_LOCKED 139
operations must be
stopped, and the program
logic must be changed.
Only buying operation is
ERR_LONG_POSITIONS_ONLY_ALLOWED 140
allowed. The SELL
151
operation must not be
repeated.
Too many requests. The
frequency of requesting
ERR_TOO_MANY_REQUESTS 141 must be reduced, the
program logic must be
changed.
The order has been
enqueued. It is not an
error but an interaction
code between the client
terminal and the trade
server. This code can be
142 got rarely, when the
disconnection and the
reconnection happen
during the execution of a
trade operation. This code
should be processed in the
same way as error 128.
The order was accepted
by the dealer for
execution. It is an
interaction code between
the client terminal and the
143
trade server. It can appear
for the same reason as
code 142. This code
should be processed in the
same way as error 128.
The order was discarded
by the client during
manual confirmation. It is
144 an interaction code
between the client
terminal and the trade
server.
Modifying has been
denied since the order is
too close to market and
locked for possible soon
execution. The data can
ERR_TRADE_MODIFY_DENIED 145
be refreshed after more
than 15 seconds using
the RefreshRates
function, and a retry can
be made.
152
The trade thread is busy.
Retry only after
ERR_TRADE_CONTEXT_BUSY 146 the IsTradeContextBusy
function has returned
FALSE.
The use of pending order
expiration date has been
denied by the broker. The
ERR_TRADE_EXPIRATION_DENIED 147 operation can only be
repeated if the expiration
parameter has been
zeroized.
The amount of open and
pending orders has
reached the limit set by
the broker. New open
ERR_TRADE_TOO_MANY_ORDERS 148 positions and pending
orders can be placed only
after the existing
positions or orders have
been closed or deleted.
An attempt to open a
position opposite to the
existing one when
hedging is disabled. First
the existing opposite
ERR_TRADE_HEDGE_PROHIBITED 149
position should be closed,
all attempts of such trade
operations must be
stopped, or the program
logic must be changed.
An attempt to close a
symbol position
contravening the FIFO
rule. First earlier existing
position(s) should be
ERR_TRADE_PROHIBITED_BY_FIFO 150
closed, all attempts of
such trade operations
must be stopped, or the
program logic must be
changed.
ORDERCLOSE
153
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()
154
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
155
if(Ask>var1)
{
OrderDelete(order_ticket);
return(0);
}
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
156
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()
157
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
158
{
Print("order #12470 open price is ", OrderOpenPrice());
Print("order #12470 close price is ", OrderClosePrice());
}
else
Print("OrderSelect returned the error of ",GetLastError());
ORDERSEND
int string symbol, int cmd, double volume, double price, int slippage,
OrderSend( double stoploss, 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.
159
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:
160
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(),OrderS
ymbol(),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)
161
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());
162
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
163
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
165
Sample:
int maywin=WindowFind("MyMACD");
if(maywin>-1 && WindowIsVisible(maywin)==true)
Print("window of MyMACD is visible");
else
Print("window of MyMACD not found or is not visible");
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
WINDOWPRICEMIN
166
double WindowPriceMin(int index=0)
Returns minimal value of the vertical scale of the specified subwindow of the current
chart (0-main chart window, the indicators' subwindows are numbered starting from 1).
If the subwindow index has not been specified, the minimal value of the price scale of
the main chart window is returned.
See also WindowPriceMax(), WindowFirstVisibleBar(), WindowBarsPerChart()
Parameters:
index - Chart subwindow index (0 - main chart window).
Sample:
double top=WindowPriceMax();
double bottom=WindowPriceMin();
datetime left=Time[WindowFirstVisibleBar()];
int right_bound=WindowFirstVisibleBar()-WindowBarsPerChart();
if(right_bound<0) right_bound=0;
datetime right=Time[right_bound]+Period()*60;
//----
ObjectCreate("Padding_rect",OBJ_RECTANGLE,0,left,top,right,bottom);
ObjectSet("Padding_rect",OBJPROP_BACK,true);
ObjectSet("Padding_rect",OBJPROP_COLOR,Blue);
WindowRedraw();
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
167
bool string filename, int size_x, int size_y, int start_bar=-1,
WindowScreenShot( int chart_scale=-1, int chart_mode=-1)
Saves current chart screen shot as a GIF file. Returns FALSE if it fails. To get the error
code, one has to use the GetLastError() function.
The screen shot is saved in the terminal_dir\experts\files (terminal_dir\tester\files in
case of testing) directory or its subdirectories.
Parameters:
filename - Screen shot file name.
size_x - 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);
}
168
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());
169
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.
170