You are on page 1of 170

MQL4 DOCUMENTATION

MQL4 REFERENCE

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


strategies. This language allows to create your own Expert Advisors that make trading
management automated and are perfectly suitable for implementing of one's own trade
strategies. Besides, one can use MQL4 for creation of one's own Custom Indicators, Scripts, and
Libraries.

A large amount of functions necessary for analysis of the current and previously income quotes,
as well as basic arithmetic and logic operations are included in MQL4 structure. There are also
basic indicators built in and commands of order placement and control.

The MetaEditor 4 (text editor) that highlights different constructions of MQL4 language is used
for writing the program code. It helps users to orientate themselves in the expert system text
quite easily. We use MetaQuotes Language Dictionary as a Help System for MQL4 language.
An abridged guide contains functions divided into categories, operations, reserved words, and
other language constructions and allows finding the description of every element we use.

Programs written in MetaQuotes Language 4 have different features and purposes:

• Expert Advisor is a mechanical trading system (MTS) linked up to a certain chart. An


Advisor starts to run with every incoming tick for a given symbol. The Advisor will not
be launched for a new, tick if it is processing the previous one at this moment (i.e., the
Advisor has not completed its operation yet). The Advisor can both inform you about a
possibility to trade and trade at an account automatically sending orders directly to the
trade server. Like most trading systems, the terminal supports testing strategies on
history data with displaying trading in-and-out points in the chart.
Experts are stored in terminal_directory\experts.
• Custom Indicator is a technical indicator written independently in addition to those
already integrated into the client terminal. Like built-in indicators, they cannot trade
automatically and are intended for implementing of analytical functions only.
Custom Indicators are stored in terminal_directory\experts\indicators.
• Script is a program intended for a single execution of some actions. Unlike Expert
Advisors, Scripts are not run tickwise, but on request.
Scripts are stored in terminal_dictionary\experts\scripts.
• Library is a set of custom functions containing programs most frequently used.
Libraries cannot start execution by itself.
Libraries are recommended to be stored in terminal_directory\experts\libraries.
• Included file is a source text of the most frequently used blocks of custom programs.
Such files can be included into the source texts of experts, scripts, custom indicators,
and libraries at the compiling stage. The use of included files is more preferable than the
use of libraries because of additional burden occurring at calling library functions.
Included files are recommended to be stored in terminal_directory\experts\include

1
BASICS

MetaQuotes Language 4 (MQL4) is a new integrated language for programming of trading


strategies. This language allows users writing of their own programs (Expert Advisors) that
automate trading management and ideally suit for implementing of their own trading strategies.
Besides, one can create one's own technical indicators (Custom Indicators), scripts, and libraries
in MQL 4.

SYNTAX

Syntax of MQL4 is much a C-like syntax, apart from some features:

• no address arithmetic;
• no operator do ... while;
• no operator goto ...;
• no operation of [condition]?[expression 1]:[expression 2];
• no compound data types (structures);
• complex assignments are impossible; for example, val1=val2=0; arr[i++]=val;
cond=(cnt=OrdersTotal)>0; etc.;
• calculation of a logical expression is always completed, never early terminated.

COMMENTS

Multiline comments start with /* symbols and end with */ symbols. Such comments cannot be
nested. Single comments start with // symbols, end with the symbol of a new line and can be
nested into multiline comments. Comments are allowed where blank spaces are possible and
tolerate any number of spaces.

Examples:

// single comment
/* multi-
line // nested single comment
comment
*/

IDENTIFIERS

Identifiers are used as names of variables, functions, and data types. The length of an identifier
cannot exceed 31 character.

Symbols you can use: numbers from 0 to 9, Latin capital and small letters a to z, A to Z
(recognized as different symbols), the symbol of underlining (_). The first symbol cannot be a
number. The identifier must not coincide with any reserved word.

Examples:

NAME1 namel Total_5 Paper

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 Memory classes Operators Other


bool extern break false
color static case true
datetime continue
double default
int else
string for
void if
return
switch
while

DATA TYPES

Any program operates with data. Data can be of different types depending on their purposes.
For example, integer data are used to access to array components. Price data belong to those of
double precision with floating point. This is related to the fact that no special data type is
foreseen for price data in MQL 4.

Data of different types are processed with different rates. Integer data are processed at the
fastest. To process the double precision data, a special co-processor is used. However, because
of complicity of internal presentation of data with floating point, they are processed slower than
the integer ones. String data are processed at the longest because of dynamic computer memory
allocation/reallocation.

The main data types are:

• Integer (int)
• Boolean (bool)
• Literals (char)
• Strings (string)
• Floating-point number (double)
• Color (color)
• Date and time (datetime)

The color and datetime types make sense only to facilitate visualization and enter those
parameters that had been set from expert advisor property tab or custom indicator "Inputs" tab.
The data of color and datetime types are represented as integer values. int and double are called
arithmetic (numeric) types.

Only implicit type casting is used in expressions.

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:

int i = 1 / 2; // no types casting, the result is 0


int i = 1 / 2.0; // the expression is cast to the double type,
then is to the target type of int, the result is 0
double d = 1.0 / 2.0; // no types casting, the result is 0.5
double d = 1 / 2.0; // the expression is cast to the double type
that is the same as the target type, the result is 0.5
double d = 1 / 2; // the expression of the int type is cast to the
target type of double, the result is 0.0
string s = 1.0 / 8; // the expression is cast to the double type,
then is to the target type of string, the result is "0.12500000" (the
string containing 10 characters)
string s = NULL; // the constant of type int is cast to the
target type of string, the result is "0" (the string containing 1
character)
string s = "Ticket #"+12345; // the expression is cast to the string
type that is the same as the target type, the result is "Ticket
#12345"

Type casting is applied to not only constants, but also variables of corresponding types.

INTEGER CONSTANTS

Decimals: numbers from 0 to 9; zero must not be the first number.

Examples:

12, 111, -956 1007

Hexadecimals: numbers from 0 to 9, letters from a to f or A to F to represent the values 10 to


15; they start with 0x or 0X.

Examples:

0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7

Its internal representation is a long 4-byte integer number. Integer constants can assume values
from -2147483648 to 2147483647. If the constant exceeds this range, the result is undefined.

4
LITERAL CONSTANTS

Any single character enclosed in single quotes or a hexadecimal ASCII-code of a character


looking like '\x10' is a character constant of integer type. Some characters like a single quote ('),
double quote (") a question mark (?), a reverse slash (\), and control characters can be
represented as a combination of characters starting with a reverse slash (\) according to the table
below:

line feed NL (LF) \n


horizontal tab HT \t
carriage return CR \r
reverse slash \ \\
single quote ' \'
double quote " \"
hexadecimal ASCII-code hh \xhh

If a character different from those listed above follows the reverse slash, the result will not be
defined:

int a = 'A';
int b = '$';
int c = '©'; // code 0xA9
int d = '\xAE'; // symbol code ®

Its internal representation is a long 4-byte integer number. Literal constants can assume values
from 0 to 255. If the constant exceeds this given range, the result is undefined.

BOOLEAN CONSTANTS

Boolean constants may have the value of true or false, numeric representation of them is 1 or 0,
respectively. True or TRUE, False or FALSE can be used, as well.

Examples:

bool a = true;
bool b = false;
bool c = 1;

Its internal representation is a long 4-byte integer number. Boolean constants can assume the
values of 0 or 1.

FLOATING-POINT NUMBER CONSTANTS (DOUBLE)

Floating-point constants consist of an integer part, a point (.), and a fractional part. The integer
and the fractional parts represent sequences of decimal numbers.

Examples:

double a = 12.111;
double b = -956.1007;
double c = 0.0001;
double d = 16;

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

String constant is a sequence of ASCII-code characters enclosed in double quotes: "Character


constant".

A string constant is an array of characters enclosed in quotes. It is of the string type. If there is a
need to insert a double quote (") into the string, a reverse slash (\) must be put before it. Any
special character constants can be inserted into the string if they have a reverse slash (\) before
them. The length of a string constant lies between 0 and 255 characters. If the string constant is
longer, the superfluous characters on the right will be rejected, and compiler will alert
correspondingly.

Examples:

"This is a character string"


"Copyright symbol \t\xA9"
"this line contains a line feed symbol \n"
"C:\\Program Files\\MetaTrader 4"
"A" "1234567890" "0" "$"

Its internal representation is a structure of 8 bytes. The first element of the structure is a long
integer that contains the size of the buffer distributed for the line. The second element of the
structure is 32-order address of the buffer that contains the line.

COLOR CONSTANTS

Color constants can be represented in three ways: literally, by integers, or by name (for named
Web colors only).

Literal representation consists of three parts representing numerical rate values of three main
color components: red, green, blue. The constant starts with C and is enclosed in single quotes.
Numerical rate values of a color component lie in the range from 0 to 255.

Integer-valued representation is written in a form of hexadecimal or a decimal number. A


hexadecimal number looks like 0x00BBGGRR where RR is the rate of the red color component,
GG - of the green one, and BB - of the blue one. Decimal constants are not directly reflected in
RGB. They represent a decimal value of the hexadecimal integer representation.

Specific colors reflect the so-called Web colors set.

Examples:

// symbol constants
C'128,128,128' // gray
C'0x00,0x00,0xFF' // blue
// named color
Red
Yellow
Black
// integer-valued representation

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:

D'2004.01.01 00:00' // New Year


D'1980.07.19 12:30:27'
D'19.07.1980 12:30:27'
D'19.07.1980 12' //equal to D'1980.07.19 12:00:00'
D'01.01.2004' //equal to D'01.01.2004 00:00:00'
D'12:30:27' //equal to D'[compilation date] 12:30:27'
D'' //equal to D'[compilation date] 00:00:00'

Its internal representation is a long integer number of 4 bytes. The value represents the amount
of seconds elapse from 00:00 Jan 1, 1970.

OPERATIONS & EXPRESSIONS

Some characters and character sequences are of a special importance. These are so-called
operation symbols, for example:
+ - * / % symbols of arithmetic operations
&& || symbols of logic operations
= += *= symbols of assignment operations

Operation symbols are used in expressions and have sense when appopriate operands are given
them

Punctuation marks are emphasized, as well. These are parentheses, braces, comma, colon, and
semicolon.

Operation symbols, punctuation marks, spaces are used to separate language elements from each
other.

EXPRESSIONS

An expression consists of one or more operands and operation characters. An expression can be
written in several lines.

Examples:

a++; b = 10;
x = (y * z) /

7
(w + 2) + 127;

An expression that ends with a semicolon (;) is an operator.

ARITHMETICAL OPERATIONS

Arithmetical operations include additive and multiplicative operations:

Sum of values i = j + 2;
Difference of values i = j - 3;
Changing the operation sign x = - x;
Product of values z = 3 * x;
Division quotient i = j / 5;
Division remainder minutes = time % 60;
Adding 1 to the variable value i++;
Subtracting 1 from the variable value k--;

The operations of adding/subtracting 1 (increment/decrement) cannot be used in expressions.

Examples:

int a=3;
a++; // valid expression
int b=(a++)*3; // invalid expression

ASSIGNMENT OPERATION

The value of the expression that includes the given operation is the value of the left operand
after assignment.

Assigning the y value to the x variable y = x;

The following operations unite arithmetic or bitwise operations with operation of assignment:

Adding x to the y variable y += x;


Subtracting x from the y variable y -= x;
Multiplying the y variable by x y *= x;
Dividing the y variable by x y /= x;
Module x value of y y %= x;
Logical shift of y representation to the right by x bit y >>= x;
Logical shift of y representation to the left by x bit y <<= x;
Bitwise operation AND y &= x;
Bitwise operation OR y |= x;
Bitwise operation exclusive OR
of x and y binary notations y ^= x;

There can be only one operation of assignment in an expression. Bitwise operations are
performed with integer numbers only. The logical shift operation uses values of x less than 5
binary digits. The greater digits are rejected, so the shift is for the range of 0 to 31 bit. By %=
operation (y value by module of x), the result sign is equal to the sign of divided number.

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;

Two unnormalized floating-point numbers cannot be linked by == or != operations. That is why


it is necessary to subtract one from another, and the normalized outcome needs to be compared
to null.

BOOLEAN OPERATIONS

Operand of logical negation (operation NOT displayed as exclamation mark) must be of


arithmetic type. The result equals TRUE (1) if the operand value is FALSE (0); and it equals
FALSE (0) if the operand differs from FALSE (0).

if(!a) Print("not 'a'");

Logical operation OR (||) of x and y values. The expression value is TRUE (1) if x or y value is
true (not null). Otherwise, it is FALSE (0). Logical expressions are calculated completely, i.e.,
the so-called "short estimate" method does not apply to them.

if(x<0 || x>=max_bars) Print("out of range");

Logical operation AND (&&) of x and y values. The expression value is TRUE (1) if both x and
y values are ture (not null). Otherwise, it is FALSE (0).

if(p!=x && p>y) Print("TRUE");

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) != 0);

Bitwise operation OR of binary-coded x and y representations. The expression value contains 1


in all digits where x or y is not equal to 0, and it contains 0 in all other digits.

b = x | y;

Bitwise operation EXCLUSIVE OR of binary-coded x and y representations. The expression


value contains 1 in all digits where x and y have different binary values, and it contains 0 in all
other digits.

b = x ^ y;

Bitwise operations are executed with integers only.

OTHER OPERATIONS

Indexing
At addressing to the i-th element of array, the expression value is the value of the variable with
serial number of i.

Example:

array[i] = 3; //Assign the value of 3 to the i-th element of the


array.

Only an integer can be index of an array. Four-dimensional and below arrays are allowed. Each
measurement is indexed from 0 to measurement size-1. In particular case, for a one-
dimensional array consisting of 50 elements, the reference to the first element will look like
array[0], that to the the last element will array[49].

At access beyond the array, the executing subsystem will generate the error
of ERR_ARRAY_INDEX_OUT_OF_RANGE that can be got through the GetLastError()
function.

Call for function with x1,x2,...,xn arguments.


Each argument can represent a constant, a variable, or an expression of the corresponding type.
The arguments passed are separated by commas and must be inside of parentheses, the opening
parenthesis to follow the name of the called function.

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:

for(i=0,j=99; i<100; i++,j--) Print(array[i][j]);

PRECEDENCE RULES

Each group of operations in the table has the same priority. The higher is the priority, the higher
is the position of the group in the table. The precedence rules determine the grouping of
operations and operands.

() Function call From left to right


[] Referencing to an array element
! Logical negation From right to left
- Sign changing operation
++ Increment
-- Decrement
~ Bitwise negation (complement)
& Bitwise operation AND From left to right
| Bitwise operation OR
^ Bitwise operation exclusive OR
<< Left shift
>> Right shift
* Multiplication From left to right
/ Division
% Module division
+ Addition From left to right
- Subtraction
< Less than From left to right
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal
!= Not equal
|| Logical OR From left to right
&& Logical AND From left to right
= Assignment From right to left
+= Assignment addition
-= Assignment subtraction

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

Assignment operator can be used in an expression only once.

Function call operator:

Function_name(argument1,..., argumentN);

FileClose(file);

Empty operator
It consists of a semicolon (;) only and used to denote a null body of a control operator.

BREAK OPERATOR

A break operator terminates the execution of the nearest nested outward switch, while, or for
operator. The control is given to the operator that follows the terminated one. One of the
purposes of this operator is to finish the looping execution when a certain value is assigned to a
variable.

Example:

// searching for the first zero element


for(i=0;i<array_size;i++)
if((array[i]==0)
break;

CONTINUE OPERATOR

A continue operator gives control to the beginning of the nearest outward cycle while or for
operator, the next iteration being called. The purpose of this operator is opposite to that of break
operator.

Example:

// summary of nonzero elements of array


int func(int array[])
{
int array_size=ArraySize(array);
int sum=0;
for(int i=0;i<array_size; i++)
{
if(a[i]==0) continue;
sum+=a[i];
}
return(sum);
}

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:

int CalcSum(int x, int y)


{
return(x+y);
}

In functions with the value of void type to be returned, the return operator must be used without
the expression:

void SomeFunction()
{
Print("Hello!");
return; // this operator can be deleted
}

The right brace of the function means implicit execution of the return operator without
expression.

CONDITIONAL OPERATOR IF-ELSE

If the expression is true, operator1 is executed and the control is given to the operator that
follows operator2 (operator2 is not executed). If the expression is false, operator2 is executed.

if (expression)
operator1
else
operator2

The else part of the if operator can be omitted. Thus, a divergence may appear in nested if
operators with omitted else part. In this case, else addresses to the nearest previous if operator in
the same block that has no else part.

Examples:

// The else part refers to the second if operator:


if(x>1)
if(y==2) z=5;
else z=6;

// The else part refers to the first if operator:


if(x>l)
{
if(y==2) z=5;
}

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;
}

CYCLE OPERATOR WHILE

If the expression is true, the operator is executed until the expression becomes false. If the
expression is false, the control will be given to the next operator.

while(expression)
operator;

An expression value has been defined before the operator is executed. Therefore, if the
expression is false from the very beginning, the operator will not be executed at all.

Example:

while(k<n)
{
y=y*x;
k++;
}

CYCLE OPERATOR FOR

Expression1 describes the cycle initialization. Expression2 is the conditional test for the cycle
termination. If it is true, the loop body for operator will be executed. The cycle repeats until
Expression2 becomes false. If it is false, the cycle will be terminated, and the control will be
given to the next operator. Expression3 is calculated after each iteration.

for (Expression1; Expression2; Expression3)


operator;

The for operator is equivalent to the following succession of operators:

Expression1;
while(Expression2)
{
operator;
Expression3;
};

Any of the three or all three expressions can be absent in the for operator, but the semicolons (;)
that separate them must not be omitted. If Expression2 is omitted, it is considered constantly
true. The for (;;) operator is a continuous cycle equivalent to the while(1) operator. Either
expression 1 or 3 can consist of several expressions combined by a comma operator ','.

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:

double // type of value to be returned


linfunc (double x, double a, double b) // function name and parameters
list
{
// composite operator
return (a + b); // returned value
}

The "return" operator can return the value of the expression included into this operator. If
necessary, the expression value can be transformed into the type of function result. A function
that does not return values must be of "void" type.

Example:

void errmesg(string s)
{
Print("error: "+s);
}

Parameters to be passed to the function can have default values that are defined by constants of
the appropriate type.

Example:

int somefunc(double a, double d=0.0001, int n=5, bool b=true, string


s="passed string")
{
Print("Required parameter a=",a);
Print("The following parameters are transmitted: d=",d," n=",n,"
b=",b," s=",s);
return (0);
}

17
If the default value was assigned to a parameter, all follow-up parameters must have the default
value, too.

Example of a wrong declaration:

int somefunc(double a, double d=0.0001, int n, bool b, string


s="passed string")
{
}

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.

function_name (x1, x2,..., xn)

Arguments (formal parameters) are passed by value, i.e., each expression xl, . . . , xn is
calculated, and the value is passed to the function. The order of expressions calculation and that
of values loading are guaranteed. During the execution, the system checks the number and type
of arguments given to the function. Such way of addressing to the function is called a value call.
Function call is an expression thy value of which is the value returned by the function. The
function type described above must correspond with the type of the returned value. The function
can be declared or described in any part of the program on the global scope, i.e., outside other
functions. The function cannot be declared or described inside of another function.

Examples:

int start()
{
double some_array[4]={0.3, 1.4, 2.5, 3.6};
double a=linfunc(some_array, 10.5, 8);
//...
}
double linfunc(double x[], double a, double b)
{
return (a*x[0] + b);
}

At calling of a function with default parameters, the list of parameters to be passed can be
limited, but not before the first default parameter.

Examples:

void somefunc(double init,double sec=0.0001,int level=10); //


function prototype

somefunc(); // wrong call, the first required


parameter must be presented.
somefunc(3.14); // proper call
somefunc(3.14, 0.0002); // proper call
somefunc(3.14, 0.0002, 10); // proper call

18
When calling a function, one may not skip parameters, even those having default values:

somefunc(3.14, , 10); // wrong call. the second parameter was


skipped.

SPECIAL FUNCTIONS

There are three functions with pre-defined names in MQL4:

init() is a function to be called during the module initialization. If it is not available, no function
will be called at initialization.

start() is the basic function. For experts, it is called after the next tick has income. For custom
indicators, it is called at recalculation after the indicator has been attached to the chart, at
opening of the client terminal (if the indicator is attached to the chart), and after the next tick
has income, as well. For scripts, it is executed immediately after the script has been attached to
the chart and initialized. If there is no start() function in the module, the module (expert, script,
or custom indicator) cannot be launched.

deinit() is a function to be called during deinitialization of the module. If it is not available, no


function will be called at deinitialization.

Pre-defined functions can have some parameters. However, no parameters will be taken from
outside when these functions are called by the client terminal, but the default values will be
used. Functions of start(), init(), and deinit() can be called from any point of the module
according to the common rules, equally to other functions.

It is not recommended to call start() function from init() function or to perform trade operations,
as chart data, market prices, etc. can be incomplete by the moment of the module initialization.
The init() and deinit() functions must finish their working as soon as possible and, in no case,
shall they loop when trying to start its full-fledged working before the start() function is called.

VARIABLES

Variables must be declared before they are used. Unique names are used to identify variables.
Descriptions of variables are used for them to be defined and for types to be declared.
Description is not an operator.

The basic types are:

• bool - boolean values of true and false;


• string - character strings;
• double - double-precision numbers with floating point.

Examples:

string MessageBox;
int Orders;
double SymbolPrice;
bool bLog;

19
Additional types:

• color is an integer representing an RGB color;


• datetime is date and time, an unsigned integer containing seconds that have passed since
0.00 a.m. on 1 January, 1970.

Additional data types make sense only at the declaration of input parameters for their more
convenient representation in the properties window.

Example:

datetime tBegin_Data = D'2004.01.01 00:00';


color cModify_Color = C'0x44,0xB9,0xE6';

Arrays

Array is the indexed sequence of the identical-type data.

int a[50]; // A one-dimensional array of 50 integers.


double m[7][50]; // Two-dimensional array of seven arrays,
//each of them consisting of 50 integers.

Only an integer can be an array index. No more than four-dimensional arrays are allowed.
Numbering of array elements starts with 0. The last element of a one-dimensional array has the
number which is 1 less than the array size. This means that call for the last element of an array
consisting of 50 integers will appear as a[49]. The same concerns multidimensional arrays: A
dimension is indexed from 0 to the dimension size-1. The last element of a two-dimensional
array from the example will appear as m[6][49].

If there is an attempt to access out of the array range, the executing subsystem will generate
error named ERR_ARRAY_INDEX_OUT_OF_RANGE that can be got using
the GetLastError() function.

LOCAL VARIABLES

A variable declared inside any function is local. The scope of a local variable is limited to the
function range inside which it is declared. A local variable can be initialized by outcome of any
expression. Every call of the function initializes a local variable. Local variables are stored in
memory area of the corresponding function.

Example:

int somefunc()
{
int ret_code=0;
....
return(ret_code);
}

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:

void func(int x[], double y, bool z)


{
if(y>0.0 && !z)
Print(x[0]);
...
}

Formal parameters can be initialized by constants. In this case, the initializing value is
considered as the default value. Parameters, next to the intialized one, must also be initialized.

Example:

void func(int x, double y = 0.0, bool z = true)


{
...
}

When calling such a function, the initialized parameters can be omitted, the defaults being
substituted instead of them.

Example:

func(123, 0.5);

MQL4-library functions imported within other modules cannot have parameters initialized by
default values.

Parameters are passed by value, i.e., modifications of the corresponding local variable inside the
called function will not be shown in the calling function in any way. It is possible to pass arrays
as parameters. However, for an array passed as parameter, it is impossible to change values of
its elements.

It is also possible to pass parameters by reference. In this case, modification of such parameters
will be shown in the corresponding variables in the called function passed by reference. Array
elements cannot be passed by reference. Parameters can be passed by reference only within one
module, such possibility being not provided for libraries. In order to inform that a parameter is
passed by reference, it is necessary to put the & modifier after the data type.

Example:

void func(int& x, double& y, double& z[])


{
double calculated_tp;
...

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.

Parameters passed by reference cannot be initialized with defaults.

Into function cannot be passed more than 64 parameters.

STATIC VARIABLES

The memory class of "static" defines a static variable. The specifier "static" is declared before a
data type.

Example:

int somefunc()
{
static int flag=10;
....
return(flag);
}

Static variables are stored in the permanent memory, their values do not get lost when the
function is exited. Any variables in a block, except for formal parameters of the function, can be
defined as static. The static variable can be initialized by a constant of the corresponded type,
unlike a simple local variable which can be initialized by any expression. If there is no explicit
initialization, the static variable is initialized with zero. Static variables are initialized only once
before calling of the "init()" function, that is at exit from the function inside which the static
variable is declared, the value of this variable not getting lost.

GLOBAL VARIABLES

Global variables are defined at the same level as functions, i.e. they are not local in any block.

Example:

int GlobalFlag=10; // global variable


int start()
{
...
}

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.

DEFINING EXTERN VARIABLES

The extern memory class defines an extern variable. The extern specifier is declared before a
data type.

Example:

extern double InputParameter1 = 1.0;


extern color InputParameter2 = red;

int init()
{
...
}

Extern variables determine inputs of the program, they are accessible from a program properties
window. Arrays cannot represent themselves as extern variables.

INITIALIZATION OF VARIABLES

Any variable can be initialized at its defining. Any variable is initialized with zero (0) if no
other initial value is explicitly defined. Global and static variables can be initialized only by a
constant of the corresponding type. Local variables can be initialized by any expression, not
only constant.

Global and static variables are initialized only once. Local variables are initialized every time by
call of the corresponded functions.

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.

Preprocessor also allows determining of specific parameters of MQL4 programs.

If the # symbol is used in the first line of the program, this line is a preprocessor directive. A
preprocessor directive ends with a line feed character.

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:

#define identifier value

The constant identifier conforms to the same rules as those regulating names of variables. The
value can be of any type:

#define ABC 100


#define PI 0.314
#define COMPANY_NAME "MetaQuotes Software Corp."

...

void ShowCopyright()
{
Print("Copyright © 2001-2007, ",COMPANY_NAME);
Print("http://www.metaquotes.net");
}

CONTROLLING COMPILATION

Every MQL4 program allows to specify additional specific parameters named #property that
help client terminal in proper servicing for programs without the necessity to launch them
explicitly. This concerns external settings of indicators, first of all.

#property identifier value

Constant Type Description


link string a link to the company website
copyright string the company name
stacksize int stack size
a library; no start function is assigned, non-referenced
library
functions are not removed
indicator_chart_window void show the indicator in the chart window
indicator_separate_window void show the indicator in a separate window
indicator_buffers int the number of buffers for calculation, up to 8
the bottom scaling limit for a separate indicator
indicator_minimum double
window
indicator_maximum double the top scaling limit for a separate indicator window
the color for displaying line N, where N lies between
indicator_colorN color
1 and 8
indicator_widthN int width of the line N, where N lies between 1 and 8

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:

#property link "http://www.metaquotes.net"


#property copyright "MetaQuotes Software Corp."
#property library
#property stacksize 1024

Compiler will write the declared values in the settings of the executed module.

INCLUDING OF FILES

The #include command line can be placed anywhere in the program, but usually all inclusions
are placed at the beginning of the source code. Call format:

#include <file_name>
#include "file_name";

Examples:

#include <WinUser32.mqh>
#include "mylib.mqh"

Preprocessor replaces this line with the content of the file WinUser32.mqh. Angle brackets
mean that the WinUser32.mqh file will be taken from the default directory (usually
terminal_directory\experts\include). The current directory is not searched.

If the file name is enclosed in quotation marks, the search will be performed in the current
directory (where the main file of the source code is located). The standard directory is not
searched in.

IMPORTING OF FUNCTIONS

Functions are imported from compiled MQL4 modules (*.ex4 files) and from operating system
modules (*.dll files). The module name is specified in the #import directive. For compiler to be
able to form the imported function call and pass parameters in a proper way, the full description
of functions is needed. Functions descriptions follow the #import "module name" immediately.

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.

The constants are grouped by their purposes.

SERIES ARRAYS

Series array identifier used with ArrayCopySeries(), iHighest() and iLowest() functions.
It can be any of the following values:

Constant Value Description


MODE_OPEN 0 Open price.
MODE_LOW 1 Low price.
MODE_HIGH 2 High price.
MODE_CLOSE 3 Close price.
MODE_VOLUME 4 Volume, used in iLowest() and iHighest() functions.
MODE_TIME 5 Bar open time, used in ArrayCopySeries() function.

TIMEFRAMES

Timeframe of the chart (chart period). It can be any of the following values:

Constant Value Description


PERIOD_M1 1 1 minute.
PERIOD_M5 5 5 minutes.
PERIOD_M15 15 15 minutes.
PERIOD_M30 30 30 minutes.
PERIOD_H1 60 1 hour.
PERIOD_H4 240 4 hour.
PERIOD_D1 1440 Daily.
PERIOD_W1 10080 Weekly.
PERIOD_MN1 43200 Monthly.
0 (zero) 0 Timeframe used on the chart.

28
TRADE OPERATIONS

Operation type for the OrderSend() function. It can be any of the following values:

Constant Value Description


OP_BUY 0 Buying position.
OP_SELL 1 Selling position.
OP_BUYLIMIT 2 Buy limit pending position.
OP_SELLLIMIT 3 Sell limit pending position.
OP_BUYSTOP 4 Buy stop pending position.
OP_SELLSTOP 5 Sell stop pending position.

PRICE CONSTANTS

Applied price constants. It can be any of the following values:

Constant Value Description


PRICE_CLOSE 0 Close price.
PRICE_OPEN 1 Open price.
PRICE_HIGH 2 High price.
PRICE_LOW 3 Low price.
PRICE_MEDIAN 4 Median price, (high+low)/2.
PRICE_TYPICAL 5 Typical price, (high+low+close)/3.
PRICE_WEIGHTED 6 Weighted close price, (high+low+close+close)/4.

MARKETINFO

Market information identifiers, used with MarketInfo() function.


It can be any of the following values:

Constant Value Description


MODE_LOW 1 Low day price.
MODE_HIGH 2 High day price.
The last incoming tick time (last
MODE_TIME 5
known server time).
Last incoming bid price. For the
MODE_BID 9 current symbol, it is stored in the
predefined variable Bid
Last incoming ask price. For the
MODE_ASK 10
current symbol, it is stored in the

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 shape style enumeration for SetIndexStyle() function.

It can be any of the following values:

Constant Value Description


DRAW_LINE 0 Drawing line.
DRAW_SECTION 1 Drawing sections.
DRAW_HISTOGRAM 2 Drawing histogram.
DRAW_ARROW 3 Drawing arrows (symbols).
Drawing sections between even and odd indicator
DRAW_ZIGZAG 4
buffers.
DRAW_NONE 12 No drawing.

Drawing style. Valid when width=1. It can be any of the following values:

Constant Value Description


STYLE_SOLID 0 The pen is solid.
STYLE_DASH 1 The pen is dashed.
STYLE_DOT 2 The pen is dotted.
STYLE_DASHDOT 3 The pen has alternating dashes and dots.
STYLE_DASHDOTDOT 4 The pen has alternating dashes and double dots.

ARROW CODES

Predefined Arrow codes enumeration. Arrows code constants. It can be one of the
following values:

Constant Value Description


SYMBOL_THUMBSUP 67 Thumb up symbol ().
SYMBOL_THUMBSDOWN 68 Thumb down symbol ().
SYMBOL_ARROWUP 241 Arrow up symbol ().
SYMBOL_ARROWDOWN 242 Arrow down symbol ().
SYMBOL_STOPSIGN 251 Stop sign symbol ().
SYMBOL_CHECKSIGN 252 Check sign symbol ().

31
Special Arrow codes that exactly points to price and time. It can be one of the following
values:

Constant Value Description


1 Upwards arrow with tip rightwards (↱).
2 Downwards arrow with tip rightwards (↳).
3 Left pointing triangle (◄).
4 En Dash symbol (–).
SYMBOL_LEFTPRICE 5 Left sided price label.
SYMBOL_RIGHTPRICE 6 Right sided price label.

WINGDINGS

Wingdings font symbols used with Arrow objects.

32 ! 33 " 34 # 35 $ 36 % 37 & 38 ' 39 ( 40 ) 41 * 42 + 43 , 44 - 45 . 46 / 47


0 48 1 49 2 50 3 51 4 52 5 53 6 54 7 55 8 56 9 57 : 58 ; 59 < 60 = 61 > 62 ? 63
@ 64 A 65 B 66 C 67 D 68 E 69 F 70 G 71 H 72 I 73 J 74 K 75 L 76 M 77 N 78 O 79
P 80 Q 81 R 82 S 83 T 84 U 85 V 86 W 87 X 88 Y 89 Z 90 [ 91 \ 92 ] 93 ^ 94 _ 95
10 10 10 10 10 10 10 10 10 10 11 11
` 96 a 97 b 98 c 99 d e f g h i j k l m n o
0 1 2 3 4 5 6 7 8 9 0 1
11 11 11 11 11 11 11 11 12 12 12 12 12 12 12 12
p q r s t u v w x y z { | } ~ 
2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
12 12 13 13 13 13 13 13 13 13 13 13 14 14 14 14
€ � ‚ ƒ „ … † ‡ ˆ ‰ Š ‹ Œ � Ž �
8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
14 14 14 14 14 14 15 15 15 15 15 15 15 15 15 15
� ‘ ’ “ ” • – — ˜ ™ š › œ � ž Ÿ
4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
16 16 16 16 16 16 16 16 16 16 17 17 17 17 17 17
¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ® ¯
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
17 17 17 17 18 18 18 18 18 18 18 18 18 18 19 19
° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿
6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
19 19 19 19 19 19 19 19 20 20 20 20 20 20 20 20
À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï
2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
20 20 21 21 21 21 21 21 21 21 21 21 22 22 22 22
Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß
8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
22 22 22 22 22 22 23 23 23 23 23 23 23 23 23 23
à á â ã ä å æ ç è é ê ë ì í î ï
4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
24 24 24 24 24 24 24 24 24 24 25 25 25 25 25 25
ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5

32
WEB COLORS

color type supported color constants.


Black DarkGreen DarkSlateGray Olive Green Teal Navy Purple
DarkOliveGree SaddleBro
Maroon Indigo MidnightBlue DarkBlue ForestGreen OliveDrab
n wn
DarkTurquois
SeaGreen DarkGoldenrod DarkSlateBlue Sienna MediumBlue Brown DimGray
e
LightSeaGr MediumVioletRe MediumSeaGr
DarkViolet FireBrick Chocolate Crimson SteelBlue
een d een
MediumSpringGr YellowGre
Goldenrod LawnGreen CadetBlue DarkOrchid LimeGreen OrangeRed
een en
DarkOrange Orange Gold Yellow Chartreuse Lime SpringGreen Aqua
DeepSkyBlu
Blue Magenta Red Gray SlateGray Peru BlueViolet
e
LightSlateG MediumTurqu
DeepPink DodgerBlue Turquoise RoyalBlue SlateBlue DarkKhaki
ray oise
MediumAquama
IndianRed MediumOrchid GreenYellow DarkSeaGreen Tomato RosyBrown Orchid
rine
MediumPur SandyBro MediumSlateB
PaleVioletRed Coral CornflowerBlue DarkGray Tan
ple wn lue
DarkSalmon BurlyWood HotPink Salmon Violet LightCoral SkyBlue LightSalmon
LightSkyBl
Plum Khaki LightGreen Aquamarine Silver LightSteelBlue LightBlue
ue
PaleGreen Thistle PowderBlue PaleGoldenrod PaleTurquoise LightGray Wheat NavajoWhite
LightGoldenro BlanchedAlm
Moccasin LightPink Gainsboro PeachPuff Pink Bisque
d ond
LemonChiff LightYello
Beige AntiqueWhite PapayaWhip Cornsilk LightCyan Linen
on w
Lavender MistyRose OldLace WhiteSmoke Seashell Ivory Honeydew AliceBlue
LavenderBl
MintCream Snow White
ush

INDICATOR LINES

Indicator line identifiers used in iMACD(), iRVI() and iStochastic() indicators.


It can be one of the following values:

Constant Value Description


MODE_MAIN 0 Base indicator line.
MODE_SIGNAL 1 Signal line.

Indicator line identifiers used in iADX() indicator.

Constant Value Description


MODE_MAIN 0 Base indicator line.
MODE_PLUSDI 1 +DI indicator line.
MODE_MINUSDI 2 -DI indicator line.

Indicator line identifiers used


in iBands(), iEnvelopes(), iEnvelopesOnArray(), iFractals() and iGator() indicators.

33
Constant Value Description
MODE_UPPER 1 Upper line.
MODE_LOWER 2 Lower line.

ICHIMOKU KINKO HYO

Ichimoku Kinko Hyo identifiers used in iIchimoku() indicator call as source of


requested data.
It can be one of the following values:

Constant Value Description


MODE_TENKANSEN 1 Tenkan-sen.
MODE_KIJUNSEN 2 Kijun-sen.
MODE_SENKOUSPANA 3 Senkou Span A.
MODE_SENKOUSPANB 4 Senkou Span B.
MODE_CHINKOUSPAN 5 Chinkou Span.

MOVING AVERAGE METHODS

Moving Average calculation method used


with iAlligator(), iEnvelopes(), iEnvelopesOnArray, iForce(), iGator(), iMA(), iMAOn
Array(), iStdDev(), iStdDevOnArray(), iStochastic() indicators.
It can be any of the following values:

Constant Value Description


MODE_SMA 0 Simple moving average,
MODE_EMA 1 Exponential moving average,
MODE_SMMA 2 Smoothed moving average,
MODE_LWMA 3 Linear weighted moving average.

The MessageBox() function return codes.


If a message box has a Cancel button, the function returns the IDCANCEL value if
either the ESC key is pressed or the Cancel button is selected. If the message box has
no Cancel button, pressing ESC has no effect.
Note: MessageBox return codes defined in the WinUser32.mqh file

Constant Value Description


IDOK 1 OK button was selected.
IDCANCEL 2 Cancel button was selected.
IDABORT 3 Abort button was selected.
IDRETRY 4 Retry button was selected.

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.

Constant Value Description


The message box contains one push
MB_OK 0x00000000
button: OK. This is the default.
The message box contains two push
MB_OKCANCEL 0x00000001
buttons: OK and Cancel.
The message box contains three
MB_ABORTRETRYIGNORE 0x00000002 push buttons: Abort, Retry, and
Ignore.
The message box contains three
MB_YESNOCANCEL 0x00000003
push buttons: Yes, No, and Cancel.
The message box contains two push
MB_YESNO 0x00000004
buttons: Yes and No.
The message box contains two push
MB_RETRYCANCEL 0x00000005
buttons: Retry and Cancel.
Windows 2000: The message box
contains three push buttons: Cancel,
MB_CANCELTRYCONTINUE 0x00000006 Try Again, Continue. Use this
message box type instead of
MB_ABORTRETRYIGNORE.

To display an icon in the message box, specify one of the following values.

Constant Value Description


MB_ICONSTOP,
A stop-sign icon appears in the
MB_ICONERROR, 0x00000010
message box.
MB_ICONHAND
A question-mark icon appears in the
MB_ICONQUESTION 0x00000020
message box.

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.

To indicate the default button, specify one of the following values.

Constant Value Description


The first button is the default button.
MB_DEFBUTTON1 is the default unless
MB_DEFBUTTON1 0x00000000
MB_DEFBUTTON2, MB_DEFBUTTON3, or
MB_DEFBUTTON4 is specified.
MB_DEFBUTTON2 0x00000100 The second button is the default button.
MB_DEFBUTTON3 0x00000200 The third button is the default button.
MB_DEFBUTTON4 0x00000300 The fourth button is the default button.

MessageBox() function behavior flags are defined in the WinUser32.mqh file, this is
why this heading file must be included to programs through #include
<WinUser32.mqh>. Not all possible flags are listed here. For more details, please refer
to Win32 API description.

OBJECT TYPES

Object type identifier constants used with ObjectCreate(), ObjectsDeleteAll()


and ObjectType() functions. It can be any of the following values:
Objects can have 1-3 coordinates related to type.

Constant Value Description


OBJ_VLINE 0 Vertical line. Uses time part of first coordinate.
Horizontal line. Uses price part of first
OBJ_HLINE 1
coordinate.
OBJ_TREND 2 Trend line. Uses 2 coordinates.
Trend by angle. Uses 1 coordinate. To set angle
OBJ_TRENDBYANGLE 3
of line use ObjectSet() function.
Regression. Uses time parts of first two
OBJ_REGRESSION 4
coordinates.
OBJ_CHANNEL 5 Channel. Uses 3 coordinates.
Standard deviation channel. Uses time parts of
OBJ_STDDEVCHANNEL 6
first two coordinates.
Gann line. Uses 2 coordinate, but price part of
OBJ_GANNLINE 7
second coordinate ignored.

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:

Constant Value Type Description


Datetime value to set/get first
OBJPROP_TIME1 0 datetime
coordinate time part.
Double value to set/get first
OBJPROP_PRICE1 1 double
coordinate price part.
Datetime value to set/get second
OBJPROP_TIME2 2 datetime
coordinate time part.
Double value to set/get second
OBJPROP_PRICE2 3 double
coordinate price part.
Datetime value to set/get third
OBJPROP_TIME3 4 datetime
coordinate time part.
Double value to set/get third
OBJPROP_PRICE3 5 double
coordinate price part.
OBJPROP_COLOR 6 color Color value to set/get object color.
OBJPROP_STYLE 7 int Value is one of STYLE_SOLID,

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

Timeframes where object may be shown. Used in ObjectSet() function to set


OBJPROP_TIMEFRAMES property.

Constant Value Description


OBJ_PERIOD_M1 0x0001 Object shown is only on 1-minute charts.
OBJ_PERIOD_M5 0x0002 Object shown is only on 5-minute charts.
OBJ_PERIOD_M15 0x0004 Object shown is only on 15-minute charts.
OBJ_PERIOD_M30 0x0008 Object shown is only on 30-minute charts.
OBJ_PERIOD_H1 0x0010 Object shown is only on 1-hour charts.
OBJ_PERIOD_H4 0x0020 Object shown is only on 4-hour charts.
OBJ_PERIOD_D1 0x0040 Object shown is only on daily charts.
OBJ_PERIOD_W1 0x0080 Object shown is only on weekly charts.
OBJ_PERIOD_MN1 0x0100 Object shown is only on monthly charts.
OBJ_ALL_PERIODS 0x01FF Object shown is on all timeframes.
NULL 0 Object shown is on all timeframes.
EMPTY -1 Hidden object on all timeframes.

UNINITIALIZE REASON CODES

Uninitialize reason codes returned by UninitializeReason() function. It can be any one


of the following values:

Constant Value Description


0 Script finished its execution independently.
REASON_REMOVE 1 Expert removed from chart.
REASON_RECOMPILE 2 Expert recompiled.

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:

Constant Value Description


NULL 0 Indicates empty state of the string.
EMPTY -1 Indicates empty state of the parameter.
EMPTY_VALUE 0x7FFFFFFF Default custom indicator empty value.
CLR_NONE 0xFFFFFFFF Indicates empty state of colors.
Used with array functions. Indicates that all
WHOLE_ARRAY 0
array elements will be processed.

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));
}

Error codes returned from trade server.

Constant Value Description


ERR_NO_ERROR 0 No error returned.
No error returned, but the
ERR_NO_RESULT 1
result is unknown.
ERR_COMMON_ERROR 2 Common error.
ERR_INVALID_TRADE_PARAMETERS 3 Invalid trade parameters.
ERR_SERVER_BUSY 4 Trade server is busy.

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.

MQL4 run time error codes

Constant Value Description


ERR_NO_MQLERROR 4000 No error.
ERR_WRONG_FUNCTION_POINTER 4001 Wrong function pointer.
Array index is out of
ERR_ARRAY_INDEX_OUT_OF_RANGE 4002
range.
No memory for function
ERR_NO_MEMORY_FOR_CALL_STACK 4003
call stack.
Recursive stack
ERR_RECURSIVE_STACK_OVERFLOW 4004
overflow.
Not enough stack for
ERR_NOT_ENOUGH_STACK_FOR_PARAM 4005
parameter.
No memory for
ERR_NO_MEMORY_FOR_PARAM_STRING 4006
parameter string.
No memory for temp
ERR_NO_MEMORY_FOR_TEMP_STRING 4007
string.
ERR_NOT_INITIALIZED_STRING 4008 Not initialized string.
Not initialized string in
ERR_NOT_INITIALIZED_ARRAYSTRING 4009
array.
No memory for array
ERR_NO_MEMORY_FOR_ARRAYSTRING 4010
string.
ERR_TOO_LONG_STRING 4011 Too long string.
Remainder from zero
ERR_REMAINDER_FROM_ZERO_DIVIDE 4012
divide.
ERR_ZERO_DIVIDE 4013 Zero divide.
ERR_UNKNOWN_COMMAND 4014 Unknown command.
Wrong jump (never
ERR_WRONG_JUMP 4015
generated error).
ERR_NOT_INITIALIZED_ARRAY 4016 Not initialized array.
DLL calls are not
ERR_DLL_CALLS_NOT_ALLOWED 4017
allowed.
ERR_CANNOT_LOAD_LIBRARY 4018 Cannot load library.
ERR_CANNOT_CALL_FUNCTION 4019 Cannot call function.
ERR_EXTERNAL_CALLS_NOT_ALLOWED 4020 Expert function calls are

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.

Libraries use variables of the module that has called a library.

To have a safe and quick access to these data, client terminal provides local copies of
predefined variables for each launched program separately. These data are updated at
every launch of an attached expert or a custom indicator automatically or using
the RefreshRates() function call.

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.

See also iClose().


Sample:
int handle = FileOpen("file.csv", FILE_CSV|FILE_WRITE, ";");
if(handle>0)
{
// table column headers recording
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// data recording
for(int i=0; i<Bars; i++)
FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i],
Volume[i]);
FileClose(handle);
}

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.

See also iHigh().


Sample:
//---- maximums counting
i=Bars-KPeriod;
if(counted_bars>KPeriod) i=Bars-counted_bars-1;
while(i>=0)
{
double max=-1000000;
k = i + KPeriod-1;
while(k>=i)

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.

See also iLow().


Sample:
//---- minima counting
i=Bars-KPeriod;
if(counted_bars>KPeriod) i=Bars-counted_bars-1;
while(i>=0)
{
double min=1000000;
k = i + KPeriod-1;
while(k>=i)
{
price=Low[k];
if(min>price) min=price;
k--;
}
LowesBuffer[i]=min;
i--;
}
//----

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.

See also iOpen().


Sample:
i = Bars - counted_bars - 1;
while(i>=0)
{
double high = High[i];
double low = Low[i];

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.

See also iTime().


Sample:
for(i=Bars-2; i>=0; i--)
{
if(High[i+1] > LastHigh) LastHigh = High[i+1];
if(Low[i+1] < LastLow) LastLow = Low[i+1];
//----
if(TimeDay(Time[i]) != TimeDay(Time[i+1]))
{
P = (LastHigh + LastLow + Close[i+1])/3;
R1 = P*2 - LastLow;
S1 = P*2 - LastHigh;
R2 = P + LastHigh - LastLow;
S2 = P - (LastHigh - LastLow);
R3 = P*2 + LastHigh - LastLow*2;
S3 = P*2 - (LastHigh*2 - LastLow);
LastLow = Open[i];
LastHigh = Open[i];
}
//----

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.

See also iVolume().


Sample:
if(i==0 && time0<i_time+periodseconds)
{
d_volume += Volume[0];
if(Low[0]<d_low) d_low = Low[0];
if(High[0]>d_high) d_high = High[0];
d_close = Close[0];
}
last_fpos = FileTell(ExtHandle);
last_volume = Volume[i];
FileWriteInteger(ExtHandle, i_time, LONG_VALUE);
FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE);

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.

IMPORTED FUNCTIONS CALL

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.

At describing of the imported function prototype, it is useless to use parameters with


default values as all parameters must be passed explicitely to the imported function.

If the call for an imported function failed (expert settings do not allow DLL imports, or
the corresponding library could not be loaded for any reason), the expert stops working
putting the corresponding message into the "expert stopped" journal. At that, the expert
will not be launched until it is re-initialized. An expert can be re-initialized as a result of
recompiling or opening of the expert properties table and pressing of OK button.

RUNTIME ERRORS

In the executing sub-system of the client terminal, the error code can be stored, in the
case of its occurring at an mql4 program execution. There is a specific last_error
variable provided for every executable mql4 program. Before the init function is run,
the last_error variable has been zeroized. If an error occurs during the process of
calculation or that of calling the built-in function, the last_error variable takes the
corresponding error code. Value stored in this variable can be got using
the GetLastError function. At that, the last_error variable will be zeroized.

There is a number of critical errors that cause immediate stopping of program


execution:

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

Other errors do not interrupt program execution.

Constant Value Description


Attempt to access an array
ERR_ARRAY_INDEX_OUT_OF_RANGE 4002 item number of which is
out of the array range
Not initialized string; no
value was assigned to the
ERR_NOT_INITIALIZED_STRING 4008
string being an operand in
an expression
Not initialized string in
the array string; no value
ERR_NOT_INITIALIZED_ARRAYSTRING 4009 was assigned to the string
item being an operand in
an expression
It is impossible to
reallocate memory for a
ERR_NO_MEMORY_FOR_RETURNED_STR 4021
string returned from
function

The ERR_NO_MQLERROR (4000) code is never generated.

There is a number of errors which are possible only as a result of software or hardware
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.

Function Error codes


ERR_STRING_PARAMETER_EXPECTED (4062),
ERR_INTEGER_PARAMETER_EXPECTED (4063),
AccountFreeMarginCheck ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_UNKNOWN_SYMBOL (4106),
ERR_NOT_ENOUGH_MONEY (134)
ERR_CUSTOM_INDICATOR_ERROR (4055),
ERR_STRING_PARAMETER_EXPECTED (4062),
ERR_INTEGER_PARAMETER_EXPECTED (4063),
ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_INVALID_PRICE_PARAM (4107),
OrderSend
ERR_UNKNOWN_SYMBOL (4106),
ERR_TRADE_NOT_ALLOWED (4109),
ERR_LONGS_NOT_ALLOWED (4110),
ERR_SHORTS_NOT_ALLOWED (4111), code
returned by trade server
ERR_CUSTOM_INDICATOR_ERROR (4055),
ERR_INTEGER_PARAMETER_EXPECTED (4063),
ERR_INVALID_FUNCTION_PARAMVALUE
(4051), ERR_INVALID_PRICE_PARAM (4107),
OrderClose
ERR_INVALID_TICKET (4108),
ERR_UNKNOWN_SYMBOL (4106),
ERR_TRADE_NOT_ALLOWED (4109), code
returned by trade server
ERR_CUSTOM_INDICATOR_ERROR (4055),
OrderCloseBy ERR_INTEGER_PARAMETER_EXPECTED (4063),
ERR_INVALID_FUNCTION_PARAMVALUE

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.

Function Error codes


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

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)

Other functions never change the last_error variable value.


AccountBalance, AccountCompany, AccountCredit, AccountCurrency, AccountEquity,
AccountFreeMargin, AccountLeverage, AccountMargin, AccountName, AccountNum
ber, AccountProfit, AccountServer, Alert, CharToStr, Comment, Day, DayOfWeek, Da
yOfYear, DoubleToStr, GetTickCount, HideTestIndicators, Hour, IndicatorCounted, Is
Connected, IsDemo, IsDllsAllowed, IsExpertEnabled, IsLibrariesAllowed, IsOptimizati
on, IsStopped, IsTesting, IsTradeAllowed, IsTradeContextBusy, IsVisualMode, MathA
bs, MathArctan, MathCeil, MathCos, MathExp, MathFloor, MathLog, MathMax, Math
Min, MathPow, MathRand, MathRound, MathSin, MathSrand, MathTan, Minute, Mont
h, NormalizeDouble, ObjectsDeleteAll, ObjectsTotal, OrderSelect, OrdersHistoryTotal,
Period, Print, RefreshRates, Seconds, SetLevelStyle, StringConcatenate, StrToTime, Str
ToDouble, Symbol, TerminalCompany, TerminalName, TerminalPath, TimeCurrent, Ti
meDay, TimeDayOfWeek, TimeDayOfYear, TimeHour, TimeLocal, TimeMinute, Tim
eMonth, TimeSeconds, TimeToStr, TimeYear, UninitializeReason, WindowBarsPerCha
rt, WindowFirstVisibleBar, WindowPriceOnDropped, WindowRedraw, WindowTimeO
nDropped, WindowsTotal, WindowOnDropped, WindowXOnDropped, WindowYOnD
ropped, Year

64
ACCOUNT INFORMATION

A group of functions to access to the active 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

double AccountFreeMarginCheck(string symbol, int cmd, double volume)


Returns free margin that remains after the specified position has been opened at the
current price on the current account. If the free margin is insufficient, an error 134
(ERR_NOT_ENOUGH_MONEY) will be generated.
Parameters:
symbol - Symbol for trading operation.
cmd - Operation type. It can be either OP_BUY or OP_SELL.
volume - Number of lots.
Sample:
if(AccountFreeMarginCheck(Symbol(),OP_BUY,Lots)<=0 ||
GetLastError()==134) return;

ACCOUNTFREEMARGINMODE

double AccountFreeMarginMode()
Calculation mode of free margin allowed to open positions on the current account. The
calculation mode can take the following values:

0 - floating profit/loss is not used for calculation;


1 - both floating profit and loss on open positions on the current account are used for
free margin calculation;
2 - only profit value is used for calculation, the current loss on open positions is not
considered;
3 - only loss value is used for calculation, the current loss on open positions is not
considered.
Sample:
if(AccountFreeMarginMode()==0)
Print("Floating Profit/Loss do not use.");

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:

0 - calculation of percentage ratio between margin and equity;


1 - comparison of the free margin level to the absolute value.
Sample:
int level=AccountStopoutLevel();
if(AccountStopoutMode()==0)
Print("StopOut level = ", level, "%");
else
Print("StopOut level = ", level, " ", AccountCurrency());

67
ARRAY FUNCTIONS

A group of functions to work with arrays.

Arrays are allowed to be maximum four-dimensional. Each dimension is indexed from


0 to dimension size-1. In a particular case of a one-dimensional array of 50 elements,
calling of the first element will appear as array[0], of the last one - as array[49].

Using these functions (except for those which change quantitative and qualitative
characteristics of the array) one can process predefined time
series Time[], Open[], High[], Low[], Close[], Volume[]

ARRAYBSEARCH

int double array[], double value, int count=WHOLE_ARRAY, int start=0,


ArrayBsearch( int direction=MODE_ASCEND)
If the element with the specified value doesn't exist in the array, the function returns the
index of the nearest smallest value of the elements between which the searched value is
located.
The function cannot be used with string arrays and series arrays (with the exception of
the series array of the bar open time).
Note: Binary search processes only sorted arrays. To sort numeric arrays use
the ArraySort() function.
Parameters:
array[] - The numeric array to search for.
value - The value to search for.
count - Count of elements to search for. By default, it searches in the whole
array.
start - Starting index to search for. By default, the search starts at the first
element.
direction - Search direction. It can be any of the following values:
MODE_ASCEND searching in forward direction,
MODE_DESCEND searching in backward direction.
Sample:
datetime daytimes[];
int shift=10,dayshift;
// All the Time[] series are sorted in descendant mode
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
if(Time[shift]>=daytimes[0]) dayshift=0;
else
{

dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND)
;
if(Period()<PERIOD_D1) dayshift++;
}
Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar
opened at ",
TimeToStr(daytimes[dayshift]));

68
ARRAYCOPY

int void dest[], object source[], int start_dest=0, int start_source=0,


ArrayCopy( int count=WHOLE_ARRAY)
Copies an array to another one. Arrays must be of the same type, but arrays with type
double[], int[], datetime[], color[], and bool[] can be copied as arrays of the same type.
Returns the amount of copied elements.
Parameters:
dest[] - Destination array.
source[] - Source array.
start_dest - Starting index for the destination array. By default, start index is 0.
start_source - Starting index for the source array. By default, start index is 0.
count - The count of elements that should be copied. By default, it is
WHOLE_ARRAY constant.
Sample:
double array1[][6];
double array2[10][6];
// array2 is filled with some data
ArrayCopyRates(array1);
ArrayCopy(array2,array1,0,0,60);
// array2 is having the first 10 bars from the history now (first
bar considered as bar with index [Bars-1])
ArrayCopy(array2,array1,0,Bars*6-60,60);
// array2 is having the last 10 bars from the history now (last bar
considered as current bar, bar wit index [0])

ARRAYCOPYRATES

int ArrayCopyRates(void dest_array[], string symbol=NULL, int timeframe=0)


Copies rates to the two-dimensional array from chart RateInfo array and returns copied
bars amount, or -1 if failed. First dimension of RateInfo array contains bars amount,
second dimension has 6 elements:
0 - time,
1 - open,
2 - low,
3 - high,
4 - close,
5 - volume.

If data (symbol name and/or timeframe differ from the current ones) are requested from
another chart, the situation is 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

int void array[], int series_index, string symbol=NULL,


ArrayCopySeries( int timeframe=0)
Copies a series array to another one and returns the count of the copied elements.

There is no real memory allocation for data array and nothing is copied. When such an
array is accessed, the access is redirected. Excluded are arrays that are assigned as
indexed ones in custom indicators. In this case, data are really copied.

If data are copied from another chart with different symbol and/or timeframe, it is
possible that the necessary data will lack. In this case, error
ERR_HISTORY_WILL_UPDATED (4066 - requested history data under updating)
will be placed into the last_error variable, and there will be necessary to retry copying
after a certain period of time.

Note: If series_index is MODE_TIME, the array to be passed to the function must be of


the datetime type.
Parameters:
array[] - Reference to the destination one-dimensional numeric array.
series_index - Series array identifier. It must be one of series array listed identifiers
values.
symbol - Symbol name (the name of the currency pair)
timeframe - Timeframe of the chart. It can be any of Timeframe list values.
Sample:
datetime daytimes[];
int shift=10,dayshift,error;
//---- the Time[] array was sroted in the descending order
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
error=GetLastError();
if(error==4066)
{
//---- make two more attempts to read
for(int i=0;i<2; i++)
{
Sleep(5000);
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
//---- check the current daily bar time
datetime last_day=daytimes[0];
if(Year()==TimeYear(last_day) && Month()==TimeMonth(last_day) &&
Day()==TimeDay(last_day)) break;
}
}

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

int ArrayDimension(object array[])


Returns the multidimensional array rank.
Parameters:
array[] - Array for which the rank will be returned.
Sample:
int num_array[10][5];
int dim_size;
dim_size=ArrayDimension(num_array);
// dim_size=2

ARRAYGETASSERIES

bool ArrayGetAsSeries(object array[])


Returns TRUE if array is organized as a series array (array elements are indexed from
the last to the first one), otherwise returns FALSE.
Parameters:
array[] - Array to be checked.
Sample:
if(ArrayGetAsSeries(array1)==true)
Print("array1 is indexed as a series array");
else
Print("array1 is indexed normally (from left to right)");

ARRAYINITIALIZE

int ArrayInitialize(void array[], double value)


Sets all elements of a numeric array to the same value. Returns the count of initialized
elements.
Note: It is not recommended to initialize index buffers in the custom indicator init()
function as such functions are initialized automatically with an "empty value" at
allocation and re-allocation of buffers.
Parameters:
array[] - Numeric array to be initialized.
value - New value to be set.
Sample:
//---- initializing of all array elements with 2.1
double myarray[10];
ArrayInitialize(myarray,2.1);

71
ARRAYISSERIES

bool ArrayIsSeries(object array[])


Returns TRUE if the array under check is a series array
(Time[],Open[],Close[],High[],Low[], or Volume[]), otherwise returns FALSE.
Parameters:
array[] - Array under check.
Sample:
if(ArrayIsSeries(array1)==false)
ArrayInitialize(array1,0);
else
{
Print("Series array cannot be initialized!");
return(-1);
}

ARRAYMAXIMUM

int ArrayMaximum(double array[], int count=WHOLE_ARRAY, int start=0)


Searches for the element with maximum value. The function returns position of this
maximum element in the array.
Parameters:
array[] - The numeric array to search in.
count - The amount of elements to search in.
start - Initial search index.
Sample:
double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9};
int maxValueIdx=ArrayMaximum(num_array);
Print("Max value = ", num_array[maxValueIdx]);

ARRAYMINIMUM

int ArrayMinimum(double array[], int count=WHOLE_ARRAY, int start=0)


Searches for the element with minimum value. The function returns position of this
minimum element in the array.
Parameters:
array[] - The numeric array to search in.
count - The amount of elements to search in.
start - Initial search index.
Sample:
double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9};
int minValueidx=ArrayMinimum(num_array);
Print("Min value = ", num_array[minValueIdx]);

ARRAYRANGE

int ArrayRange(object array[], int range_index)


Returns the count of elements in the given dimension of the array. Since indexes are
zero-based, the size of dimension is 1 greater than the largest index.

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

int ArrayResize(void array[], int new_size)


Sets a new size for the first dimension. If executed successfully, it returns count of all
elements contained in the array after resizing, otherwise, returns -1, and array is not
resized.
Note: Array declared at a local level in a function and resized will remain unchanged
after the function has completed its operation. After the function has been recalled, such
array will have a size differing from the declared one.
Parameters:
array[] - Array to resize.
new_size - New size for the first dimension.
Sample:
double array1[][4];
int element_count=ArrayResize(array1, 20);
// new size - 80 elements

ARRAYSETASSERIES

bool ArraySetAsSeries(void array[], bool set)


Sets indexing direction of the array. If the set parameter has the TRUE value, the array
will be indexed in a reversed order, i.e., the last element has a zero index. The FALSE
value sets a standard indexing order. The function returns the previous status.
Parameters:
array[] - The numeric array to set.
set - Array indexing order.
Sample:
double macd_buffer[300];
double signal_buffer[300];
int i,limit=ArraySize(macd_buffer);
ArraySetAsSeries(macd_buffer,true);

for(i=0; i<limit; i++)


macd_buffer[i]=iMA(NULL,0,12,0,MODE_EMA,PRICE_CLOSE,i)-
iMA(NULL,0,26,0,MODE_EMA,PRICE_CLOSE,i);

for(i=0; i<limit; i++)


signal_buffer[i]=iMAOnArray(macd_buffer,limit,9,0,MODE_SMA,i);

73
ARRAYSIZE

int ArraySize(object array[])


Returns the count of elements contained in the array. For a one-dimensional array, the
value to be returned by the ArraySize function is equal to that of ArrayRange(array,0).
Parameters:
array[] - Array of any type.
Sample:
int count=ArraySize(array1);
for(int i=0; i<count; i++)
{
// some calculations.
}

ARRAYSORT

int void array[], int count=WHOLE_ARRAY, int start=0,


ArraySort( int sort_dir=MODE_ASCEND)
Sorts numeric arrays by first dimension. Series arrays cannot be sorted by ArraySort().
Parameters:
array[] - The numeric array to be sorted.
count - Count of elements to be sorted.
start - Starting index.
sort_dir - Array sorting direction. It can be any of the following values:
MODE_ASCEND - sort ascending,
MODE_DESCEND - sort descending.
Sample:
double num_array[5]={4,1,6,3,9};
// now array contains values 4,1,6,3,9
ArraySort(num_array);
// now array is sorted 1,3,4,6,9
ArraySort(num_array,WHOLE_ARRAY,0,MODE_DESCEND);
// now array is sorted 9,6,4,3,1

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

Functions returning information about 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

General-purpose functions not included into any specialized groups.

ALERT

void Alert(...)
Displays a dialog box containing the user-defined data. Parameters can be of any type.
Amount of passed parameters cannot exceed 64.

Arrays cannot be passed to the Alert function. Arrays should be output elementwise.

Data of double type output with 4 decimal digits after point. To output with more
precision use DoubleToStr() function.
Data of bool, datetime and color types will be output as its numeric presentation.
To output values of datetime type as string convert it by TimeToStr() function.
See also Comment() and Print() functions.
Parameters:
... - Any values, separated by commas. It can be up to 64 parameters.
Sample:
if(Close[0]>SignalLevel)
Alert("Close price coming ", Close[0],"!!!");

COMMENT

void Comment(...)
The function outputs the comment defined by the user in the left top corner of the chart.
Parameters can be of any type. Amount of passed parameters cannot exceed 64.

Arrays cannot be passed to the Comment() function. Arrays should be output


elementwise.

Data of double type output with 4 digits after the decimal point. To output with more
precision, use the DoubleToStr() function.
Data of bool, datetime and color types will be output as their numeric presentation.
To output values of datetime type as strings, convert them with the TimeToStr()
function.
See also Alert() and Print() functions.
Parameters:
... - =Any values separated by commas. It can be up to 64 parameters.
Sample:
double free=AccountFreeMargin();
Comment("Account free margin is ",DoubleToStr(free,2),"\n","Current
time is ",TimeToStr(TimeCurrent()));

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

double MarketInfo(string symbol, int type)


Returns various data about securities listed in the Market Watch window. A part of
information about the current security is stored in predefined variables.
Parameters:
symbol - Security symbol.
type - Request identifier that defines the type of information to be returned. Can
be any of values of request identifiers.
Sample:
double bid =MarketInfo("EURUSD",MODE_BID);
double ask =MarketInfo("EURUSD",MODE_ASK);
double point =MarketInfo("EURUSD",MODE_POINT);
int digits=MarketInfo("EURUSD",MODE_DIGITS);
int spread=MarketInfo("EURUSD",MODE_SPREAD);

MESSAGEBOX

int MessageBox(string text=NULL, string caption=NULL, int flags=EMPTY)


The MessageBox function creates, displays, and operates message box. The message
box contains an application-defined message and header, as well as a random
combination of predefined icons and push buttons. If the function succeeds, the returned
value is one of the MessageBox return code values.
The function cannot be called from custom indicators since they are executed within
interface thread and may not decelerate it.
Parameters:
text - Optional text that contains the message to be displayed.
caption - Optional text to be displayed in the header of the dialog box. If this
parameter is NULL, the expert name will be displayed in the header.
flags - Optional flags that determine the type and behavior of the dialog box.
They can represent a conbination of flags from the following groups.
Sample:
#include <WinUser32.mqh>

if(ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30',


1.0045)==false)
{
int ret=MessageBox(" ObjectCreate() function returned the
"+GetLastError()+" error\nContinue?", "Question",
MB_YESNO|MB_ICONQUESTION);

81
if(ret==IDNO) return(false);
}
// continue

PLAYSOUND

void PlaySound(string filename)


Function plays a sound file. The file must be located in the terminal_dir\sounds
directory or in its subdirectory.
Parameters:
filename - Path to the sound file.
Sample:
if(IsDemo()) PlaySound("alert.wav");

PRINT

void Print(...)
Prints a message to the experts log. Parameters can be of any type. Amount of passed
parameters cannot exceed 64.

Arrays cannot be passed to the Print() function. Arrays should be printed elementwise.

Data of double type are printed with 4 decimal digits after point. To output more
precisely, use the DoubleToStr() function.
Data of bool, datetime and color types will be printed as their numeric presentation.
To print values of datetime type as string, convert them with the TimeToStr() function.
See also Alert() and Comment() functions.
Parameters:
... - Any values separated by commas. It can be up to 64 parameters.
Sample:
Print("Account free margin is ", AccountFreeMargin());
Print("Current time is ", TimeToStr(TimeCurrent()));
double pi=3.141592653589793;
Print("PI number is ", DoubleToStr(pi,8));
// Output: PI number is 3.14159265
// Array printing
for(int i=0;i<10;i++)
Print(Close[i]);

SENDFTP

bool SendFTP(string filename, string ftp_path=NULL)


Sends the file to the FTP server set in the Tools->Options->Publisher tab. If the attempt
fails, it retuns FALSE.
The function does not operate in the testing mode. This function cannot be called from
custom indicators, either.
The file to be sent must be stored in the terminal_directory\experts\files folder or in its
sub-folders.
It will not be sent if there is no FTP address and/or access password specified in
settings.

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

void SendMail(string subject, string some_text)


Sends a message to the e-mail set in the Tools->Options->EMail tab.
The sending can be disabled in settings, or it can be omitted to specify the e-mail
address. To get the detailed error information, one has to call the GetLastError()
function.
Parameters:
subject - Subject text.
some_text - Mail body.
Sample:
double lastclose=Close[0];
if(lastclose<my_signal)
SendMail("from your expert", "Price dropped down to
"+DoubleToStr(lastclose,Digits));

SLEEP

void Sleep(int milliseconds)


The Sleep() function suspends execution of the current expert within the specified
interval.
The Sleep() function cannot be called from custom indicators since they calculate in the
interface thread and may not decelerate it.
The checking of the expert stop flag status every 0.1 second has been built into the
function.
Parameters:
milliseconds - Sleeping interval in milliseconds.
Sample:
//---- wait for 10 seconds
Sleep(10000);

83
CONVERSION FUNCTIONS

A group of functions that provide conversion of data from one format into another.

The NormalizeDouble() function must be specially noted as it provides the necessary


accuracy of the price presentation. In trading operations, no unnormalized prices may be
used if their accuracy even a digit exceeds that required by the trade server.

CHARTOSTR

string CharToStr(int char_code)


Conversion of the symbol code into a one-character string.
Parameters:
char_code - ASCII char code.
Sample:
string str="WORL" + CharToStr(44); // 44 is code for 'D'
// the resulting string will be WORLD

DOUBLETOSTR

string DoubleToStr(double value, int digits)


Returns text string with the specified numerical value converted into a specified
precision format.
Parameters:
value - Floating point value.
digits - Precision format, number of digits after decimal point (0-8).
Sample:
string value=DoubleToStr(1.28473418, 5);
// the value is "1.28473"

NORMALIZEDOUBLE

double NormalizeDouble(double value, int digits)


Rounds the floating point value to the given precision. Returns normalized value of the
double type.
The calculated StopLoss and TakeProfit values, as well as open price of pending orders
must be normalized with a precision the value of which is stored in the pre-defined
variable of Digits.
Parameters:
value - Floating point value.
digits - Precision format, number of digits after decimal point (0-8).
Sample:
double var1=0.123456789;
Print(DoubleToStr(NormalizeDouble(var1,5),8));
// output: 0.12346000

84
STRTODOUBLE

double StrToDouble(string value)


Converts string representation of number to double type (double-precision format with
floating point).
Parameters:
value - String containing the number character representation format.
Sample:
double var=StrToDouble("103.2812");

STRTOINTEGER

int StrToInteger(string value)


Converts string containing the value character representation into a value of the int
(integer) type.
Parameters:
value - String containing the integer character representation format.
Sample:
int var1=StrToInteger("1024");

STRTOTIME

datetime StrToTime(string value)


Converts string in the format "yyyy.mm.dd hh:mi" to datetime type (the amount of
seconds that have passed since 1 Jan., 1970).
Parameters:
value - String value of date/time format as "yyyy.mm.dd hh:mi".
Sample:
datetime var1;
var1=StrToTime("2003.8.12 17:35");
var1=StrToTime("17:35"); // returns the current date with the
given time
var1=StrToTime("2003.8.12"); // returns the date with the midnight
time of "00:00"

TIMETOSTR

string TimeToStr(datetime value, int mode=TIME_DATE|TIME_MINUTES)


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

85
CUSTOM INDICATORS

A group of functions used at producing of custom indicators.

These functions cannot be used in experts and scripts.

INDICATORBUFFERS

void IndicatorBuffers(int count)


Allocates memory for buffers used for custom indicator calculations. The amount of
buffers cannot exceed 8 or be less than the value given in the indicator_buffers property.
If custom indicator requires additional buffers for counting, this function must be used
for specifying of the total amount of buffers.
Parameters:
count - Amount of buffers to be allocated. Should be within the range between
indicator_buffers and 8 buffers.
Sample:
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//---- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//---- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}

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

void IndicatorDigits(int digits)


Sets precision format (the count of digits after decimal point) to visualize indicator
values. The symbol price preicision is used by default, the indicator being attached to
this symbol chart.
Parameters:
digits - Precision format, the count of digits after decimal point.
Sample:
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- setting of drawing parameters
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(Digits+2);
//---- 3 allocated buffers of an indicator
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);

87
//---- "short name" for DataWindow and indicator subwindow
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}

INDICATORSHORTNAME

void IndicatorShortName(string name)


Sets the "short" name of a custom indicator to be shown in the DataWindow and in the
chart subwindow.
Parameters:
name - New short name.
Sample:
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}

SETINDEXARROW

void SetIndexArrow(int index, int code)


Sets an arrow symbol for indicators line of the DRAW_ARROW type.
Arrow codes out of range 33 to 255 cannot be used.
Parameters:
index - Line index. Must lie between 0 and 7.
code - Symbol code from Wingdings font or Array constants.
Sample:
int init()
{
//---- 2 allocated indicator buffers
SetIndexBuffer(0,ExtUppperBuffer);
SetIndexBuffer(1,ExtLowerBuffer);
//---- drawing parameters setting
SetIndexStyle(0,DRAW_ARROW);
SetIndexArrow(0,217);
SetIndexStyle(1,DRAW_ARROW);
SetIndexArrow(1,218);
//---- displaying in the DataWindow
SetIndexLabel(0,"Fractal Up");
SetIndexLabel(1,"Fractal Down");
//---- initialization done

88
return(0);
}

SETINDEXBUFFER

bool SetIndexBuffer(int index, double array[])


Binds the array variable declared at a global level to the custom indicator pre-defined
buffer. The amount of buffers needed to calculate the indicator is set with
the IndicatorBuffers() function and cannot exceed 8. If it succeeds, TRUE will be
returned, otherwise, it will be FALSE. To get the extended information about the error,
one has to call the GetLastError() function.
Parameters:
index - Line index. Must lie between 0 and 7.
array[] - Array that stores calculated indicator values.
Sample:
double ExtBufferSilver[];
int init()
{
SetIndexBuffer(0, ExtBufferSilver); // first line buffer
// ...
}

SETINDEXDRAWBEGIN

void SetIndexDrawBegin(int index, int begin)


Sets the bar number (from the data beginning) from which the drawing of the given
indicator line must start. The indicators are drawn from left to right. The indicator array
values that are to the left of the given bar will not be shown in the chart or in the
DataWindow. 0 will be set as default, and all data will be drawn.
Parameters:
index - Line index. Must lie between 0 and 7.
begin - First drawing bar position number.
Sample:
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}

89
SETINDEXEMPTYVALUE

void SetIndexEmptyValue(int index, double value)


Sets drawing line empty value. Empty values are not drawn or shown in the
DataWindow. By default, empty value is EMPTY_VALUE.
Parameters:
index - Line index. Must lie between 0 and 7.
value - New "empty" value.
Sample:
int init()
{
//---- 2 allocated indicator buffers
SetIndexBuffer(0,ExtUppperBuffer);
SetIndexBuffer(1,ExtLowerBuffer);
//---- drawing parameters setting
SetIndexStyle(0,DRAW_ARROW);
SetIndexArrow(0,217);
SetIndexStyle(1,DRAW_ARROW);
SetIndexArrow(1,218);
//---- 0 value will not be displayed
SetIndexEmptyValue(0,0.0);
SetIndexEmptyValue(1,0.0);
//---- displaying in DataWindow
SetIndexLabel(0,"Fractal Up");
SetIndexLabel(1,"Fractal Down");
//---- initialization done
return(0);
}

SETINDEXLABEL

void SetIndexLabel(int index, string text)


Sets drawing line description for showing in the DataWindow and in the tooltip.
Parameters:
index - Line index. Must lie between 0 and 7.
text - Label text. NULL means that index value is not shown in the DataWindow.
Sample:
//+------------------------------------------------------------------+
//| Ichimoku Kinko Hyo initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,Tenkan_Buffer);
SetIndexDrawBegin(0,Tenkan-1);
SetIndexLabel(0,"Tenkan Sen");
//----
SetIndexStyle(1,DRAW_LINE);
SetIndexBuffer(1,Kijun_Buffer);
SetIndexDrawBegin(1,Kijun-1);
SetIndexLabel(1,"Kijun Sen");
//----
a_begin=Kijun; if(a_begin<Tenkan) a_begin=Tenkan;
SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_DOT);

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

void SetIndexShift(int index, int shift)


Sets offset for the drawing line. For positive values, the line drawing will be shifted to
the right, otherwise it will be shifted to the left. I.e., the value calculated on the current
bar will be drawn shifted relatively to the current bar.
Parameters:
index - Line index. Must lie between 0 and 7.
shift - Shitf value in bars.
Sample:
//+------------------------------------------------------------------+
//| Alligator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- line shifts when drawing
SetIndexShift(0,JawsShift);
SetIndexShift(1,TeethShift);
SetIndexShift(2,LipsShift);
//---- first positions skipped when drawing
SetIndexDrawBegin(0,JawsShift+JawsPeriod);
SetIndexDrawBegin(1,TeethShift+TeethPeriod);
SetIndexDrawBegin(2,LipsShift+LipsPeriod);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ExtBlueBuffer);
SetIndexBuffer(1,ExtRedBuffer);

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

void int index, int type, int style=EMPTY, int width=EMPTY,


SetIndexStyle( color clr=CLR_NONE)
Sets the new type, style, width and color for a given indicator line.
Parameters:
index - Line index. Must lie between 0 and 7.
type - Shape style. Can be one of Drawing shape styles listed.
style - Drawing style. It is used for one-pixel thick lines. It can be one of
the Drawing shape styles listed. EMPTY value means that the style will not
be changed.
width - Line width. Valid values are: 1,2,3,4,5. EMPTY value means that width will
not be changed.
clr - Line color. Absence of this parameter means that the color will not be
changed.
Sample:
SetIndexStyle(3, DRAW_LINE, EMPTY, 2, Red);

SETLEVELSTYLE

void SetLevelStyle(int draw_style, int line_width, color clr=CLR_NONE)


The function sets a new style, width and color of horizontal levels of indicator to be
output in a separate window.
Parameters:
draw_style - Drawing style. Can be one of the Drawing shape styles listed. EMPTY
value means that the style will not be changed.
line_width - Line width. Valid values are 1,2,3,4,5. EMPTY value indicates that the
width will not be changed.
clr - Line color. Empty value CLR_NONE means that the color will not be
changed.
Sample:
//---- show levels as thick red lines
SetLevelStyle(STYLE_SOLID,2,Red)

92
SETLEVELVALUE

void SetLevelValue(int level, double value)


The function sets a value for a given horizontal level of the indicator to be output in a
separate window.
Parameters:
level - Level index (0-31).
value - Value for the given indicator level.
Sample:
SetLevelValue(1,3.14);

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.

Note: At the testing, the last known server time is modelled.


Sample:
if(TimeCurrent()-OrderOpenTime()<360) return(0);

TIMEDAY

int TimeDay(datetime date)


Returns day of month (1 - 31) for the specified date.
Parameters:
date - Datetime as number of seconds elapsed since midnight (00:00:00), January 1,
1970.
Sample:
int day=TimeDay(D'2003.12.31');
// day is 31

TIMEDAYOFWEEK

int TimeDayOfWeek(datetime date)


Returns the zero-based day of week (0 means Sunday,1,2,3,4,5,6) for the specified date.
Parameters:

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

int TimeDayOfYear(datetime date)


Returns day (1 means 1 January,..,365(6) does 31 December) of year for the specified
date.
Parameters:
date - Datetime as number of seconds elapsed since midnight (00:00:00), January 1,
1970.
Sample:
int day=TimeDayOfYear(TimeCurrent());

TIMEHOUR

int TimeHour(datetime time)


Returns the hour for the specified time.
Parameters:
time - Datetime is the number of seconds elapsed since midnight (00:00:00), January
1, 1970.
Sample:
int h=TimeHour(TimeCurrent());

TIMELOCAL

datetime TimeLocal()
Returns local computer time as number of seconds elapsed from 00:00 January 1, 1970.
Note: At the testing, local time is modelled and is the same as the modelled last known
server time.
Sample:
if(TimeLocal()-OrderOpenTime()<360) return(0);

TIMEMINUTE

int TimeMinute(datetime time)


Returns the minute for the specified time.
Parameters:
time - Datetime as number of seconds elapsed since midnight (00:00:00), January 1,
1970.
Sample:
int m=TimeMinute(TimeCurrent());

96
TIMEMONTH

int TimeMonth(datetime time)


Returns the month number for the specified time.
Parameters:
time - Datetime as number of seconds elapsed since midnight (00:00:00), January 1,
1970.
Sample:
int m=TimeMonth(TimeCurrent());

TIMESECONDS

int TimeSeconds(datetime time)


Returns the amount of seconds elapsed from the beginning of the minute for the
specified time.
Parameters:
time - Datetime as number of seconds elapsed since midnight (00:00:00), January 1,
1970.
Sample:
int m=TimeSeconds(TimeCurrent());

TIMEYEAR

int TimeYear(datetime time)


Returns year for the specified date. The returned value can be within the range of 1970
to 2037.
Parameters:
time - Datetime as number of seconds elapsed since midnight (00:00:00), January 1,
1970.
Sample:
int y=TimeYear(TimeCurrent());

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

A group of functions for working with files.

There are three directories (with subdirectories) where working files can be placed:

• /HISTORY/<current broker> - especially for the FileOpenHistory function;


• /EXPERTS/FILES - common case;
• /TESTER/FILES - especially for testing.

Working with files from other directories is prohibited.

FILECLOSE

void FileClose(int handle)


Closes file previously opened by the FileOpen() function.
Parameters:
handle - File handle returned by the FileOpen() function
Sample:
int handle=FileOpen("filename", FILE_CSV|FILE_READ);
if(handle>0)
{
// working with file ...
FileClose(handle);
}

FileDelete

void FileDelete(string filename)


Removes specified file name. To get the detailed error information, call GetLastError().
Files can only be deleted if they are in the terminal_dir\experts\files directory
(terminal_directory\tester\files, in case of testing) or its subdirectories.
Parameters:
filename - Path to the file.
Sample:
// file my_table.csv will be deleted from terminal_dir\experts\files
directory
int lastError;
FileDelete("my_table.csv");
lastError=GetLastError();
if(laseError!=ERR_NOERROR)
{
Print("An error ocurred while (",lastError,") deleting file
my_table.csv");
return(0);
}

98
FILEFLUSH

void FileFlush(int handle)


Flushes all data stored in the file buffer to the disk.
Notes: The FileFlush() function must be called between operations of file reading and
writing in the file.
At file closing, the data are flushed to the disk automatically, so there is no need to call
the FileFlush() function before calling of the FileClose() function.
Parameters:
handle - File handle, returned by FileOpen() functions.
Sample:
int bars_count=Bars;
int handle=FileOpen("mydat.csv",FILE_CSV|FILE_WRITE);
if(handle>0)
{
FileWrite(handle, "#","OPEN","CLOSE","HIGH","LOW");
for(int i=0;i<bars_count;i++)
FileWrite(handle, i+1,Open[i],Close[i],High[i], Low[i]);
FileFlush(handle);
...
for(int i=0;i<bars_count;i++)
FileWrite(handle, i+1,Open[i],Close[i],High[i], Low[i]);
FileClose(handle);
}

FILEISENDING

bool FileIsEnding(int handle)


Returns logical true if file pointer is at the end of the file, otherwise returns false. To get
the detailed error information, call GetLastError() function. If the file end is reached
during reading, the GetLastError() function will return error ERR_END_OF_FILE
(4099).
Parameters:
handle - File handle, returned by FileOpen() functions.
Sample:
if(FileIsEnding(h1))
{
FileClose(h1);
return(false);
}

FILEISLINEENDING

bool FileIsLineEnding(int handle)


For CSV file returns logical true if file pointer is at the end of the line, otherwise returns
false. To get the detailed error information, call GetLastError() function.
Parameters:
handle - File handle, returned by FileOpen() function.
Sample:
if(FileIsLineEnding(h1))
{
FileClose(h1);

99
return(false);
}

FILEOPEN

int FileOpen(string filename, int mode, int delimiter=';')


Opens file for input and/or output. Returns a file handle for the opened file or -1 (if the
function fails). To get the detailed error information, call GetLastError() function.
Notes: Files can only be opened in the terminal_directory\experts\files folder
(terminal_directory\tester\files if for expert testing) or in its subfolders.
FILE_BIN and FILE_CSV modes cannot be used simultaneously.
If FILE_WRITE does not combine with FILE_READ, a zero-length file will be opened.
If even the file containd some data, they will be deleted. If there is a need to add data to
an existing file, it must be opened using combination of FILE_READ | FILE_WRITE.
If FILE_READ does not combine with FILE_WRITE, the file will be opened only if it
already exists. If the file does not exist, it can be created using the FILE_WRITE mode.
No more than 32 files can be opened within an executable module simultaneously.
Handles of files opened in the same module cannot be passed to other modules
(libraries).
Parameters:
filename - Filename.
mode - Opening mode. It can be one or combination of values: FILE_BIN,
FILE_CSV, FILE_READ, FILE_WRITE.
delimiter - Delimiter character for csv files. By default, the ';' symbol applies.
Sample:
int handle;
handle=FileOpen("my_data.csv",FILE_CSV|FILE_READ,';');
if(handle<1)
{
Print("File my_data.dat not found, the last error is ",
GetLastError());
return(false);
}

FILEOPENHISTORY

int FileOpenHistory(string filename, int mode, int delimiter=';')


Opens file in the current history directory (terminal_directory\history\server_name) or
in its subfolders. Returns the file handle for the opened file. If the function fails, the
returned value is -1. To get the detailed error information, call the GetLastError()
function.
Notes: Client terminal can connect to servers of different brokerage companies. History
data (HST files) for each brokerage company are stored in the corresponding subfolder
of the terminal_directory\history folder.
The function can be useful to form own history data for a non-standard symbol and/or
period. The file formed in the history folder can be opened offline, not data pumping is
needed to chart it.
Parameters:
filename - Filename.
mode - Opening mode. Can be one or combination of values: FILE_BIN,

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

int FileReadArray(int handle, void array[], int start, int count)


Reads the specified amount of elements from the binary file into array. Before reading,
make sure that the array is large enough. Returns the amount of actually read elements.
To get the detailed error information, call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
array[] - Array where data will be stored.
start - Starting position for storing in array.
count - Count of elements to be read.
Sample:
int handle;
double varray[10];
handle=FileOpen("filename.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
FileReadArray(handle, varray, 0, 10);
FileClose(handle);
}

FILEREADDOUBLE

double FileReadDouble(int handle, int size=DOUBLE_VALUE)


Reads the double-precision number with floating point from the current binary file
position. The number format size can be 8 bytes (double) or 4 bytes (float).
To get the error information, one has to call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
size - Number format size. Can be DOUBLE_VALUE(8 bytes) or
FLOAT_VALUE(4 bytes).
Sample:
int handle;
double value;
handle=FileOpen("mydata.dat",FILE_BIN);
if(handle>0)
{
value=FileReadDouble(handle,DOUBLE_VALUE);

101
FileClose(handle);
}

FILEREADINTEGER

int FileReadInteger(int handle, int size=LONG_VALUE)


The function reads the integer from the current binary file position. The integer format
size can be 1, 2 or 4 bytes. If the format size is not specified, the system tries to read the
4-bytes value. To get the detailed error information, one has to call the GetLastError()
function.
Parameters:
handle - File handle returned by the FileOpen() function.
size - Format size. Can be CHAR_VALUE(1 byte), SHORT_VALUE(2 bytes) or
LONG_VALUE(4 bytes).
Sample:
int handle;
int value;
handle=FileOpen("mydata.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
value=FileReadInteger(h1,2);
FileClose(handle);
}

FILEREADNUMBER

double FileReadNumber(int handle)


Read the number from the current file position before the delimiter. Only for CSV files.
To get the detailed error information, one has to call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
Sample:
int handle;
int value;
handle=FileOpen("filename.csv", FILE_CSV, ';');
if(handle>0)
{
value=FileReadNumber(handle);
FileClose(handle);
}

FILEREADSTRING

string FileReadString(int handle, int length=0)


The function reads the string from the current file position. Applies to both CSV and
binary files. For text files, the string will be read before the delimiter. For binary file,
the given count of characters will be read to the string. To get the detailed error
information, one has to call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.

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

bool FileSeek(int handle, int offset, int origin)


The function moves the file pointer to a new position that is an offset, in bytes, from the
beginning, the end or the current file position. The next reading or writing are made at a
new position.
If file pointer has been moved successfully, the function returns TRUE, otherwise, it
returns FALSE. To get the detailed error information, one has to call the GetLastError()
function.
Parameters:
handle - File handle returned by the FileOpen() functions.
offset - Offset, in bytes, from origin.
origin - Initial position. Value can be one of the following constants:
SEEK_CUR - from current position,
SEEK_SET - from begin,
SEEK_END - from end of file.
Sample:
int handle=FileOpen("filename.csv", FILE_CSV|FILE_READ|FILE_WRITE,
';');
if(handle>0)
{
FileSeek(handle, 0, SEEK_END);
//---- add data to the end of file
FileWrite(handle, data1, data2);
FileClose(handle);
handle=0;
}

FILESIZE

int FileSize(int handle)


The function returns file size in bytes. To get the detailed error information, one has to
call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
Sample:
int handle;
int size;
handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ);
if(handle>0)
{

103
size=FileSize(handle);
Print("my_table.dat size is ", size, " bytes");
FileClose(handle);
}

FILETELL

int FileTell(int handle)


Returns the current position of the file pointer. To get the detailed error information,
one has to call GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
Sample:
int handle;
int pos;
handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ);
// reading some data
pos=FileTell(handle);
Print("current position is ", pos);

FILEWRITE

int FileWrite(int handle, ...)


The function is intended for writing of data into a CSV file, delimiter being inserted
automatically. After writing into the file, the line end character "\r\n" will be added.
Numbers will be converted into a text at output (see the Print() function).
Returns the count of written characters or a negative number if an error occurs.
To get the detailed error information, one has to call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
... - User data to write, separated by commas. It can be up to 63 parameters.
Data of int and double types are automatically converted into a string, but
those of color, datetime and bool typesare not automatically converted and
will be written to file as they are (as integers).
Arrays cannot be passed as a parameter, they can be output elementwise.
Sample:
int handle;
datetime orderOpen=OrderOpenTime();
handle=FileOpen("filename", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
FileWrite(handle, Close[0], Open[0], High[0], Low[0],
TimeToStr(orderOpen));
FileClose(handle);
}

FILEWRITEARRAY

int FileWriteArray(int handle, object array[], int start, int count)


The function writes the array to a binary file. Arrays of int, bool, datetime and color
types will be written elementwise, as 4-bytes integers. Arrays of double type will be

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

int FileWriteDouble(int handle, double value, int size=DOUBLE_VALUE)


The function writes a double value with floating point to a binary file. If the format is
specified as FLOAT_VALUE, the value will be written as a 4-bytes floating point
number (of the float type), otherwise, it will be written in the 8-bytes floating point
format (of the double type).
Returns the actually written bytes count or a negative value if an error occurs.
To get the detailed error information, one has to call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
value - Double precision value.
size - Optional format flag. It can be any of the following values:
DOUBLE_VALUE (8 bytes, default)
FLOAT_VALUE (4 bytes).
Sample:
int handle;
double var1=0.345;
handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("can't open file error-",GetLastError());
return(0);
}
FileWriteDouble(h1, var1, DOUBLE_VALUE);
//...
FileClose(handle);

105
FILEWRITEINTEGER

int FileWriteInteger(int handle, int value, int size=LONG_VALUE)


The function writes the integer value to a binary file. If the size is SHORT_VALUE, the
value will be written as a 2-byte integer (the short type), if the size is CHAR_VALUE,
the value will be written as a 1-byte integer (the char type), and if the size is
LONG_VALUE, the value will be written as a 4-byte integer (the long int type).
Returns the actually written bytes count or a negative value if an error occurs.
To get the detailed error information, one has to call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
value - Value to be written.
size - Optional format flag. It can be any of the following values:
CHAR_VALUE (1 byte),
SHORT_VALUE (2 bytes),
LONG_VALUE (4 bytes, default).
Sample:
int handle;
int value=10;
handle=FileOpen("filename.dat", FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("can't open file error-",GetLastError());
return(0);
}
FileWriteInteger(handle, value, SHORT_VALUE);
//...
FileClose(handle);

FILEWRITESTRING

int FileWriteString(int handle, string value, int length)


The function writes the string to a binary file from the current file position.
Returns the actually written bytes count or a negative value if an error occurs.
To get the detailed error information, one has to call the GetLastError() function.
Parameters:
handle - File handle returned by the FileOpen() function.
value - String to be written.
length - The length of the string to be written. If the string length exceeds the given
value, it will be truncated. If it is shorter, it will be extended by binary 0s
up to the given length.
Sample:
int handle;
string str="some string";
handle=FileOpen("filename.bin", FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("can't open file error-",GetLastError());
return(0);
}
FileWriteString(handle, str, 8);
FileClose(handle);

106
GLOBAL VARIABLES

A group of functions intended for working with global variables.

Global variables of the client terminal should not be mixed up with variables declared in
the global scope of the MQL4 program.

Global variables are kept in the client terminal within 4 weeks since the last access, then
they will be deleted 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

bool GlobalVariableCheck(string name)


Returns TRUE if the global variable exists, otherwise, returns FALSE. To get the
detailed error information, one has to call the GetLastError() function.
Parameters:
name - Global variable name.
Sample:
// check variable before use
if(!GlobalVariableCheck("g1"))
GlobalVariableSet("g1",1);

GLOBALVARIABLEDEL

bool GlobalVariableDel(string name)


Deletes the global variable. If the function succeeds, the returned value will be TRUE,
otherwise, it will be FALSE. To get the detailed error information, one has to call
the GetLastError() function.
Parameters:
name - Global variable name.
Sample:
// deleting of the global variable named "gvar_1"
GlobalVariableDel("gvar_1");

GLOBALVARIABLEGET

double GlobalVariableGet(string name)


Returns the value of an existing global variable or 0 if an error occurs. To get the
detailed error information, one has to call the GetLastError() function.
Parameters:
name - Global variable name.
Sample:
double v1=GlobalVariableGet("g1");
//---- check function call result
if(GetLastError()!=0) return(false);

107
//---- continue processing

GLOBALVARIABLENAME

string GlobalVariableName(int index)


The function returns the name of a global variable by its index in the list of global
variables. To get the detailed error information, one has to call the GetLastError().
Parameters:
index - Index in the list of global variables. It must exceed or be equal to 0 and be
less than GlobalVariablesTotal().
Sample:
int var_total=GlobalVariablesTotal();
string name;
for(int i=0;i<var_total;i++)
{
name=GlobalVariableName(i);
Print(i,": Global variable name - ",name);
}

GLOBALVARIABLESET

datetime GlobalVariableSet(string name, double value)


Sets a new value of the global variable. If it does not exist, the system creates a new
gloabl variable. If the function succeeds, the returned value will be the last access time.
Otherwise, the returned value will be 0. To get the detailed error information, one has to
call the GetLastError() function.
Parameters:
name - Global variable name.
value - The new numeric value.
Sample:
//---- try to set new value
if(GlobalVariableSet("BarsTotal",Bars)==0)
return(false);
//---- continue processing

GLOBALVARIABLESETONCONDITION

bool GlobalVariableSetOnCondition(string name, double value, double check_value)


Sets the new value of the existing global variable if the current value equals to the third
parameter check_value. If there is no global variable, the function will generate error
ERR_GLOBAL_VARIABLE_NOT_FOUND (4058) and return FALSE. When
successfully executed, the function returns TRUE, otherwise, it returns FALSE. To get
the detailed error information, one has to call the GetLastError() function.
If the current value of the global variable differs from the check_value, the function will
return FALSE.
The function provides atomic access to the global variable, this is why it can be used for
providing of a semaphore at interaction of several experts working simultaneously
within one client terminal.
Parameters:
name - Global variable name.

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

int GlobalVariablesDeleteAll(string prefix_name=NULL)


Deletes global variables. If the name prefix is not specified, all global variables will be
deleted. Otherwise, only those variables will be deleted, the names of which begin with
the specified prefix. The function returns the count of deleted variables.
Parameters:
prefix_name - Name prefix of the global variables to be deleted.
Sample:
Print(GlobalVariablesDeleteAll("test_")," test globals deleted");

GLOBALVARIABLESTOTAL

int GlobalVariablesTotal()
The function returns the total count of global variables.
Sample:
Print(GlobalVariablesTotal()," global variables detected");

109
MATH & TRIG

A set of mathematical and trigonometric functions.

MATHABS

double MathAbs(double value)


Returns the absolute value (modulus) of the specified numeric value.
Parameters:
value - Numeric value.
Sample:
double dx=-3.141593, dy;
// calc MathAbs
dy=MathAbs(dx);
Print("The absolute value of ",dx," is ",dy);
// Output: The absolute value of -3.141593 is 3.141593

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

double MathCos(double value)


Returns the cosine of the specified angle.
Parameters:
value - An angle measured in radians.
Sample:
double pi=3.1415926535;
double x, y;
x=pi/2;
y=MathSin(x);
Print("MathSin(",x,") = ",y);
y=MathCos(x);
Print("MathCos(",x,") = ",y);
//Output: MathSin(1.5708)=1
// MathCos(1.5708)=0

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

double MathMax(double value1, double value2)


Returns the maximum value of two numeric values.
Parameters:
value1 - The first numeric value.
value2 - The second numeric value.
Sample:
double result=MathMax(1.08,Bid);

112
MATHMIN

double MathMin(double value1, double value2)


Returns the minimum value of two numeric values.
Parameters:
value1 - The first numeric value.
value2 - The second numeric value.
Sample:
double result=MathMin(1.08,Ask);

MATHMOD

double MathMod(double value, double value2)


The function returns the floating-point remainder of division of two numbers.

The MathMod function calculates the floating-point remainder f of x / y such that


x = i * y + f , where i is an integer, f has the same sign as x, and the absolute value of
f is less than the absolute value of y.
Parameters:
value - Dividend value.
value2 - Divisor value.
Sample:
double x=-10.0,y=3.0,z;
z=MathMod(x,y);
Print("The remainder of ",x," / ",y," is ",z);
//Output: The remainder of -10 / 3 is -1

MATHPOW

double MathPow(double base, double exponent)


Returns the value of the base expression raised to the specified power (exponent value).
Parameters:
base - Base value.
exponent - Exponent value.
Sample:
double x=2.0,y=3.0,z;
z=MathPow(x,y);
Printf(x," to the power of ",y," is ", z);
//Output: 2 to the power of 3 is 8

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

double MathRound(double value)


Returns value rounded to the nearest integer of the specified numeric value.
Parameters:
value - Numeric value to be rounded.
Sample:
double y=MathRound(2.8);
Print("The round of 2.8 is ",y);
y=MathRound(2.4);
Print("The round of -2.4 is ",y);
//Output: The round of 2.8 is 3
// The round of -2.4 is -2

MATHSIN

double MathSin(double value)


Returns the sine of the specified angle.
Parameters:
value - An angle measured in radians.
Sample:
double pi=3.1415926535;
double x, y;
x=pi/2;
y=MathSin(x);
Print("MathSin(",x,") = ",y);
y=MathCos(x);
Print("MathCos(",x,") = ",y);
//Output: MathSin(1.5708)=1
// MathCos(1.5708)=0

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

void MathSrand(int seed)


The MathSrand() function sets the starting point for generating a series of
pseudorandom integers. To reinitialize the generator, use 1 as the seed argument. Any
other value for seed sets the generator to a random starting point. MathRand retrieves
the pseudorandom numbers that are generated. Calling MathRand before any call to
MathSrand generates the same sequence as calling MathSrand with seed passed as 1.
Parameters:
seed - Seed for random-number generation.
Sample:
MathSrand(TimeLocal());
// Display 10 numbers.
for(int i=0;i<10;i++ )
Print("random value ", MathRand());

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

bool ObjectDelete(string name)


Deletes object having the specified name. If the function succeeds, the returned value
will be TRUE. Otherwise, it will be FALSE.
To get the detailed error information, one has to call the GetLastError() function.
Parameters:
name - Name of the object to be deleted.
Sample:
ObjectDelete("text_object");

OBJECTDESCRIPTION

string ObjectDescription(string name)


Return object description. For objects of OBJ_TEXT and OBJ_LABEL types, the text
drawn by these objects will be returned.
To get the detailed error information, one has to call the GetLastError() function.
See also ObjectSetText() function.
Parameters:
name - Object name.
Sample:
// writing the chart objects list to the file
int handle, total;
string obj_name,fname;
// file name
fname="objlist_"+Symbol();
handle=FileOpen(fname,FILE_CSV|FILE_WRITE);
if(handle!=false)
{
total=ObjectsTotal();
for(int i=-;i<total;i++)
{
obj_name=ObjectName(i);
FileWrite(handle,"Object "+obj_name+" description=
"+ObjectDescription(obj_name));
}
FileClose(handle);
}

OBJECTFIND

int ObjectFind(string name)


Search for an object having the specified name. The function returns index of the
windows that contains the object to be found. If it fails, the returned value will be -1. To
get the detailed error information, one has to call the GetLastError() function. The chart
sub-windows (if there are sub-windows with indicators in the chart) are numbered
starting from 1. The chart main window always exists and has the 0 index.
Parameters:
name - Object name to search for.
Sample:
if(ObjectFind("line_object2")!=win_idx) return(0);

117
OBJECTGET

double ObjectGet(string name, int index)


The function returns the value of the specified object property. To check errors, one has
to call the GetLastError() function.
See also ObjectSet() function.
Parameters:
name - Object name.
index - Object property index. It can be any of the Object properties enumeration
values.
Sample:
color oldColor=ObjectGet("hline12", OBJPROP_COLOR);

OBJECTGETFIBODESCRIPTION

string ObjectGetFiboDescription(string name, int index)


The function returns the level description of a Fibonacci object. The amount of
Fibonacci levels depends on the object type. The maximum amount of Fibonacci levels
is 32.
To get the detailed error information, one has to call the GetLastError() function.
See also ObjectSetFiboDescription() function.
Parameters:
name - Fibonacci object name.
index - Index of the Fibonacci level (0-31).
Sample:
#include <stdlib.mqh>
...
string text;
for(int i=0;i<32;i++)
{
text=ObjectGetFiboDescription(MyObjectName,i);
//---- checking whether the objects has less than 32 levels
if(GetLastError()!=ERR_NO_ERROR) break;
Print(MyObjectName,"level: ",i," description: ",text);
}

OBJECTGETSHIFTBYVALUE

int ObjectGetShiftByValue(string name, double value)


The function calculates and returns bar index (shift related to the current bar) for the
given price. The bar index is calculated by the first and second coordinates using a
linear equation. Applied to trendlines and similar objects. To get the detailed error
information, one has to call the GetLastError() function.
See also ObjectGetValueByShift() function.
Parameters:
name - Object name.
value - Price value.
Sample:
int shift=ObjectGetShiftByValue("MyTrendLine#123", 1.34);

118
OBJECTGETVALUEBYSHIFT

double ObjectGetValueByShift(string name, int shift)


The function calculates and returns the price value for the specified bar (shift related to
the current bar). The price value is calculated by the first and second coordinates using a
linear equation. Applied to trendlines and similar objects. To get the detailed error
information, one has to call the GetLastError() function.
See also ObjectGetShiftByValue() function.
Parameters:
name - Object name
shift - Bar index.
Sample:
double price=ObjectGetValueByShift("MyTrendLine#123", 11);

OBJECTMOVE

bool ObjectMove(string name, int point, datetime time1, double price1)


The function moves an object coordinate in the chart. Objects can have from one to
three coordinates depending on their types. If the function succeeds, the returned value
will be TRUE. Otherwise, it will be FALSE. To get the detailed error information, one
has to call the GetLastError() function. The object coordinates are numbered starting
from 0.
Parameters:
name - Object name.
point - Coordinate index (0-2).
time1 - New time value.
price1 - New price value.
Sample:
ObjectMove("MyTrend", 1, D'2005.02.25 12:30', 1.2345);

OBJECTNAME

string ObjectName(int index)


The function returns the object name by its index in the objects list. To get the detailed
error information, one has to call the GetLastError() function.
Parameters:
index - Object index in the objects list. Object index must exceed or equal to 0 and
be less than ObjectsTotal().
Sample:
int obj_total=ObjectsTotal();
string name;
for(int i=0;i<obj_total;i++)
{
name=ObjectName(i);
Print(i,"Object name is " + name);
}

119
OBJECTSDELETEALL

int ObjectsDeleteAll(int window=EMPTY, int type=EMPTY)


Removes all objects of the specified type and in the specified sub-window of the chart.
The function returns the count of removed objects. To get the detailed error information,
one has to call the GetLastError() function.
Notes: The chart sub-windows (if there are sub-windows with indicators in the chart)
are numbered starting from 1. The chart main window always exists and has the 0
index. If the window index is missing or it has the value of -1, the objects will be
removed from the entire chart.
If the type value equals to -1 or this parameter is missing, all objects will be removed
from the specified sub-window.
Parameters:
window - Optional parameter. Index of the window in which the objects will be
deleted. Must exceed or equal to -1 (EMPTY, the default value) and be
less than WindowsTotal().
type - Optional parameter. An object type to be deleted. It can be any of
the Object type enumeration values or EMPTY constant to delete all
objects with any types.
Sample:
ObjectsDeleteAll(2, OBJ_HLINE); // all horizontal lines are removed
from the 2nd sub-window.
ObjectsDeleteAll(2); // all objects are removed from the
2nd sub-window.
ObjectsDeleteAll(); // all objects are removed from the
chart.

OBJECTSET

bool ObjectSet(string name, int index, double value)


Changes the value of the specified object property. If the function succeeds, the returned
value will be TRUE. Otherwise, it will be FALSE. To get the detailed error information,
one has to call the GetLastError() function.
See also ObjectGet() function.
Parameters:
name - Object name.
index - Object value index. It can be any of Object properties enumeration values.
value - New value of the given property.
Sample:
// moving the first coord to the last bar time
ObjectSet("MyTrend", OBJPROP_TIME1, Time[0]);
// setting the second fibo level
ObjectSet("MyFibo", OBJPROP_FIRSTLEVEL+1, 1.234);
// setting object visibility. object will be shown only on 15 minute
and 1 hour charts
ObjectSet("MyObject", OBJPROP_TIMEFRAMES, OBJ_PERIOD_M15 |
OBJ_PERIOD_H1);

120
OBJECTSETFIBODESCRIPTION

bool ObjectSetFiboDescription(string name, int index, string text)


The function assigns a new description to a level of a Fibonacci object. The amount of
Fibonacci levels depends on the object type. The maximum amount of Fibonacci levels
is 32.
To get the detailed error information, one has to call the GetLastError() function.
Parameters:
name - Object name.
index - Index of the Fibonacci level (0-31).
text - New description of the level.
Sample:
ObjectSetFiboDescription("MyFiboObject",2,"Second line");

OBJECTSETTEXT

bool string name, string text, int font_size, string font=NULL,


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

OBJECTSTOTAL

int ObjectsTotal(int type=EMPTY)


Returns total amount of objects of the specified type in the chart.
Parameters:
type - Optional parameter. An object type to be counted. It can be any of the Object
type enumeration values or EMPTY constant to count all objects with any
types.
Sample:
int obj_total=ObjectsTotal();
string name;
for(int i=0;i<obj_total;i++)
{

121
name=ObjectName(i);
Print(i,"Object name for object #",i," is " + name);
}

OBJECTTYPE

int ObjectType(string name)


The function returns the object type value. To get the detailed error information, one has
to call the GetLastError() function.
Parameters:
name - Object name.
Sample:
if(ObjectType("line_object2")!=OBJ_HLINE) return(0);

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

int StringFind(string text, string matched_text, int start=0)


Search for a substring. Returns the position in the string from which the searched
substring begins, or -1 if the substring has not been found.
Parameters:
text - String to search in.
matched_text - Substring to search for.
start - Position in the string to start search from.
Sample:
string text="The quick brown dog jumps over the lazy fox";
int index=StringFind(text, "dog jumps over", 0);
if(index!=16)
Print("oops!");

STRINGGETCHAR

int StringGetChar(string text, int pos)


Returns character (code) from the specified position in the string.
Parameters:
text - String
pos - Char position in the string. Can be from 0 to StringLen(text)-1.

123
Sample:
int char_code=StringGetChar("abcdefgh", 3);
// char code 'c' is 99

STRINGLEN

int StringLen(string text)


Returns character count in a string.
Parameters:
text - String where the length must be calculated.
Sample:
string str="some text";
if(StringLen(str)<5) return(0);

STRINGSETCHAR

string StringSetChar(string text, int pos, int value)


Returns the string copy with changed character in the specified position.
Parameters:
text - String where character will be changed.
pos - The character position in the string. Can be from 0 to StringLen(text).
value - New char ASCII code.
Sample:
string str="abcdefgh";
string str1=StringSetChar(str, 3, 'D');
// str1 is "abcDefgh"

STRINGSUBSTR

string StringSubstr(string text, int start, int length=0)


Extracts a substring from text string starting from the given position.
The function returns a copy of the extracted substring if possible, otherwise, it returns
an empty string.
Parameters:
text - String from which the substring will be extracted.
start - Substring starting index. Can be from 0 to StringLen(text)-1.
length - Length of the substring extracted. If the parameter value exceeds or equals
to 0 or the parameter is not specified, the substring will be extracted starting
from the given position and up to the end of the string.
Sample:
string text="The quick brown dog jumps over the lazy fox";
string substr=StringSubstr(text, 4, 5);
// subtracted string is the "quick" word

124
STRINGTRIMLEFT

string StringTrimLeft(string text)


The function cuts line feed characters, spaces and tabs in the left part of the string. The
function returns a copy of the trimmed string, if possible. Otherwise, it returns an empty
string.
Parameters:
text - String to be trimmed at the left.
Sample:
string str1=" Hello world ";
string str2=StringTrimLeft(str);
// after trimming the str2 variable will be "Hello World "

STRINGTRIMRIGHT

string StringTrimRight(string text)


The function cuts line feed characters, spaces and tabs in the right part of the string. The
function returns a copy of the trimmed string, if possible. Otherwise, it returns an empty
string.
Parameters:
text - String to be trimmed at the right.
Sample:
string str1=" Hello world ";
string str2=StringTrimRight(str);
// after trimming the str2 variable will be " Hello World"

125
TECHNICAL INDICATORS

A group of functions intended for calculation of standard and custom indicators.

For an expert (or any other MQL4 program) to take up the value of any indicator, it is
not necessary that this indicator is present in the chart. The requested indicator will be
loaded and calculated in the thread of the module that has called it.

Any indicator can be calculated on the data of not only current chart, but also on the
data of any available symbol/period. If data (symbol name and/or timeframe differ from
the current ones) are requested from another chart, the situation is possible that the
corresponding chart was not opened in the client terminal and the necessary data must
be requested from the server. In this case, error ERR_HISTORY_WILL_UPDATED
(4066 - the requested history data are under updating) will be placed in the last_error
variable, and one will has to re-request (see example of ArrayCopySeries()).

IAC

double iAC(string symbol, int timeframe, int shift)


Calculates the Bill Williams' Accelerator/Decelerator oscillator.
Parameters:
symbol - Symbol name of the security on the data of which the indicator will be
calculated. NULL means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
double result=iAC(NULL, 0, 1);

IAD

double iAD(string symbol, int timeframe, int shift)


Calculates the Accumulation/Distribution indicator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
double result=iAD(NULL, 0, 1);

126
IALLIGATOR

double string symbol, int timeframe, int jaw_period, int jaw_shift,


iAlligator( int teeth_period, int teeth_shift, int lips_period, int lips_shift,
int ma_method, int applied_price, int mode, int shift)
Calculates the Bill Williams' Alligator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator.
NULL means the current symbol.
timeframe - Timeframe. It can be one of Timeframe enumeration values. 0
means the current chart timeframe.
jaw_period - Blue line averaging period (Alligator's Jaw).
jaw_shift - Blue line shift relative to the chart.
teeth_period - Red line averaging period (Alligator's Teeth).
teeth_shift - Red line shift relative to the chart.
lips_period - Green line averaging period (Alligator's Lips).
lips_shift - Green line shift relative to the chart.
ma_method - MA method. It can be any of Moving Average methods.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - Data source, identifier of a line of the indicator. It can be any of the
following values:
MODE_GATORJAW - Gator Jaw (blue) balance line,
MODE_GATORTEETH - Gator Teeth (red) balance line,
MODE_GATORLIPS - Gator Lips (green) balance line.
shift - Shift relative to the current bar (number of periods back) where the
data should be taken from.
Sample:
double jaw_val=iAlligator(NULL, 0, 13, 8, 8, 5, 5, 3, MODE_SMMA,
PRICE_MEDIAN, MODE_GATORJAW, 1);

IADX

double 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

double iATR(string symbol, int timeframe, int period, int shift)


Calculates the Indicator of the average true range and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
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(iATR(NULL,0,12,0)>iATR(NULL,0,20,0)) return(0);

IAO

double iAO(string symbol, int timeframe, int shift)


Calculates the Bill Williams' Awesome oscillator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
double val=iAO(NULL, 0, 2);

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

double iCCIOnArray(double array[], int total, int period, int shift)


Calculation of the Commodity Channel Index on data stored in a numeric array. Unlike
iCCI(...), the iCCIOnArray function does not take data by symbol name, timeframe, the
applied price. The price data must be previously prepared. The indicator is calculated
from left to 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:

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

double iDeMarker(string symbol, int timeframe, int period, int shift)


Calculates the DeMarker indicator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
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:
double val=iDeMarker(NULL, 0, 13, 1);

131
IENVELOPES

double string symbol, int timeframe, int ma_period, int ma_method,


iEnvelopes( int ma_shift, int applied_price, double deviation, int mode, int shift)
Calculates the Envelopes indicator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator.
NULL means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0
means the current chart timeframe.
ma_period - Averaging period for calculation of the main line.
ma_method - MA method. It can be any of Moving Average method enumeration
value.
ma_shift - MA shift. Indicator line offset relate to the chart by timeframe.
applied_price - Applied price. It can be any of Applied price enumeration values.
deviation - Percent deviation from the main line.
mode - Indicator line index. It can be any of Indicators line identifiers
enumeration value.
shift - Index of the value taken from the indicator buffer (shift relative to
the current bar the given amount of periods ago).
Sample:
double val=iEnvelopes(NULL, 0,
13,MODE_SMA,10,PRICE_CLOSE,0.2,MODE_UPPER,0);

IENVELOPESONARRAY

double double array[], int total, int ma_period, int ma_method,


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

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

double iFractals(string symbol, int timeframe, int mode, int shift)


Calculates the Fractals and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
mode - Indicator line index. It can be any of the Indicators line identifiers
enumeration value.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
double val=iFractals(NULL, 0, MODE_UPPER, 3);

IGATOR

double string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period,
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

double string symbol, int timeframe, int tenkan_sen, int kijun_sen,


iIchimoku( int senkou_span_b, int mode, int shift)
Calculates the Ichimoku Kinko Hyo and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator.
NULL means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0
means the current chart timeframe.
tenkan_sen - Tenkan Sen averaging period.
kijun_sen - Kijun Sen averaging period.
senkou_span_b - Senkou SpanB averaging period.
mode - Source of data. It can be one of the Ichimoku Kinko Hyo mode
enumeration.
shift - Index of the value taken from the indicator buffer (shift relative to
the current bar the given amount of periods ago).
Sample:
double tenkan_sen=iIchimoku(NULL, 0, 9, 26, 52, MODE_TENKANSEN, 1);

134
IBWMFI

double iBWMFI(string symbol, int timeframe, int shift)


Calculates the Bill Williams Market Facilitation index and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
double val=iBWMFI(NULL, 0, 0);

IMOMENTUM

double iMomentum(string symbol, int timeframe, int period, int applied_price, int shift)
Calculates the Momentum indicator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate
indicator.NULL means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0
means the current chart timeframe.
period - Period (amount of bars) for calculation of price changes.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Index of the value taken from the indicator buffer (shift relative to
the current bar the given amount of periods ago).
Sample:
if(iMomentum(NULL,0,12,PRICE_CLOSE,0)>iMomentum(NULL,0,20,PRICE_CLOSE,
0)) return(0);

IMOMENTUMONARRAY

double iMomentumOnArray(double array[], int total, int period, int shift)


Calculation of the Momentum indicator on data stored in a numeric array. Unlike
iMomentum(...), the iMomentumOnArray function does not take data by symbol name,
timeframe, the applied price. The price data must be previously prepared. The indicator
is 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.
period - Period (amount of bars) for calculation of price changes.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:

135
if(iMomentumOnArray(mybuffer,100,12,0)>iMomentumOnArray(mubuffer,100,2
0,0)) return(0);

IMFI

double iMFI(string symbol, int timeframe, int period, int shift)


Calculates the Money flow index and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
period - Period (amount of bars) for calculation of the indicator.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
if(iMFI(NULL,0,14,0)>iMFI(NULL,0,14,1)) return(0);

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

double string symbol, int timeframe, int fast_ema_period, int slow_ema_period,


iOsMA( int signal_period, int applied_price, int shift)
Calculates the Moving Average of Oscillator and returns its value. Sometimes called
MACD Histogram in some systems.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator.
NULL means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0
means the current chart timeframe.
fast_ema_period - Number of periods for fast moving average calculation.
slow_ema_period - Number of periods for slow moving average calculation.
signal_period - Number of periods for signal moving average calculation.
applied_price - Applied price. It can be any of Applied price enumeration
values.
shift - Index of the value taken from the indicator buffer (shift relative
to the current bar the given amount of periods ago).
Sample:
if(iOsMA(NULL,0,12,26,9,PRICE_OPEN,1)>iOsMA(NULL,0,12,26,9,PRICE_OPEN,
0)) return(0);

137
IMACD

double string symbol, int timeframe, int fast_ema_period, int slow_ema_period,


iMACD( int signal_period, int applied_price, int mode, int shift)
Calculates the Moving averages convergence/divergence and returns its value. In the
systems where OsMA is called MACD Histogram, this indicator is displayed as two
lines. In the Client Terminal, the Moving Average Convergence/Divergence is drawn as
a histogram.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator.
NULL means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0
means the current chart timeframe.
fast_ema_period - Number of periods for fast moving average calculation.
slow_ema_period - Number of periods for slow moving average calculation.
signal_period - Number of periods for signal moving average calculation.
applied_price - Applied price. It can be any of Applied price enumeration
values.
mode - Indicator line index. It can be any of the Indicators line
identifiers enumeration value.
shift - Index of the value taken from the indicator buffer (shift relative
to the current bar the given amount of periods ago).
Sample:
if(iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0)>iMACD(NULL,0,12,26,9,
PRICE_CLOSE,MODE_SIGNAL,0)) return(0);

IOBV

double iOBV(string symbol, int timeframe, int applied_price, int shift)


Calculates the On Balance Volume indicator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator.
NULL means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0
means the current chart timeframe.
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=iOBV(NULL, 0, PRICE_CLOSE, 1);

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

double iRSIOnArray(double array[], int total, int period, int shift)


Calculation of the Relative Strength Index on data stored in a numeric array. Unlike
iRSI(...), the iRSIOnArray function does not take data by symbol name, timeframe, the
applied price. The price data must be previously prepared. The indicator is 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.
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(iRSIOnArray(ExtBuffer,1000,14,0)>iRSI(NULL,0,14,PRICE_CLOSE,1))
return(0);

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

double double array[], int total, int ma_period, int ma_shift,


iStdDevOnArray( int ma_method, int shift)
Calculation of the Standard Deviation indicator on data stored in a numeric array.
Unlike iStdDev(...), the iStdDevOnArray function does not take data by symbol name,
timeframe, the applied price. The price data must be previously prepared. The indicator
is calculated from left to right. To access to the array elements as to a series array (i.e.,
from right to left), one has to use the ArraySetAsSeries function.

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

double iWPR(string symbol, int timeframe, int period, int shift)


Calculates the Larry William's percent range indicator and returns its value.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL

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

int iBars(string symbol, int timeframe)


Returns the number of bars on the specified chart.
For the current chart, the information about the amount of bars is in the predefined
variable named Bars.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
Sample:
Print("Bar count on the 'EUROUSD' symbol with PERIOD_H1
is",iBars("EUROUSD",PERIOD_H1));

IBARSHIFT

int iBarShift(string symbol, int timeframe, datetime time, bool exact=false)


Search for bar by open time. The function returns bar shift with the open time specified.
If the bar having the specified open time is missing, the function will return -1 or the
nearest bar shift depending on the exact.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
time - value to find (bar's open time).
exact - Return mode when bar not found. false - iBarShift returns nearest. true -
iBarShift returns -1.
Sample:
datetime some_time=D'2004.03.21 12:00';
int shift=iBarShift("EUROUSD",PERIOD_M1,some_time);

143
Print("shift of bar with open time ",TimeToStr(some_time)," is
",shift);

ICLOSE

double iClose(string symbol, int timeframe, int shift)


Returns Close value for the bar of indicated symbol with timeframe and shift. If local
history is empty (not loaded), function returns 0.
For the current chart, the information about close prices is in the predefined array
named Close[].
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),",
", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),",
", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),",
", iVolume("USDCHF",PERIOD_H1,i));

IHIGH

double iHigh(string symbol, int timeframe, int shift)


Returns High value for the bar of indicated symbol with timeframe and shift. If local
history is empty (not loaded), function returns 0.
For the current chart, the information about high prices is in the predefined array
named High[].
Parameters:
symbol - Symbol on that data need to calculate indicator. NULL means current
symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),",
", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),",
", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),",
", iVolume("USDCHF",PERIOD_H1,i));

IHIGHEST

int string symbol, int timeframe, int type, int count=WHOLE_ARRAY,


144
iHighest( int start=0)
Returns the shift of the maximum value over a specific number of periods depending on
type.
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
type - Series array identifier. It can be any of the Series array identifier
enumeration values.
count - Number of periods (in direction from the start bar to the back one) on
which the calculation is carried out.
start - Shift showing the bar, relative to the current bar, that the data should be
taken from.
Sample:
double val;
// calculating the highest value on the 20 consequtive bars in the
range
// from the 4th to the 23rd index inclusive on the current chart
val=High[iHighest(NULL,0,MODE_HIGH,20,4)];

ILOW

double iLow(string symbol, int timeframe, int shift)


Returns Low value for the bar of indicated symbol with timeframe and shift. If local
history is empty (not loaded), function returns 0.
For the current chart, the information about low prices is in the predefined array
named Low[].
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),",
", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),",
", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),",
", iVolume("USDCHF",PERIOD_H1,i));

ILOWEST

int string symbol, int timeframe, int type, int count=WHOLE_ARRAY,


iLowest( int start=0)
Returns the shift of the least value over a specific number of periods depending on type.
Parameters:

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

double iOpen(string symbol, int timeframe, int shift)


Returns Open value for the bar of indicated symbol with timeframe and shift. If local
history is empty (not loaded), function returns 0.
For the current chart, the information about open prices is in the predefined array
named Open[].
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),",
", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),",
", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),",
", iVolume("USDCHF",PERIOD_H1,i));

ITIME

datetime iTime(string symbol, int timeframe, int shift)


Returns Time value for the bar of indicated symbol with timeframe and shift. If local
history is empty (not loaded), function returns 0.
For the current chart, the information about bars open times is in the predefined array
named Time[].
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.

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

double iVolume(string symbol, int timeframe, int shift)


Returns Tick Volume value for the bar of indicated symbol with timeframe and shift. If
local history is empty (not loaded), function returns 0.
For the current chart, the information about bars tick volumes is in the predefined array
named Volume[].
Parameters:
symbol - Symbol the data of which should be used to calculate indicator. NULL
means the current symbol.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
shift - Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Sample:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),",
", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),",
", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),",
", iVolume("USDCHF",PERIOD_H1,i));

147
TRADING FUNCTIONS

A group of functions intended for trading management.

Trading functions of OrderSend(), OrderClose, OrderCloseBy, OrderDelete,


and OrderModify cannot be called from custom indicators.

Trading functions can be used in experts and scripts. Trading functions can be called
only if the "Allow live trading" property of this particular expert is checked.

To trade from experts and scripts, only one thread was provided that was launched in
the program trade context (context of automated trading from experts and scripts). This
is why, if this context is occupied with an expert trading operation, another expert or
script cannot call trading functions at that moment due to error 146
(ERR_TRADE_CONTEXT_BUSY). To check whether it is possible to trade or not,
one has to use the IsTradeAllowed() function. To make a clear sharing of access to the
trading context, one can use a semaphore on the basis of a global variable the value of
which must be changed using the GlobalVariableSetOnCondition() function.

EXECUTION ERRORS

Any trading operation (functions


of OrderSend(), OrderClose, OrderCloseBy, OrderDelete or OrderModify) can fail, for
a number of reasons, and return either negative ticket number or FALSE. One can find
out about the reason for fail by calling of the GetLastError() function. Every error must
be processed in a special way. The most common recommendations are given below.

Error codes returned from trade server.

Constant Value Description


Trade operation
ERR_NO_ERROR 0
succeeded.
OrderModify attempts to
replace the values already
set with the same values.
ERR_NO_RESULT 1 One or more values must
be changed, then
modification attempt can
be repeated.
Common error. All
attempts to trade must be
stopped until reasons are
ERR_COMMON_ERROR 2 clarified. Restart of
operation system and
client terminal will
possibly be needed.
ERR_INVALID_TRADE_PARAMETERS 3 Invalid parameters were

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

bool int ticket, double lots, double price, int slippage,


OrderClose( color Color=CLR_NONE)

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

bool OrderCloseBy(int ticket, int opposite, color Color=CLR_NONE)


Closes an opened order by another opposite opened order. If the function succeeds, the
return value is true. If the function fails, the return value is false. To get the detailed
error information, call GetLastError().
Parameters:
ticket - Unique number of the order ticket.
opposite - Unique number of the opposite order ticket.
Color - Color of the closing arrow on the chart. If the parameter is missing or has
CLR_NONE value closing arrow will not be drawn on the chart.
Sample:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)
{
OrderCloseBy(order_id,opposite_id);
return(0);
}

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

bool OrderDelete(int ticket, color Color=CLR_NONE)


Deletes previously opened pending order. If the function succeeds, the return value is
true. If the function fails, the return value is false. To get the detailed error information,
call GetLastError().
Parameters:
ticket - Unique number of the order ticket.
Color - Color of the arrow on the chart. If the parameter is missing or has
CLR_NONE value arrow will not be drawn on the chart.
Sample:

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

bool int ticket, double price, double stoploss, double takeprofit,


OrderModify( datetime expiration, color arrow_color=CLR_NONE)
Modification of characteristics for the previously opened position or pending orders. If
the function succeeds, the returned value will be TRUE. If the function fails, the
returned value will be FALSE. To get the detailed error information, call GetLastError()
function.
Notes: Open price and expiration time can be changed only for pending orders.
If unchanged values are passed as the function parameters, the error 1
(ERR_NO_RESULT) will be generated.
Pending order expiration time can be disabled in some trade servers. In this case, when

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

bool OrderSelect(int index, int select, int pool=MODE_TRADES)


The function selects an order for further processing. It returns TRUE if the function
succeeds. It returns FALSE if the function fails. To get the error information, one has to
call the GetLastError() function.
The pool parameter is ignored if the order is selected by the ticket number. The ticket
number is a unique order identifier. To find out from what list the order has been
selected, its close time must be analyzed. If the order close time equals to 0, the order is
open or pending and taken from the terminal open positions list. One can distinguish an
open position from a pending order by the order type. If the order close time does not
equal to 0, the order is a closed order or a deleted pending order and was selected from
the terminal history. They also differ from each other by their order types.
Parameters:
index - Order index or order ticket depending on the second parameter.
select - Selecting flags. It can be any of the following values:
SELECT_BY_POS - index in the order pool,
SELECT_BY_TICKET - index is order ticket.
pool - Optional order pool index. Used when the selected parameter is
SELECT_BY_POS. It can be any of the following values:
MODE_TRADES (default)- order selected from trading pool(opened and
pending orders),
MODE_HISTORY - order selected from history pool (closed and canceled
order).
Sample:
if(OrderSelect(12470, SELECT_BY_TICKET)==true)

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

void HideTestIndicators(bool hide)


The function sets a flag hiding indicators called by the Expert Advisor. After the expert
has been tested and the appropriate chart opened, the flagged indicators will not be
drawn in the testing chart. Every indicator called will first be flagged with the current
hiding flag.
It must be noted that only those indicators can be drawn in the testing chart that are
directly called from the expert under test.
Parameters:
hide - TRUE, if there is a need to hide indicators, or else FALSE.
Sample:
HideTestIndicators(true);
MaCurrent=iMA(NULL,0,56,0,MODE_EMA,PRICE_CLOSE,0);
MaPrevious=iMA(NULL,0,56,0,MODE_EMA,PRICE_CLOSE,1);
HideTestIndicators(false);

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

int WindowFind(string name)


164
If indicator with name was found, the function returns the window index containing this
specified indicator, otherwise it returns -1.
Note: WindowFind() returns -1 if custom indicator searches itself when init() function
works.
Parameters:
name - Indicator short name.
Sample:
int win_idx=WindowFind("MACD(12,26,9)");

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

int WindowHandle(string symbol, int timeframe)


Returns the system window handler containing the given chart. If the chart of symbol
and timeframe has not been opened by the moment of function calling, 0 will be
returned.
Parameters:
symbol - symbol name.
timeframe - Timeframe. It can be any of Timeframe enumeration values. 0 means
the current chart timeframe.
Sample:
int win_handle=WindowHandle("USDX",PERIOD_H1);
if(win_handle!=0)
Print("Window with USDX,H1 detected. Rates array will be copied
immediately.");

WINDOWISVISIBLE

bool WindowIsVisible(int index)


Returns TRUE if the chart subwindow is visible, otherwise returns FALSE. The chart
subwindow can be hidden due to the visibility properties of the indicator placed in it.
Parameters:
index - Chart subwindow index.

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

double WindowPriceMax(int index=0)


Returns maximal value of the vertical scale of the specified subwindow of the current
chart (0-main chart window, the indicators' subwindows are numbered starting from 1).
If the subwindow index has not been specified, the maximal value of the price scale of
the main chart window is returned.
See also WindowPriceMin(), WindowFirstVisibleBar(), WindowBarsPerChart()
Parameters:
index - Chart subwindow index (0 - main chart window).
Sample:
double top=WindowPriceMax();
double bottom=WindowPriceMin();
datetime left=Time[WindowFirstVisibleBar()];
int right_bound=WindowFirstVisibleBar()-WindowBarsPerChart();
if(right_bound<0) right_bound=0;
datetime right=Time[right_bound]+Period()*60;
//----
ObjectCreate("Padding_rect",OBJ_RECTANGLE,0,left,top,right,bottom);
ObjectSet("Padding_rect",OBJPROP_BACK,true);
ObjectSet("Padding_rect",OBJPROP_COLOR,Blue);
WindowRedraw();

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.

Old Name New Name


BarsPerWindow WindowBarsPerChart
ClientTerminalName TerminalName
CurTime TimeCurrent
CompanyName TerminalCompany
FirstVisibleBar WindowFirstVisibleBar
Highest iHighest
HistoryTotal OrdersHistoryTotal
LocalTime TimeLocal
Lowest iLowest
ObjectsRedraw WindowRedraw,
PriceOnDropped WindowPriceOnDropped
ScreenShot WindowScreenShot
ServerAddress AccountServer
TimeOnDropped WindowTimeOnDropped

170

You might also like