MQL5 Reference

MQL5 Reference Forward

MQL5 Reference

MetaQuotes Language 5 (MQL5) is a built-in language for programming trading strategies, which is developed by MetaQuotes Software Corp. based on their long experience in the creation of online trading platforms. Using this language, you can create your own Expert Advisors that make trading management automated and are perfectly suitable for implementing your own trading strategies. Besides, using MQL5 you can create your own technical indicators (custom indicators), scripts and libraries.

MQL5 contains a large number of functions necessary for analyzing current and previously received quotes, and has built-in basic indicators and functions for managing trade positions and controlling them.

The MetaEditor 5 (text editor) that highlights different constructions of MQL5 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 MQL5 language.

The brief guide contains functions, operations, reserved words, and other language constructions divided into categories, and allows finding the description of every used element of the language.

Programs written in MetaQuotes Language 5 have different fe0atures and purposes:

· Expert Advisor is a mechanical trading system linked up to a certain chart. An Expert Advisor starts to run when an event happens that can be processed by it: events of initialization and deinitialization, event of a new tick receipt, a timer event, depth of market changing event chart event and custom events.

An Expert Advisor can both inform you about a possibility to trade and automatically trade on an account sending orders directly to a trade server. Expert Advisors are stored in terminal_directory\MQL5\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 can't use functions for working with charts or chart objects. Custom indicators are stored in terminal_directory\MQL5\Indicators
· Script is a program intended for a single execution of some actions. Unlike Expert Advisors, scripts do not process any actions, except for the start event (this requires the OnStart handler function in a script). Scripts are stored in terminal_directory\MQL5\Scripts
· Library is a set of custom functions intended for storing and distributing frequently used blocks of custom programs. Libraries cannot start executing by themselves.
Libraries are stored in terminal_directory\MQL5\Libraries
· Include File is a source text of the most frequently used blocks of custom programs. Such files can be included into the source texts of Expert Advisors, 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.

Include files can be stored in the same directory as a source file - in this case the #include directive with double quotes is used. Another place to store include files is terminal_directory\MQL5\Include, in this case the #include directive is used with angle brackets.

Â © 2000-2009,MetaQuotes Software Corp.


Language Basics

MQL5 Reference / Language Basics

Language Basics

Language MetaQuotes Language 5 (MQL5) is an object-oriented programming language High-level and intended to write automated trading strategies, custom technical indicators for the analysis of various financial markets.It allows not only to write a variety of expert systems, designed to operate in real time, but also create their own graphical tools to help you make trade decisions.

MQL5 based on the concept of widespread programming language, C + +, compared with MQL4 it added enumeration, structure, classes and event handling. By increasing the number of embedded core types, the interaction of executable programs on MQL5 with other applications as easy as possible through dll.MQL5 syntax is similar to the syntax of C + +, and this makes it easy to transfer to him the program of modern programming languages.

For the purposes of learning the language MQL5 all topics grouped under the following headings:

· Syntax
· Data Types
· Operations and Expressions
· Operators
· Functions
· Variables
· Preprocessor
· Object-Oriented Programming


Syntax

MQL5 Reference / Language Basics / Syntax

Syntax

Syntactical language for trade strategies MQL5 very similar to the programming language C + +, except for some possibilities:

· no address arithmetic;
· no operator goto;
· can not declare an anonymous enumeration;
· constructors of classes and structures can not have parameters;
· no multiple inheritance.


Comments

MQL5 Reference / Language Basics / Syntax / Comments

Comments

Multi-line comments start with the /* pair of symbols and end with the */ one. Such kind of comments cannot be nested comments. Single-line comments begin with the // pair of symbols and end with the symbols of new line, they can be nested in other multi-line comments. Comments are allowed everywhere where the spaces are allowed, they can have any number of spaces in them.

Examples:

//--- Single-line comment
/* Multi-
line // Nested single-line comment
comment
*/


Identifiers

MQL5 Reference / Language Basics / Syntax / Identifiers

Identifiers

Identifiers are used as names for variables and functions. The length of the identifier can not exceed 31 characters.

Allowed characters for writing ID: Figures 0-9, the Latin uppercase and lowercase letters a-z and A-Z, recognized as different characters, the underscore character (_).The first character can not be a digit.

The identifier must not coincide with reserved word.

Examples:

NAME1 namel Total_5 Paper


Reserved Words

MQL5 Reference / Language Basics / Syntax / Reserved Words

Reserved Words

The following identifiers are recorded as reserved words, each of which corresponds to a certain action, and in another sense can not be used:

Data Types

bool | enum | struct
char | float | uchar
class | int | uint
color | long | ulong
datetime | short | ushort
double | string | void

Access Specificators

const

private

protected

public

virtual

Storage Classes

extern

input

static

Operators

break | default | else | new | switch
case | delete | for | return | while
continue | do | if | sizeof |

Other

false | true | #import | #property
this | #define | #include |


Datatypes

MQL5 Reference / Language Basics / Data Types

Data Types

Any program operates on data.Data can be of different types depending on the destination.For example, to access the array elements using integer data.Price data are of type double precision floating point.This is due to the fact that the language MQL5 no explicit type for the price data.

These different types are processed at different speeds.Integer data is processed faster than total.For data using a special double precision coprocessor.However, because of the complexity of the internal representation of floating point data, they are processed for longer than integer.

Longest string of processed data. This is due to dynamic allocation, redistribution of the computer's memory.

Basic data types:
· integers (char, short, int, long, uchar, ushort, uint, ulong)
· logical (bool)
· literals (char, uchar)
· strings (string)
· float (double, float)
· color (color)
· date and time (datetime)
· enumerations (enum)

Complex data types:

· structures;
· classes.

In terms of OOP complex data types called abstract data types.

Types of color and datetime are meaningful only for the convenience of presentation and input parameters defined from the outside - from the table properties advisor or Custom indicator (Tab "Inputs"). These types of color and datetime are represented as integers. Integer types with the types of floating point arithmetic called the (numeric) types.

In expressions use implicit type casting unless the explicit one is specified.


Integer constants

MQL5 Reference / Language Basics / Data Types / Integer Types

Integer Types

Integer types are represented in the language MQL5 eleven species. Some types may be used in conjunction with others, if required by the logic of the program, but it must be borne in mind the rules of types conversion.

The table lists the characteristics of each type. In addition, in the last column for each type specified in the appropriate type of programming language C++.

Type | Size in Bytes | Minimum Value | Maximum Value | C + + Analog
char | 1 | -128 | 127 | char
uchar | 1 | 0 | 255 | unsigned char, BYTE
bool | 1 | 0(false) | 1(true) | bool
short | 2 | -32 768 | 32 767 | short, wchar_t
ushort | 2 | 0 | 65 535 | unsigned short, WORD
int | 4 | - 2 147 483 648 | 2 147 483 647 | int
uint | 4 | 0 | 4 294 967 295 | unsigned int, DWORD
color | 4 | -1 | 16 777 215 | int, COLORREF
long | 8 | -9 223 372 036 854 775 808 | 9 223 372 036 854 775 807 | __int64
ulong | 8 | 0 | 18 446 744 073 709 551 615 | unsigned __int64
datetime | 8 | 0 (1970.01.01 0:00:00) | 32 535 244 799 (3000.12.31 23:59:59) | __time64_t

See also

Data Conversion, Constants of Numeric Types


Char, Short, Int and Long Types

MQL5 Reference / Language Basics / Data Types / Integer Types / Char, Short, Int and Long Types

Char, Short, Int and Long Types

Char

A type char occupies 1 byte of memory (8 bits) and can be expressed in binary notation 2 ^ 8 = 256 values.Type char can contain both positive and negative values.Range of values is from -128 to 127.

Uchar

A type uchar also occupies 1 byte of memory, as well as type char, but unlike him, uchar intended only for positive values.The minimum value is zero, the maximum value is 255.The first letter u in the name of the type uchar an abbreviation for the word unsigned (unsigned).

Short

A type of short is 2 bytes (16 bits) and, accordingly, allows us to express the set of values equal to 2 to the power 16: 2 ^ 16 = 65 536.Since the type of short is a landmark and contains both positive and negative values, the value range is between -32 768 and 32 767.

Ushort

Unsigned short type is the type ushort, which also has a size of 2 bytes. The minimum value is 0, the maximum value of 65 535.

Int

A type of int is 4 bytes (32 bits). The minimum value of -2 147 483 648, the maximum value of 2 147 483 647.

Uint

Unsigned integer type uint is 4 bytes in memory and allows you to express the integers from 0 to 4 294 967 295.

Long

A type of long is 8 bytes (64 bits). The minimum value of -9 223 372 036 854 775 808, the maximum value of 9 223 372 036 854 775 807.

Ulong

A type ulong also occupies 8 bytes and can store values from 0 to 18 446 744 073 709 551 615.

Examples:

char ch=12;
short sh=-5000;
int in=2445777;

Since the unsigned integer types are not designed for storage of negative values, then the attempt to set a negative value can lead to unexpected consequences.That's so innocent script will lead to an infinite loop:

//--- Infinite loop
void OnStart()
{
uchar u_ch;

for(char ch=-128;ch<128;ch++)
{
u_ch=ch;
Print("ch=",ch," u_ch=",u_ch);
}
}

Correct would be:

//--- Correct variant
void OnStart()
{
uchar u_ch;

for(char ch=-128;ch<=127;ch++)
{
u_ch=ch;
Print("ch=",ch," u_ch=",u_ch);
if(ch==127) break;
}
}

Result:

ch= -128 u_ch= 128

ch= -127 u_ch= 129

ch= -126 u_ch= 130

ch= -125 u_ch= 131

ch= -124 u_ch= 132

ch= -123 u_ch= 133

ch= -122 u_ch= 134

ch= -121 u_ch= 135

ch= -120 u_ch= 136

ch= -119 u_ch= 137

ch= -118 u_ch= 138

ch= -117 u_ch= 139

ch= -116 u_ch= 140

ch= -115 u_ch= 141

ch= -114 u_ch= 142

ch= -113 u_ch= 143

ch= -112 u_ch= 144

ch= -111 u_ch= 145

...

Examples:

//--- Negative values can not be stored in the unsigned types
uchar u_ch=-120;
ushort u_sh=-5000;
uint u_in=-401280;

Hexadecimal: numbers 0-9, the letters a-f or A-F for the values of 10-15; start with 0x or 0x.

Examples:

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


Datetime Type

MQL5 Reference / Language Basics / Data Types / Integer Types / Datetime Type

Datetime Type

The datetime type is intended to store the date and time as the number of seconds elapsed since January 01, 1970. Occupies 8 bytes of memory.

Constants of the date and time can be represented as a literal string, which consists of 6 parts of the numerical value of the year, month, day (or day, month, year), hours, minutes and seconds.The constant enclosed in single quotation marks and begins with a D.

Can be lowered or the date (year, month, day) or time (hours, minutes, seconds), or all together. Values range from 1 January 1970 until 31 December 3000.

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' //equivalent to D'1980.07.19 12:00:00'
D'01.01.2004' //equivalent to D'01.01.2004 00:00:00'
D'12:30:27' //equivalent to D'[compilation date] 12:30:27'
D'' //equivalent to D'[compilation date] 00:00:00'


Color Type

MQL5 Reference / Language Basics / Data Types / Integer Types / Color Type

Color Type

The color type is intended for storing information about color and occupies 4 bytes in memory. The first byte is ignored, the remaining 3 bytes contain the RGB-components.

Color constants can be represented by three different ways: literally, integer, or by name (only for the named Web-colors).

Literal representation consists of three parts, representing the numerical values of the intensity of the three main components of color: red (red), green (green), blue (blue).Constant begins with a C and is enclosed by single quotes.The numerical values of intensity of the color components are in the range from 0 to 255.

Integer representation is written in hexadecimal or decimal.Hexadecimal number has the form 0x00BBGGRR, where RR - meaning the intensity of red color components, GG - green and BB - blue.Decimal constants are not directly reflected in the RGB.They represent the decimal value of hexadecimal integer representation.

Named colors reflect the so-called set Web-colors.

Examples:

//--- Literals
C'128,128,128' // Gray
C'0x00,0x00,0xFF' // Blue
//color names
Red // Red
Yellow // Yellow
Black // Black
//--- Integral representations
0xFFFFFF // White
16777215 // White
0x008000 // Green
32768 // Green


Bool Type

MQL5 Reference / Language Basics / Data Types / Integer Types / Bool Type

Bool Type

The bool type is intended to store the logical values true or false, numeric representation of which 1 or 0, respectively.

Examples:

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

The internal representation - a whole number, 1 byte.It should be noted that, in logical terms acceptable to use instead of type bool other integer or real types or expressions of these types, the compiler will not issue an error.In this case, a value of zero will be interpreted as false, and all other values as true.

Examples:

int i=5;
double d=-2.5;
if(i) Print("i=",i,"and is set to true");
else Print("i=",i,"and is set to false");

if(d) Print("d=",d,"and has the true value");
else Print("d=",d,"and has the false value");

i=0;
if(i) Print("i=",i,"and has the true value");
else Print("i=",i,"and has the false value");

d=0.0;
if(d) Print("d=",d,"and has the true value");
else Print("d=",d,"and has the false value");

//--- Execution results
// i= 5 and has the true value
// d= -2.50000000 and has the true value
// i= 0 and has the false value
// d= 0.00000000 and has the false value


Enumerations

MQL5 Reference / Language Basics / Data Types / Integer Types / Enumerations

Enumerations

These enumeration of enum type belong to a certain limited set of data. Of enumeration type:

enum name of enumerable type
{
list of values
};

A list of values is a list of variables, separated by commas.

Example:

enum months // Enumeration of named constants
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
};

Following the announcement of the transfer there is a new 4-byte integer data type.Announcement of a new data type allows the compiler to strictly control the types of transmission parameters, as well as a listing of introducing new named constants.In this example, a named constant January is 0, February is 1, December has value 11.

Rule: If a named constant - a member of the transfer is clearly not given a specific value, then its value will be generated automatically.If this is the first member of the transfers will be set to 0.For all subsequent members of the value will be calculated based on the value of the previous members by adding a unit.

Example:

enum intervals // Enumeration of named constants
{
month=1, // Interval of one month
two_months, // Two months
quarter, // Three months - quarter
halfyear=6, // Half year
year=12, // Year - 12 months
};

Notes

· Unlike C + +, the size of the internal representation of an enumerated type in MQL5 always is 4 bytes. That is, sizeof (months) returns the value 4.
· Unlike C + +, in MQL5 can not declare an anonymous enumeration. That is, after the enum keyword shall always be given a unique name.


Real Types

MQL5 Reference / Language Basics / Data Types / Real Types

Real Types (double, float)

Real types (or types of floating-point) represent the values with a fractional part.In the language MQL5 there are two types for floating point.Way to represent real numbers in computer memory standard defined by IEEE 754 and is independent of platforms, operating systems and programming languages.

Type | Size in bytes | Minimal Positive Value | Maximum Value | Representation Accuracy | C + + Analog
float | 4 | 1.175494351e-38 | 3.402823466e+38 | 7 significant digits | float
double | 8 | 2.2250738585072014e-308 | 1.7976931348623158e+308 | 15 significant digits | double

The double name means that the accuracy of these numbers is twice the accuracy of the numbers of type float. In most cases, the type double is the most convenient. Limited precision of numbers float many cases, simply not enough. The reason that type float is still used - to save memory storage (this is important for large arrays of real numbers).

Floating-point constants consist of an intact part of the point (.) And the fractional part. Whole and fractional parts are sequences of decimal digits.

Examples:

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

There is a scientific way of writing real constants, often this method of recording more compact than the traditional.

Example:

double c1=1.12123515e-25;
double c2=0.000000000000000000000000112123515; // 24 zero after the decimal point

Print("1. c1 =",DoubleToString(c1,16));
// Result: 1. c1 = 0.0000000000000000

Print("2. c1 =",DoubleToString(c1,-16));
// Result: 2. c1 = 1.1212351499999999e-025

Print("3. c2 =",DoubleToString(c2,-16));
// Result: 3. c2 = 1.1212351499999999e-025

Must be remembered that the real numbers are stored in memory with some limited accuracy in the binary system, while the standard in the use of a decimal number system.Therefore, many of which are accurately recorded in the decimal system, binary system can be written only in the form of an infinite decimals.

For example, the number of 0.3 and 0.7 are represented in the computer infinite fractions, while the number of 0.25 is stored exactly as represents the power of two.

In this regard, strongly not recommended compare together two real numbers for equality, because such a comparison is not correct.

Example:

void OnStart()
{
//---
double three=3.0;
double x,y,z;
x=1/three;
y=4/three;
z=5/three;
if(x+y==z) Print("1/3 + 4/3 == 5/3");
else Print("1/3 + 4/3 != 5/3");
// Result: 1 / 3 + 4 / 3 = 5 / 3
}

If you still need to compare the equality of two real numbers, then you can do this in two different ways.The first way is to compare the difference between two numbers with a small quantity that specifies the accuracy of comparison.

Example:

bool EqualDoubles(double d1,double d2,double epsilon)
{
if(epsilon<0) epsilon=-epsilon;
//---
if(d1-d2>epsilon) return false;
if(d1-d2<-epsilon) return false;
//---
return true;
}
void OnStart()
{
double d_val=0.7;
float f_val=0.7;
if(EqualDoubles(d_val,f_val,0.000000000000001)) Print(d_val,"equals",f_val);
else Print("Different: d_val=",DoubleToString(d_val,16),
" f_val=",DoubleToString(f_val,16));
// Result: Different: d_val = 0.7000000000000000 f_val = 0.6999999880790710
}

It should be noted that the value of epsilon in the above example, can not be less than the predefined constants DBL_EPSILON.The value of this constant 2.2204460492503131e-016.For a float corresponding to a constant FLT_EPSILON = 1.192092896e-07.The meaning of these values is such that it is the lowest value udovletoryayuschee condition 1.0 + DBL_EPSILON! = 1.0 (for numbers of type float 1.0 + FLT_EPSILON! = 1.0).

The second way is to compare the normalized difference of two real numbers with zero.Compare the difference of normalized numbers with a zero futile, as a result of any mathematical operation with normalized numbers, the result is nonnormalized.

Example:

bool CompareDoubles(double number1,double number2)
{
if(NormalizeDouble(number1-number2,8)==0) return(true);
else return(false);
}
void OnStart()
{
double d_val=0.3;
float f_val=0.3;
if(CompareDoubles(d_val,f_val)) Print(d_val,"equals",f_val);
else Print("Different: d_val=",DoubleToString(d_val,16),
" f_val=",DoubleToString(f_val,16));
// Result: Different: d_val = 0.3000000000000000 f_val = 0.3000000119209290
}

As a result, some operations math coprocessor can turn out invalid real number, which can not be used in mathematical operations and comparisons, as the result of invalid operations on real numbers is undefined.For example, when trying to calculate arcsine of 2, the result is negative infinity.

Example:

double abnormal = MathArcsin(2.0);
Print("MathArcsin(2.0) =",abnormal);
// Result: MathArcsin (2.0) = -1. # IND0000

In addition to minus infinity plus infinity, and there is NaN (not a number). To determine that this number is not valid, you can use MathIsValidNumber(). According to IEEE, they have a special machine representation. For example, plus infinity for type double has a bit representation 0x7FF0 0000 0000 0000.

Examples:

struct str1
{
double d;
};
struct str2
{
long l;
};

//--- Start
str1 s1;
str2 s2;
//---
s1.d=MathArcsin(2.0); // Get the invalid number -1.#IND
s2=s1;
printf("1. %f %I64X",s1.d,s2.l);
//---
s2.l=0xFFFF000000000000; // invalid number -1.#QNAN
s1=s2;
printf("2. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF7000000000000; // greatest nonnumber SNaN
s1=s2;
printf("3. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF8000000000000; // smallest nonnumber QNaN
s1=s2;
printf("4. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FFF000000000000; // greatest nonnumber QNaN
s1=s2;
printf("5. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF0000000000000; // Positive infinity 1.#INF and smallest nnonnumber SNaN
s1=s2;
printf("6. %f %I64X",s1.d,s2.l);
//---
s2.l=0xFFF0000000000000; // Negative infinity -1.#INF
s1=s2;
printf("7. %f %I64X",s1.d,s2.l);
//---
s2.l=0x8000000000000000; // Negative zero -0.0
s1=s2;
printf("8. %f %I64X",s1.d,s2.l);
//---
s2.l=0x3FE0000000000000; // 0.5
s1=s2;
printf("9. %f %I64X",s1.d,s2.l);
//---
s2.l=0x3FF0000000000000; // 1.0
s1=s2;
printf("10. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FEFFFFFFFFFFFFF; // Greatest normalized number (MAX_DBL)
s1=s2;
printf("11. %.16e %I64X",s1.d,s2.l);
//---
s2.l=0x0010000000000000; // Smallest positive normalized (MIN_DBL)
s1=s2;
printf("12. %.16e %.16I64X",s1.d,s2.l);
//---
s1.d=0.7; // Show that the number of 0.7 - endless fraction
s2=s1;
printf("13. %.16e %.16I64X",s1.d,s2.l);
/*
1. -1.#IND00 FFF8000000000000
2. -1.#QNAN0 FFFF000000000000
3. 1.#SNAN0 7FF7000000000000
4. 1.#QNAN0 7FF8000000000000
5. 1.#QNAN0 7FFF000000000000
6. 1.#INF00 7FF0000000000000
7. -1.#INF00 FFF0000000000000
8. -0.000000 8000000000000000
9. 0.500000 3FE0000000000000
10. 1.000000 3FF0000000000000
11. 1.7976931348623157e+308 7FEFFFFFFFFFFFFF
12. 2.2250738585072014e-308 0010000000000000
13. 6.9999999999999996e-001 3FE6666666666666
*/

See also

DoubleToString, NormalizeDouble, Constants of Numeric Types


String Types

MQL5 Reference / Language Basics / Data Types / String Types

String Types

Type string is used to store text strings.Text string is a sequence of characters in Unicode format with the final zero at the end of.string-variable can be assigned a string constant.A string constant is a sequence of characters Unicode, enclosed in double quotes: "This is a string constant".

The internal representation --structure size of 8 bytes.The first element of the structure - integer type int buf_len, contains the size of the distributed to the line buffer.The second element of the structure buf_ptr - 32-bit pointer to a buffer containing the string.Immediately before the buffer is placed str_len variable of type int, containing the string length (number of characters in the string to the end of zero).

Member buf_len structure can be one of the following:

· 0 - indicates that this is a constant string that is stored in a pool of constant strings;
· -1 - Indicates that the line belongs to the client terminal (osvobozheniem this line deals with the client terminal, and not performing subsystem);
· number - the size of the buffer in characters such short, placed in the computer memory to store the string.

Immediately before the buffer allocated 4 bytes for the service information about the length of the line. It is from here to extract information about the length of the line function StringLen(). The length of the line may have zero size, even if the buffer is allocated by a string has non-zero size. End of line in the buffer is always there, where it finds the first byte containing 0.

If you need to enter a string double quote ( "), then it must be put before the backslash character (\).In line may be introduced by any special character constants, faced with a backslash (\).

Examples:

string svar="This is a character string";
string svar2=StringSubstr(svar,0,4);
Print("Copyright symbol\t\x00A9");
FileWrite(handle,"This string contains a new line symbols \n");
string MT5path="C:\\Program Files\\MetaTrader 5";

If a variable of type string is not explicitly initialized, the compiler itself substitutes the code resets the specified structure.This is necessary in order to avoid critical errors when accessing such a variable.


Structures and Classes

MQL5 Reference / Language Basics / Data Types / Structures and Classes

Structures and Classes

Structures

The structure is a set of elements of any type (except type void). Thus, the structure combines logically related data of different types.

Structure Declaration

Structured data type is determined by the following description:

struct structure_name
{
elements_description
};

The name of the structure can not be used as an identifier (variable name or function).It should be borne in mind that in MQL5 structure elements follow one another directly, without smoothing.In language C + + compiler such indication is made by using.

#pragma pack(1)

If you want to do another alignment in the structure, it is necessary to use the auxiliary members, "fillers" right size.

Example:

struct trade_settings
{
uchar slippage; // Value of the permissible slip-size 1 byte
char reserved1; // 1 byte passes
short reserved2; // Skip 2 bytes
int reserved4; // Another 4 bytes pass. Ensure alignment of the boundary 8 bytes
double take; // Values of the price fixing profit
double stop; // Price value protective stop
};

This description is aligned structures are necessary only for the transfer of the imported dll-functions.

Attention: This example illustrates a correctly designed data. It would be better first to declare the data take, and stop Larger type double and then declare a member of the slippage type double. In this case, the internal representation of data will always be the same regardless of the value specified in #pragma pack().

If the structure contains a variable of type string and/or object of a dynamic array, The compiler assigns to such a structure implicit constructor, which is reset all members of the structure type string and initialize the object for a dynamic array.

Structures that do not contain lines and facilities of dynamic arrays are called simple structures, variables such structures can be freely copied each other, even if they are different structures.

Access to Structure Members

The name of the structure is a new type of data and allows you to declare variables of this type.The structure can be declared only once within the project.Access to the members of the structures produced by operation point (.).

Example:

struct trade_settings
{
double take; // Values of the price fixing profit
double stop; // Price value protective stop
uchar slippage; // Value of the permissible slip
};
//--- Set up and initialize a variable of type trade_settings
trade_settings my_set={0.0,0.0,5};
if (input_TP>0) my_set.take=input_TP;
Classes

Classes are different from the structures:

· The ads use the keyword class;
· By default, all class members have access specifier private, unless otherwise indicated. Members of the data structure has a default type of access is public, unless otherwise indicated;
· class objects always have a table virtual functions, even if the class is not declared a single virtual function. Structures can not have virtual functions;
· classes can be inherited only on the classes, structures can be inherited only from the structures.

Classes and structures can have an explicit constructor and destructor.If you explicitly define a constructor to initialize a structure variable or class with the initialization sequence is not possible.

Example:

struct trade_settings
{
double take; // Values of the price fixing profit
double stop; // Price value protective stop
uchar slippage; // Value of the permissible slip
//--- Constructor
trade_settings() { take=0.0; stop=0.0; slippage=5; }
//--- Destructor
~trade_settings() { Print("This is the end"); }
};
//--- Compiler will generate an error message that is initialized
trade_settings my_set={0.0,0.0,5};

Constructors and Destructors

Designer - a special feature, which is called automatically when an object of structure or class and is typically used to initialize the class members.Next we will talk only about the classes, all of the above applies to the structures, unless otherwise.The name of the constructor must match the name of the class.The constructor has no return type (you can specify the type of void). In MQL5 designers do not have any input parameters. Thus, each class can have only one constructor.

Class memebers: strings, dynamic arrays and objects that require initialization, in any case be initialized, regardless of the designer.

Destructor - is a special function that is called automatically when an object is destroyed class.The name of the destructor is written as a class name with a tilde (~).Strings, dynamic arrays and objects, requiring deinitialization, in any case be deinitsializirovany regardless of the destructor.If a destructor, these actions will be made after calling destructor.

Defining Class Methods

Options-class methods can be defined as inside the classroom and outside the class declaration.If the method is defined within a class, then his body should be immediately after the announcement of the method.

Example:

class CTetrisShape
{
protected:
int m_type;
int m_xpos;
int m_ypos;
int m_xsize;
int m_ysize;
int m_prev_turn;
int m_turn;
int m_right_border;
public:
void CTetrisShape();
void SetRightBorder(int border) { m_right_border=border; }
void SetYPos(int ypos) { m_ypos=ypos; }
void SetXPos(int xpos) { m_xpos=xpos; }
int GetYPos() { return(m_ypos); }
int GetXPos() { return(m_xpos); }
int GetYSize() { return(m_ysize); }
int GetXSize() { return(m_xsize); }
int GetType() { return(m_type); }
void Left() { m_xpos-=SHAPE_SIZE; }
void Right() { m_xpos+=SHAPE_SIZE; }
void Rotate() { m_prev_turn=m_turn; if(++m_turn>3) m_turn=0; }
virtual void Draw() { return; }
virtual bool CheckDown(int& pad_array[]);
virtual bool CheckLeft(int& side_row[]);
virtual bool CheckRight(int& side_row[]);
};

Options with SetRightBorder (int border) on the Draw () are declared and defined directly inside the class CTetrisShape.

Designer CTetrisShape () and methods CheckDown (int & pad_array []), CheckLeft (int & side_row []) and CheckRight (int & side_row []) just declared inside the class, but not yet identified.Definitions of these functions should continue to follow the code.In order to define the method outside the class, used scope resolution operator, as the context, a class name.

Example:

//+------------------------------------------------------------------+
//| Constructor of the base class |
//+------------------------------------------------------------------+
void CTetrisShape::CTetrisShape()
{
m_type=0;
m_ypos=0;
m_xpos=0;
m_xsize=SHAPE_SIZE;
m_ysize=SHAPE_SIZE;
m_prev_turn=0;
m_turn=0;
m_right_border=0;
}
//+------------------------------------------------------------------+
//| Check ability to move down (for the stick and cube) |
//+------------------------------------------------------------------+
bool CTetrisShape::CheckDown(int& pad_array[])
{
int i,xsize=m_xsize/SHAPE_SIZE;
//---
for(i=0; i<xsize; i++)
{
if(m_ypos+m_ysize>=pad_array[i]) return(false);
}
//---
return(true);
}

Public, Protected and Private Access Modifiers

In developing a new class is recommended to restrict access to the members outside. For these purposes keywords private ro protected. Access this case, the hidden data can only function methods of same class.If you use the keyword protected, then access to the hidden data can be carried out and the methods of classes - heirs of this class. Absolutely the same manner may be limited access to functions and methods on the class.

If you need to completely open access to the members and / or methods of a class, then use the keyword public.

Example:

class CTetrisField
{
private:
int m_score; // Score
int m_ypos; // Current position of the figures
int m_field[FIELD_HEIGHT][FIELD_WIDTH]; // Matrix glass
int m_rows[FIELD_HEIGHT]; // Numbering series glass
int m_last_row; // Last free row
CTetrisShape *m_shape; // Tetris figure
bool m_bover; // Game over
public:
void CTetrisField() { m_shape=NULL; m_bover=false; }
void Init();
void Deinit();
void Down();
void Left();
void Right();
void Rotate();
void Drop();
private:
void NewShape();
void CheckAndDeleteRows();
void LabelOver();
};

Any members and class methods that are declared after the specifierpublic: (and before the next access specifier)Available for any treatment program to the object of this class.In this example the following members: function CTetrisField (), Init (), Deinit (), Down (), Left (), Right (), Rotate () and Drop ().

Any members that are declared after the access specifier to the elementsprivate: (and before the next access specifier)Available only by member functions of this class. Specifiers access elements always ends with a colon (:) and may appear in the definition of class many times.

Access to the members of the base class can be overridden when inheritance in derived classes.


Object of Dynamic Array

MQL5 Reference / Language Basics / Data Types / Object of Dynamic Array

Object of Dynamic Array

Dynamic Arrays

Dynamic array represents a structure of 40 bytes. Non ad is not more than 4-dimensional array.

struct MqlArrayObject
{
ushort type; // Encoded data type
ushort flags; // Flags that determine the status of the array
uint item_len; // Size of one element of an array of bytes
int allocated; // Actual size, allocated for the array
int range0; // Size of the first measurement (initially equal to 0)
int range1; // Size of the second measurement, if available. Otherwise 0
int range2; // Size of the third dimension, if any. Otherwise 0
int range3; // Size of the fourth dimension, if any. Otherwise 0
int reserved0; // Data for
int reserved1; // Internal
int reserved2; // Usage
};

When you declare a dynamic array (an array of unspecified value in the first pair of square brackets), the compiler automatically creates a variable of the above structure (a dynamic array object) and provides the code to initialize the.

Example:

double matrix[][10][20]; // 3-dimensional dynamic array
ArrayResize(matrix,5); // Set the size of the first measurement

Static Arrays

When you explicitly specify all significant dimensions of the array pre-compiler allocates the required memory size.Such an array is called static.Nevertheless, the compiler allocates additional memory for the object of a dynamic array, which (object) is associated with pre-distributed static buffer (a memory for storing the array).

Creating a dynamic array object is due to the possible need to pass this static array as a parameter in any function.

Examples:

double stat_array[5]; // 1-dimensional static array
some_function(stat_array);
...
bool some_function(double& array[])
{
if(ArrayResize(array,100) return(false);
...
return(true);
}

Arrays of structures

When you declare a static array as a member of the structure of a dynamic array object is not created. This is done to ensure compatibility of data structures used in the Windows API.

However, static arrays that are declared as members of the structures, you can also send MQL5-function.In this case, the transfer option will create a temporary object of a dynamic array, associated with a static array - a member of the structure.


Typecasting

MQL5 Reference / Language Basics / Data Types / Typecasting

Typecasting

Converting numeric types

Often necessary to convert one numeric type to another. Not everyone is allowed to convert a numeric type to another, allowed changes in MQL5 shown in the scheme:

Solid lines with arrows indicate the changes that are performed without loss of information. Instead of type char can be a type bool (Both are in the memory of 1 byte), instead of type int, you can use the type color (4 bytes), but instead let the type of type long datetime (with 8 bytes).The four dashed lines of gray, and arrows signify the transformation, in which loss can occur exactly.For example, the number of digits in whole number 123456789 (int) Exceeds the number of digits that can be represented by typefloat.

int n=123456789;
float f=n; // the content of f is equal to 1.234567892E8
Print("n=",n," f=",f);
// result n= 123456789 f= 123456792.00000

Number converted to float in the same order, but somewhat less accurate.Inverses black arrows, carried out with the possible loss of information. Conversions between char and uchar, short and ushort, int and uint, long and ulong (both sides conversions are meant), may lead to the loss of data.

As a result of conversion floating point values to integer type fractional part is always discarded.If you want to round a float to the nearest whole number (which in many cases is more useful), you must use the MathRound().

Example:

//--- Gravitational acceleration
double g=9.8;
double round_g=(int)g;
double math_round_g=MathRound(g);
Print("round_g= ",round_g);
Print("math_round_g =",math_round_g);
/*
Result:
round_g = 9.00000000
math_round_g = 10.00000000
*/

If two values are combined binary operator before attempting the operation operand is converted to the type of young the older type in accordance with the priority given to the scheme:

The data types char, uchar, short, and ushort operations certainly are a type int.

Examples:

char c1=3;
//--- First example
double d2=c1/2+0.3;
Print("c1/2+0.3 =",d2);
// Result: c1/2+0.3 = 1.30000000

//--- Second example
d2=c1/2.0+0.3;
Print("c1/2.0+0.3 =",d2);
// Result: c1/2.0+0.3 = 1.80000000

Calculated expression consists of two operations.In the first example the variable c1 of type char is converted to a temporary variable of type int, because the second operand of division operation, the constant 2 is an older type int.As a result of integer division 3 / 2 has the value 1, which is of type int.

In the second operation of the first example of the second operand appears constant 0.3, which is of type double, so the result of the first operation is converted into a temporary variable of type double with a value of 1.0.

In the second example the variable of type char c1 preobazuetsya to a temporary variable of type double, because the second operand of division operation, the constant 2.0, is of type double; further change is not made.

Typecasting Numeric Types

In terms of language MQL5 can be used as an explicit or implicit casting. Explicit type conversion is written as follows:

var_1 = (type)var_2;

As variable var_2 may be an expression or result of a function. Also allowed a functional record explicit casts:

var_1 = type(var_2);

Consider an explicit conversion on the basis of the first example.

//--- Third example
double d2=(double)c1/2+0.3;
Print("(double)c1/2+0.3 =",d2);
// Result: (double)c1/2+0.3 = 1.80000000

Before the operation division variable c1 is clearly a type of double.Now the integer constant 2 leads to the 2.0 type double, so as a result of converting the first operand has type double.In fact, the explicit type conversion is a unary operation.

In addition, when you try to cast the result may go beyond the permissible range. In this case, the truncation occurs. For example:

char c;
uchar u;
c=400;
u=400;
Print("c=",c); // Result from =- 112
Print("u=",u); // Result u=144

Before performing operations (except for assignment operators) are transformed into type, which has the highest priority, and before the assignment operators - to target type.

Examples:

int i=1/2; // No casts, result: 0
Print("i=1/2 ",i);

int k=1/2.0; // Expression is of type double,
Print("k=1/2 ",k); // Then reduced to the target type int, result: 0

double d=1.0/2.0; // No casts, result: 0
Print("d=1/2.0; ",d);

double e=1/2.0; // Expression is of type double,
Print("e=1/2.0; ",e);// Which coincides with the target type, result: 0.5

double x=1/2; // Expression of type int is the target type double,
Print("x=1/2; ",x); // Output: 0.0

Typecasting String Type

Type string has the highest priority among the common types.Therefore, if the operation is one of the operands is of type string, then the other operand will be cast to a string automatically.It should be borne in mind that for a string is permitted only two-place operation of addition.Acceptable explicit string type variable to any numeric type.

Examples:

string s1=1.0/8; // Expression is of type double,
Print("s1=1.0/8; ",s1); // Then to the target type string,
// Result: "0.12500000" (a string containing 10 characters)

string s2=NULL; // Deinitialization line
Print("s2=NULL; ",s2); // Result: an empty string
string s3="Ticket N"+12345; // Expression is of type string,
Print("s=\"Ticket N"+12345,s3);

string str1="true";
string str2="0,255,0";
string str3="2009.06.01";
string str4="1.2345e2";
Print(bool(str1));
Print(color(str2));
Print(datetime(str3));
Print(double(str4));
Typecasting of Simple Structures Data Types

Data type simple structures you can assign each other. Thus in assignment operations both operands, and the left and right, must be the type of structures.As such term by term reduction is not made, is a simple copy.If the size of the structures are different, then copied the number of bytes corresponding to a smaller size.Thus offset the lack of association (union) in the language MQL5.

Examples:

struct str1
{
double d;
};
//---
struct str2
{
long l;
};
//---
struct str3
{
int low_part;
int high_part;
};
//---
struct str4
{
string s;
};
//+------------------------------------------------------------------+
void OnStart()
{
str1 s1;
str2 s2;
str3 s3;
str4 s4;
//---
s1.d=MathArcsin(2.0); // Get the invalid number -1. # IND
s2=s1;
printf("1. %f %I64X",s1.d,s2.l);
//---
s3=s2;
printf("2. high part of long %.8X low part of long %.8X",
s3.high_part,s3.low_part);
//---
s4.s="some constant string";
s3=s4;
printf("3. buffer len is %d constant string address is 0x%.8X",
1s3.low_part,s3.high_part);
}

Typecasting Pointers of Base Classes to Pointers of Derivative Classes

Objects of open generated class can also be seen as objects of the corresponding base class.This leads to some interesting consequences.For example, despite the fact that objects of different classes generated by a single base class, may differ significantly from each other, we can create them linked list (List), as we view them as objects of base type.But the converse is not true: the base class objects are not automatically derived class object.

You can use explicit casting to convert the pointers to the base class pointers derived class.But it must be fully confident in the admissibility of such a transformation, because otherwise there critical runtime error and mql5-program will be stopped.


Void Type and NULL Constant

MQL5 Reference / Language Basics / Data Types / Void Type and NULL Constant

Void Type and NULL Constant

Syntactically type void is a fundamental type along with types of char, uchar, bool, short, ushort, int, uint, color, long, ulong, datetime, float, double and string.This type is used either to indicate that the function does not return a value, either as a parameter to a function denotes the absence of parameters.

Predetermined constant variables NULL has type void. It can be assigned to variables of any other fundamental type without conversion. It also enables the comparison of the fundamental types of variables with a NULL.

Example:

//--- If the row is not initialized, then assign it to our predefined value
if(some_string==NULL) some_string="empty";

Also NULL can be compared pointers to objects created with the new operator.


Objects Pointers

MQL5 Reference / Language Basics / Data Types / Objects Pointers

Objects Pointers

In MQL5 is possible to dynamically create objects of complex type. This is done by the ne w operator, which returns a descriptor of the created object. Descriptor has a size of 8 bytes. Syntactically descriptors of objects in MQL5 similar to pointers in C + +.

Examples:

MyObject* hobject= new MyObject();

Again, in contrast to C + +, variable hobject from the example above is not a pointer to the memory, and is a descriptor of the object.


Operations and Expressions

MQL5 Reference / Language Basics / Operations and Expressions

Operations and Expressions

Some characters and character sequences given special importance. This - so-called symbols of operations, such as:

+ - * / % Symbols of arithmetic operations
&& || Symbols of logical operations
= += *= Characters assignment operators

Symbols of operations used in expressions and have a sense when they are given the appropriate operands.Also of particular importance punctuation.Punctuation include parentheses, braces, comma, colon and semicolon.

Symbols of operations, punctuation and spaces are used to separate the elements of language.

This section discusses the following topics:

· Expressions
· Arithmetic Operations
· Assignment Operations
· Relational Operations
· Logical Operations
· Bitwise Operations
· Other Operations
· Priorities and Operations Order


Expressions

MQL5 Reference / Language Basics / Operations and Expressions / Expressions

Expressions

The expression consists of one or more operands and symbols of operations. Can be written in several lines.

Examples:

a++; b = 10; // Several expressions are located on one line
//--- One expression divided into several lines
x = (y * z) /
(w + 2) + 127;

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


Arithmetic Operations

MQL5 Reference / Language Basics / Operations and Expressions / Arithmetic Operations

Arithmetic Operations

By arithmetic are additive and multiplicative operations:

Sum of variables i = j + 2;
Subtraction of variables i = j - 3;
Changing the sign x = - x;
Multiplication of variables z = 3 * x;
Quotient from division i = j / 5;
Residue of divisions minutes = time % 60;
Adding 1 to variable value i++;
Adding 1 to variable value ++i;
Subtracting 1 from variable value k--;
Subtracting 1 from variable value --k;

Increment and decrement operators are applied only to variables, constants do not apply to.Prefiksnye increment (+ + i) and decrement (- k) applied to the variable immediately before use this variable in the expression.

Post-increment (i + +) and decrement (k -) are applied to the variable immediately after the use of this variable in the expression.

Examples:

int a=3;
a++; // Valid expression
int b=(a++)*3; // Invalid expression


Assignment Operations

MQL5 Reference / Language Basics / Operations and Expressions / Assignment Operations

Assignment Operations

The value of expression, which includes the assignment operator is the left operand after the assignment:

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

The following operations combine arithmetic or bitwise operator with the assignment operator:

Increasing value of the y variable by y + = x;.
Reducing value of the y variable by x y -= x;
Multiplying value of the y variable by x y *= x;
Dividing value of the y variable by x y /= x;
Residue of division of value of the y variable by x y %= x;
The shift of the binary representation of y to the right by x bit y >>= x;
The shift of the binary representation of y to the left by x bit y y <<= x;
AND bitwise operation of binary representations of y and x y &= x;
OR bitwise operation of binary representations of y and x y |= x;
Excluding OR bitwise operation of binary representations of y and x y ^= x;

Bitwise operations are made only with integers.When performing the logical presentation of the shift y right / left by x bits are used under 5 bits the value x, the senior level are discarded, ie, the shift is made to the 0-31 bits.

When the% operator = (value of y modulo x) sign of the result coincides with the sign of the dividend.

In terms of the assignment operator may be present many times. In this case, processing of expression is from left to right:

y=x=3;

First, the variable x will be assigned the value 3, then the variable y is assigned the value of x, then there is also 3.


Relational Operations

MQL5 Reference / Language Basics / Operations and Expressions / Relational Operations

Relational Operations

Boolean FALSE is integer value of zero, and TRUE is any non-zero.

The value of expressions containing relational operators or logic operations are FALSE (0) or TRUE (1).

True if a is equal to b a == b;
True if a is not equal to 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 equal to b a <= b;
True if a is greater than or equal to b a >= b;

You can not compare two real numbers to equal each other.In most cases, two seemingly identical numbers can be unequal because of different values in the 15th decimal place.In order to compare two real numbers to compare the normalized difference of these numbers with zero.

Example:

bool CompareDoubles(double number1,double number2)
{
if(NormalizeDouble(number1-number2,8)==0) return(true);
else return(false);
}
void OnStart()
{
double first=0.3;
double second=3.0;
double third=second-2.7;
if(first!=third)
{
if(CompareDoubles(first,third))
printf("%.16f %.16f are equal",first,third);
}
}
// Result: 0.3000000000000000 0.2999999999999998 are equal


Logical Operations

MQL5 Reference / Language Basics / Operations and Expressions / Logical Operations

Logical Operations

Logical Negation NOT (!)

Operand of the logical negation (!) Must have arithmetic type. The result is TRUE (1), if the operand is FALSE (0), and is equal to FALSE (0), if the operand is not equal to FALSE (0).

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

Logical Operation OR (||)

Logical OR operator (| |) values of x and y. The value of the expression is TRUE (1), if true (not zero) value of x or y. Otherwise - FALSE (0).

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

Logical Operation AND (&&)

Logical operation AND (& &) values of x and y.The value of the expression is TRUE (1), if the values of x and y are true (not zero).Otherwise - FALSE (0).Logical expressions are evaluated fully, t.e., Not applied to them the scheme of so-called "short Assessment.

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


Bitwise Operations

MQL5 Reference / Language Basics / Operations and Expressions / Bitwise Operations

Bitwise Operations

One's complement

Addendum to the unit value of the variable. Value of the expression contains 1 in all digits, in which the variable contains 0, and 0 in all digits, in which the variable contains 1.

b = ~n;

Example:

char a='a',b;
b=~a;
Print("a=",a, " b=",b);
// The result will be:
// a= 97 b= -98

Right Shift

The binary representation of x is shifted to the right by y bits.If you shift the value is unsigned type, then made a logical shift right, that is, the level will be vacated on the left filled with zeros.

If, however, shifts the value of a type of sign, then made an arithmetic shift right, that is vacated will be filled on the left level value of the sign bit (if the number is positive, then the value of sign bit is 0 if the number is negative, the value of the sign bit is 1).

x = x >> y;

Example:

char a='a',b='b';
Print("Before: a=",a, " b=",b);
//--- Shall make shift to the right
b=a>>1;
Print("After: a=",a, " b=",b);
// The result will be:
// Before: a= 97 b= 98
// After: a= 97 b= 48

Left Shift

The binary representation of x is shifted to the left by y bit positions vacated right level are filled with zeros.

x = x << y;

Example:

char a='a',b='b';
Print("Before: a=",a, " b=",b);
//--- Shall make shift to the left
b=a<<1;
Print("After: a=",a, " b=",b);
// The result will be:
// Before: a= 97 b= 98
// After: a= 97 b= -62

Bitwise AND Operation

Bitwise operators and binary representations of x and y. Value of the expression contains a 1 (TRUE) in all discharges, in which the x, y, and contain non-zero, and 0 (FALSE) in all other discharges.

b = ((x & y) != 0);

Example:

char a='a',b='b';
//--- AND operation
char c=a&b;
Print("a=",a," b=",b);
Print("a&b=",c);
// The result will be:
// a= 97 b= 98
// a&b==96

Bitwise OR Operation

Bitwise operators or binary representations of x and y. Value of the expression contains 1 in all digits, in which x or y does not contain 0, and 0 - in all other discharges.

b = x | y;

Example:

char a='a',b='b';
//--- OR operation
char c=a|b;
Print("a=",a," b=",b);
Print("a|b=",c);
// The result will be:
// a= 97 b= 98
// a|b==99

Bitwise Excluding OR Operation

Bitwise exclusive OR (eXclusive OR) binary representations of x and y.Value of the expression contains a 1 in those discharges, in which x and y have different binary values, and 0 - for all other discharges.

b = x ^ y;

Example:

char a='a', b='b';
//--- Excluding OR operation
char c=a^b;
Print("a=",a," b=",b);
Print("a^b=",c);
// The result will be:
// a= 97 b= 98
// a^b==99

Bitwise operations are performed only with integers.


Other Operations

MQL5 Reference / Language Basics / Operations and Expressions / Other Operations

Other operations

Indexing ( [] )

When accessing the i-th element of the array expression value is the value of a variable with the ordinal number i.

Example:

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

Index of the array can only be an integer. Allowed no more than four-dimensional arrays. Indexation of each measurement is from 0 to dimension size -1. In the particular case of one-dimensional array of 50 elements in the first element will look like array [0], to the last item - array [49].

When you access an array beyond performing subsystem generates a critical error, and the program will be stopped.

Calling Function with Arguments x1, x2 ,..., xn

Each argument can be a constant, variable, or expression of the type.Transferable arguments are separated by commas and must be within parentheses, opening parenthesis must follow the name of the called function.

The value of expression is the return value of.If the return type of function is void, then the call such a function can not be placed in the right assignments.Note that the order of expressions x1,..., Xn guaranteed.

Example:

int length=1000000;
string a="a",b="b",c;
//---
int start=GetTickCount(),stop;
long i;
for(i=0;i<length;i++)
{
c=a+b;
}
stop=GetTickCount();
Print("time for 'c=a+b'=",(stop-start),"milliseconds, i =",i);

Comma Operation ( , )

Expressions separated by commas, are evaluated from left to right.All the side effects of calculating the left expression can occur before the calculation of the expression.The type and value of the results coincide with the type and value of the expression.As an example, consider the list of transmitted parameters (see above).

Example:

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

For direct access to the public members structures and classes use the dot operator. Syntax:

Variable_name_of_structure_type.Member_name

Example:

struct SessionTime
{
string sessionName;
int startHour;
int startMinutes;
int endHour;
int endMinutes;
} st;
st.sessionName="Asian";
st.startHour=0;
st.startMinutes=0;
st.endHour=9;
st.endMinutes=0;
Operation of Context Permission ( :: )

Each function in mql5-program has its own execution context. For example, a system function Print() performed in a global context. Imported functions are called in the context of the imports. Options methods classes have the context of the relevant class. The syntax of the scope resolution operator:

[Context_name]::Function_name(parameters)

In the absence of the scope resolution operator, function is sought in the immediate context.In the absence of function in the local context, search is made in a global context.

Also, scope resolution operator is used to function definition-class member.

type Calss_name::Function_name(parameters_description)
{
// Body of function
}

Example:

#property script_show_inputs
#import"kernel32.dll"
int GetLastError(void);
#import

class CCheckContext
{
int m_id;
public:
CCheckContext() { m_id=1234; }
protected:
int GetLastError() { return(m_id); }
};
class CCheckContext2 : public CCheckContext
{
int m_id2;
public:
CCheckContext2() { m_id2=5678; }
void Print();
protected:
int GetLastError() { return(m_id2); }
};
void CCheckContext2::Print()
{
::Print("Terminal GetLastError",::GetLastError());
::Print("kernel32 GetLastError",kernel32::GetLastError());
::Print("parent GetLastError",CCheckContext::GetLastError());
::Print("our GetLastError",GetLastError());
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
CCheckContext2 test;
test.Print();
}
//+------------------------------------------------------------------+
Operation of Taking Size of Data Type or Size of Object of any Type of Data ( sizeof )

With operations sizeof you can determine the amount of memory which corresponds to the identifier or type. Sizeof operator has the following format:

Example:

sizeof(expression)

As an expression can be any identifier, or type name enclosed in brackets.Note that can not be used by the name of the type void, and the identifier can not be applicable to the field of bits, or be a function name.

If the expression is the name of a static array (that is, given the first dimension), then the result is the size of the array (m.e.product of the number of elements on the length of type).If the expression is the name of a dynamic array (first dimension is not specified), the result will be the size of the object dynamic array.

When sizeof applied to the name type of structure or class or to the identifier having a type of structure or class, then the result is the actual size of the structure or class.

Example:

struct myStruct
{
char h;
int b;
double f;
} str;
Print("sizeof(str) =",sizeof(str));
Print("sizeof(myStruct) =",sizeof(myStruct));

Costing happen at compile time.


Priorities and order of operations

MQL5 Reference / Language Basics / Operations and Expressions / Priorities and Operations Order

Priorities and Operations Order

For each group of operations in the priority table is the same. The higher the priority of operations, the higher it is located in the table. The order of performance determines the grouping of operations and operands.

Attention: Priority of operations in the language MQL5 the priorities adopted in C + +, and differs from the priority given in the language MQL4.

Operation | Desciption | Execution Order
() [] . | Function Call Isolation of an array element Isolation of structural element | From left to right
! ~ -- ++ -- (type) sizeof | Logical negation Bitwise negation (complement) Changing sign Increase per unit (increment) Reducing unit (decrement) Casting Determination of the size in bytes | Right to left
* / % | Multiplication Division Modulo Division | From left to right
+ -- | Addition Subtraction | From left to right
<< >> | Shift left Shift right | From left to right
< <= > >= | Less than Less than or equal More than Greater than or equal | From left to right
== != | Equals Not equal | From left to right
& | Bitwise AND operation | From left to right
^ | Bitwise exclusive OR (exclude OR) | From left to right
| | Bitwise OR operation | From left to right
&& | Logical AND operation | From left to right
|| | Logical OR operation | From left to right
?: | Conditional Operator | Right to left
= *= /= %= += -= <<= >>= &= ^= |= | Assignment Multiplication with assignment Division with assignment Modulo with assignment Addition to the assignment Subtraction assignment Left shift with assignment Right shift assignment Bitwise AND with assignment Exclusive OR with assignment Bitwise OR with assignment | Right to left
, | Comma | From left to right

To change the order of operations used parentheses, which have the highest priority.


Operators

MQL5 Reference / Language Basics / Operators

Operators

Operators of language describe some algorithmic steps that must be done to solve the problem.The body of the program - a sequence of such operators.Of consecutive operators are separated by semicolons.

Operator | Description
Composite operator {} | One or more operators of any type, enclosed in curly braces { }
Expression operator (;) | Any expression that ends with a semicolon (;)
return operator | Terminates the current function and returns control to the caller program
if-else conditional operator | Used when necessary to make a choice
?: conditional operator | A simple analog conditional statement if-else
switch selection operator | Transfers the control to the operator, which corresponds to the expression
while loop operator | Performs operator up until the test expression becomes false. Checking the expression is made before each iteration
for loop operator | Performs operator up until the test expression becomes false. Checking the expression is made before each iteration
do-while loop operator | Performs operator up until the test expression becomes false.Checks conditions for termination made at the end, after each passage cycle.The loop body is always executed at least once.
break operator | Terminates the nearest attached external operator switch, while, do-while or for
continue operator | Passes control to the beginning of the nearest external operator cycle while, do-while or for
new operator | Creates an object of appropriate size and returns a descriptor of the created object.
delete operator | Deletes the object created by new operator

A single operator can hold one or more lines.Two or more operators can be located on one line.The operators control the order of execution (if, if-else, switch, while and for), can be nested.

Example:

if(Month() == 12)
if(Day() == 31) Print("Happy New Year!");


Composite Operator

MQL5 Reference / Language Basics / Operators / Composite Operator

Composite Operator

A compound statement (block) consists of one or more operators of any type, enclosed in curly braces { }. After the closing brace should not be a semicolon (;).

Example:

if(x==0)
{
Print("invalid position x=",x);
return;
}


Expression Operator

MQL5 Reference / Language Basics / Operators / Expression Operator

Expression Operator

Any expression that ends with a semicolon (;), is the operator. The following are examples of operators-expressions.

Assignment Operator

Identifier = expression;

x=3;
y=x=3;
bool equal=(x==y);

In terms of the assignment operator may be present many times. In this case, processing of expression is from left to right:

Operation of Function Calling

Function_name (argument1,..., argumentN);

FileClose(file);

Empty Operator

Consists only of a semicolon (;) and is used to denote an empty body are controlled by the operator.


Return Operator

MQL5 Reference / Language Basics / Operators / Return Operator

Return operator

Return statement terminates the current function and returns control to the caller program. The result of evaluating the expression returned to the calling function. The expression may contain an assignment operator.

Example:

int CalcSum(int x, int y)
{
return(x+y);
}

In functions with return type void must use operator return without expression:

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

The final brace of a function involves an implicit response to the operator return without expression.


If-Else Conditional Operator

MQL5 Reference / Language Basics / Operators / If-Else Conditional Operator

If-Else Conditional Operator

Operator IF - ELSE used if necessary to make a choice. Formally, the syntax is:

if (expression)
operator1
else
operator2

If the expression is true, then the following statement1 and control is transferred to the statement following the operatorom2 (ie statement2 not performed). If the expression is false, then the following statement2.

Part else of if operator can be omitted. Therefore, in nested if operators with missing else part an ambiguity may appear. In this case else is associated with the closest previous if operator in the same box without else part.

Examples:

//--- Else belongs to the second operator if:
if(x>1)
if(y==2) z=5;
else z=6;
//--- Part applies to the first else if statement
if(x>l)
{
if(y==2) z=5;
}
else z=6;
//--- Nested operators
if(x=='a')
{
y=1;
}
else if(x=='b')
{
y=2;
z=3;
}
else if(x=='c')
{
y=4;
}
else Print("ERROR");


?: Conditional Operator

MQL5 Reference / Language Basics / Operators / ?: Conditional Operator

?: Conditional Operator

The general form of the ternary operator is as follows:

expression1? expression2:expression3

As a first operand - "expr1" - can be used any expression that evaluates to a value of type bool. If the result is true, then the statement is executed, given the second operand, that is, "expression2".

If the first operand is false then performed a third operand - vyrazhenieZ. The second and third operands, ie "expr2" and "vyrazhenieZ" should return a value of one type and should not be of type void. The result of the conditional statement is the result of vyrazheniya2 a result of the expression 3, depending on the result of expression 1.

Example:

//--- Number difference between the prices of opening and closing on the day sweep
double true_range = (High==Low)?0:(Close-Open)/(High-Low);

This entry is equivalent to the following:

double true_range;
if(High==Low)true_range=0; // If High and Low are equal
else true_range=(Close-Open)/(High-Low); // If swing is not null


Switch Selection Operator

MQL5 Reference / Language Basics / Operators / Switch Selection Operator

Switch Selection Operator

Compares the value of the expression with constants in all variants case andtransfers control to the operator, which corresponds to the value of expression. Each option case can be marked integer constant, A symbolic constant or constant expression. A constant expression can not include variables or function calls. Expression operator switch should be integer.

switch(expression)
{
case constant: operators
case constant: operators
...
default: operators
}

Operators associated with the label default are executed if none of the constants in the operators case not equal to the value of expression. Option default not necessarily be announced and will not necessarily be the last. If none of the constant does not correspond to the value of expression and alternative default absent, then nothing happens.

Keyword case with the constant are just labels, and if the operators will be implemented for some variants case then the operators will continue to run all subsequent versions until until a statement break that you can associate a sequence of operators with several options.

A constant expression is evaluated during compilation. No two constants in a switch statement can not have the same value.

Examples:

//--- First example
switch(x)
{
case 'A':
Print("CASE A");
break;
case 'B':
case 'C':
Print("CASE B or C");
break;
default:
Print("NOT A, B or C");
break;
}

//--- Second example
string res="";
int i=0;
switch(i)
{
case 1:
res=i;break;
default:
res="default";break;
case 2:
res=i;break;
case 3:
res=i;break;
}
Print(res);
/*
Result
default
*/


While Loop Operator

MQL5 Reference / Language Basics / Operators / While Loop Operator

While Loop Operator

Operator while consists of a test expression and the operator, which must be fulfilled:

while(expression)
operator;

If the expression is true, then the statement is executed before until expression becomes false.If the expression is false, then control is passed to the next operator.The value of expression is determined to execute a.Consequently, if the expression is false from the outset, the operator generally does not hold.

Example:

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


For Loop Operator

MQL5 Reference / Language Basics / Operators / For Loop Operator

For Loop Operator

The for statement consists of three expressions and executes the:

for(expression1; expression2; expression3)
operator;

Expression1 describes the initialization cycle. Expression2 - check the conditions on a loop. If it is true, statement is executed loop for. Everything is repeated until expr2 becomes false. If it is false, the loop ends and control is transferred to the next statement. VyrazhenieZ evaluated after each iteration.

Operator for equivalent to the following sequence of statements:

expression1;
while(expression2)
{
operator;
expression3;
};

Any of the three or all three expressions in the statement for may be absent, but separating them with a semicolon (;) can not be omitted. If you omit expression2, it is considered that it is always true. Operator for(;;) Is an infinite loop, equivalent to the operator while(1). Each of expression1 and expression3 may consist of several expressions, combined operator comma ','.

Examples:

for(x=1;x<=7;x++) Print(MathPower(x,2));
//--- Another example
for(;;)
{
Print(MathPower(x,2));
x++;
if(x>10) break;
}
//--- Third example
for(i=0,j=n-l;i<n;i++,j--) a[i]=a[j];


Do While Loop Operator

MQL5 Reference / Language Basics / Operators / Do While Loop Operator

Do While Loop Operator

Cycles for and while check the end of the beginning rather than at the end of the cycle. The third statement cycle do - while the condition of completion at the end, after each passage cycle. The loop body is always executed at least once.

do
operator;
while(expression)

Statement is executed, then expression is evaluated. If it is true, then the statement is executed again, etc. If the expression becomes false, the loop ends.

Example:

//--- Calculate the Fibonacci number sequence
int counterFibonacci=15;
int i=0,first=0,second=1;
int currentFibonacciNumber;
do
{
currentFibonacciNumber=first+second;
Print("i=",i," currentFibonacciNumber=",currentFibonacciNumber);
first=second;
second=currentFibonacciNumber;
i++; // Without this operator to obtain an infinite loop!
}
while(i<counterFibonacci);


Break Termination Operator

MQL5 Reference / Language Basics / Operators / Break Termination Operator

Break Termination Operator

Operator break terminates the nearest attached external operator switch, while, do-while or for. Control is passed to statement following the end. One of the purposes of this operator - to finish the loop when you assign a variable a particular value.

Example:

//--- Search for the first zero element
for(i=0;i<array_size;i++)
if(array[i]==0)
break;


Continue Proceeding Operator

MQL5 Reference / Language Basics / Operators / Continue Proceeding Operator

Continue Proceeding Operator

Operator continue passes control to the beginning of the nearest external operator cycle while, do-while or for, Causing the beginning of the next iteration. This statement is opposed by the action of the operator break.

Example:

//--- Sum of all nonzero elements
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);
}


New Operator of Object Creation

MQL5 Reference / Language Basics / Operators / New Operator of Object Creation

New Operator of Object Creation

Operator new automatically creates an object of appropriate size, is the constructor of the object and returns descriptor of the created object. In case of failure, the operator returns a null descriptor that can be compared with the constant NULL.

New operator can be applied only to objects of complex type (structures and classes ).

Operator shall not be used to create arrays of objects. To do this, use the ArrayResize().

Example:

//+------------------------------------------------------------------+
//| Figure creation |
//+------------------------------------------------------------------+
void CTetrisField::NewShape()
{
m_ypos=HORZ_BORDER;
//--- Randomly create one of the 7 possible shapes
int nshape=rand()%7;
switch(nshape)
{
case 0: m_shape=new CTetrisShape1; break;
case 1: m_shape=new CTetrisShape2; break;
case 2: m_shape=new CTetrisShape3; break;
case 3: m_shape=new CTetrisShape4; break;
case 4: m_shape=new CTetrisShape5; break;
case 5: m_shape=new CTetrisShape6; break;
case 6: m_shape=new CTetrisShape7; break;
}
//--- Draws
if(m_shape!=NULL)
{
//--- Initial installation
m_shape.SetRightBorder(WIDTH_IN_PIXELS+VERT_BORDER);
m_shape.SetYPos(m_ypos);
m_shape.SetXPos(VERT_BORDER+SHAPE_SIZE*8);
//--- Draw
m_shape.Draw();
}
//---
}

It should be noted that the descriptor of the object is not a pointer to the memory.

Object created with operator new, must be explicitly destroyed by the operator delete.


Delete Operator of Object Destruction

MQL5 Reference / Language Basics / Operators / Delete Operator of Object Destruction

Delete Operator of Object Destruction

Operator delete created by the operator removes new object, the destructor of the class and free the memory for the object.As operands used a valid descriptor of an existing object.After the delete operator descriptor object becomes invalid.

Example:

//--- Delete figure
delete m_shape;
m_shape=NULL;
//--- Create a new figure
NewShape();


Options

MQL5 Reference / Language Basics / Functions

Functions

Every task can be broken down into subtasks, each of which can either be directly represented in the form of code, or broken down into even smaller sub-problems. This method is called stepwise refinement. Options are used to write code directly addresses these subtasks. Code that describes what makes a function called function definition:

function_header
{
instructions
}

All that is before the first brace is title function definition, but what is between the braces is body function definition. function header includes a description of return type, name (identifier) and formal parameters. The number of parameters passed to the function is limited and can not exceed 64.

The function can be called from other parts of the program as many times as necessary. In fact, the return type, identifier and function parameter types are function prototype.

Function prototype - this is the function declaration, but not its definition.Due to an apparent declaration of the return type and a list of types of arguments in function calls are possible strict type checking and implicit conversions.Very often function declarations are used in classrooms to improve the readability of code.

The function definition must exactly match its declaration. Each declared function must be defined.

Example:

double // Return value type
linfunc (doubleAdouble b) // Function name and parameter list
{
// Composite operator
return (a + b); // Returned value
}

Operator return can return a value expression in this statement.Value of the expression if necessary converted to the type of the function.A function that returns no value, should be described as having type void.

Example:

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

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

Example:

int somefunc(double a,
double d=0.0001,
int n=5,
bool b=true,
string s="passed string")
{
Print("Mandatory parameter a=",a);
Print("Pass the following parameters: d=",d," n=",n," b=",b," s=",s);
return(0);
}

If any parameter was set default values, then all subsequent parameters must also have default values.

Example of incorrect declaration:

int somefunc(double a,
double d=0.0001, // Declared default value 0.0001
int n, // Default value is not specified !
bool b, // Default value is not specified !
string s="passed string")
{
}


Function Calling

MQL5 Reference / Language Basics / Functions / Function Calling

Function Calling

If a name that has not been described previously, appears in the expression and followed by the left parenthesis, then it is considered by the context name of a function.

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

Arguments (formal parameters) passed by value, t.e.each expression xl,..., Xn is calculated and the value passed to the function.The order of evaluation of expressions and the boot order of values is guaranteed.At runtime checks the number and type of arguments passed to the function.This way the function call is called call by value.

Call function - an expression whose value is the return value.Describe the type of function must match the type of the return value.The function can be advertised or described anywhere in the program on global level, that is, outside of other functions. The function can not be advertised or described in 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);
}

When you call a function with default options, a list of transmitted parameters can limit default not earlier than the first option.

Examples:

void somefunc(double init,
double sec=0.0001, //set default values
int level=10);
//...
somefunc(); // Wrong call. The first option should be mandatory.
somefunc(3.14); // Correct call
somefunc(3.14,0.0002); // Correct call
somefunc(3.14,0.0002,10); // Correct call

When a function, you can not pass parameters, even with default values:

somefunc(3.14, , 10); // Wrong call -> the second parameter is omitted.


Passing Parameters

MQL5 Reference / Language Basics / Functions / Passing Parameters

Passing Parameters

There are two methods by which the machine language can pass arguments to subroutine (function). The first method - to send a parameter by value. This method copies the value argument the formal function parameter. Therefore, any changes in this parameter within the function have no influence on the corresponding argument of the call.

//+------------------------------------------------------------------+
//| Passing parameters by value |
//+------------------------------------------------------------------+
double FirstMethod(int i,int j)
{
double res;
//---
i*=2;
j/=2;
res=i+j;
//---
return(res);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int a=14,b=8;
Print("a and b before call:",a,b);
double d=FirstMethod(a,b);
Print("a and b after call:",a,b);
}
//--- Result of script execution
// a and b before call: 14 8
// a and b after call: 14 8

The second method - pass by reference.In this case, the reference to the parameter (and not its value) is passed to the parameter function.Inside the function, it is used to refer to the actual parameter, specified in the call.This means that the parameter change will affect the argument used to call the function.

//+------------------------------------------------------------------+
//| Passing parameters by link |
//+------------------------------------------------------------------+
double SecondMethod(int &i,int &j)
{
double res;
//---
i*=2;
j/=2;
res=i+j;
//---
return(res);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int a=14,b=8;
Print("a and b before call;",a,b);
double d=SecondMethod(a,b);
Print("a and b after call:",a,b);
}
//+------------------------------------------------------------------+
//--- Result of script
// a and b before call: 14 8
// a and b after call: 28 4

MQL5 uses both methods, with one exception: arrays and variables like structures (class objects) are always passed by reference.In order to exclude changes in the actual parameters (arguments passed to function call) must use the access specifier const. When you try to change the contents of a variable declared with the specifierconstCompiler will generate an error.

Note

It is necessary to remember that parameters are passed to a function back to front, in other words, the very last parameter is calculated and passed at first and then the last but one, etc. The last calculated and passed parameters is the one that stands first after braces.

Example:

void OnStart()
{
//---
int a[]={0,1,2};
int i=0;

func(a[i],a[i++],"First call(i="+string(i)+")");
func(a[i++],a[i],"Second call(i="+string(i)+")");
// Result:
// First call(i=0) : par1 = 1 par2 = 0
// Second call(i=1) : par1 = 1 par2 = 1

}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void func(int par1,int par2,string comment)
{
Print(comment,": par1 =",par1," par2 =",par2);
}

At first call in the mentioned example the i variable firstly takes part in concatenation of strings

"First call(i="+string(i)+")"

at that its value doesn't change. The the i variable takes in calculation of array element a[i++], i.e. after the i element of the array is take, the i variable is incremented. And only after that the first parameter with the chaged value of i variable is calculated.

At the second call when calculating all three parameters one and the same value of i is used, the one that was calculated on the first phase of function calling, and only after the first parameters is calculated the i variable is changed again.


Reloading Functions

MQL5 Reference / Language Basics / Functions / Reloading Functions

Reloading Functions

Usually in the name of functions tend to display its main purpose. Readable programs typically contain a variety and well-matched identifiers. Sometimes different functions are used for the same purposes.Consider, for example, a function that calculates the average value of an array of double precision numbers and the same function, but operating a array of integers.The one and the other is conveniently called AverageFromArray:

//+------------------------------------------------------------------+
//| The calculation of average for an array of type double |
//+------------------------------------------------------------------+
double AverageFromArray(const double array[],int size)
{
if(size<=0) return 0.0;
double sum=0.0;
double aver;
//---
for(int i=0;i<size;i++)
{
sum+=array[i]; // Addition to the double
}
aver=sum/size; // Just divide the sum by the number of
//---
Print("Calculation of the average for an array of type double");
return aver;
}
//+------------------------------------------------------------------+
//| The calculation of average for an array of type int |
//+------------------------------------------------------------------+
double AverageFromArray(const int array[],int size)
{
if(size<=0) return 0.0;
double aver=0.0;
int sum=0;
//---
for(int i=0;i<size;i++)
{
sum+=array[i]; // Addition to the double
}
aver=(double)sum/size;// Give the amount of type double, and divide
//---
Print("Calculation of the average for an array of type int");
return aver;
}

Each function contains the output messages via the function Print();

Print("Calculation of the average for an array of type int");

The compiler selects the desired function in accordance with the types of arguments and their quantity. Rule, which made this choice, called algorithm match the signature. Under the signature refers to a list of types used in the function declaration.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int a[5]={1,2,3,4,5};
double b[5]={1.1,2.2,3.3,4.4,5.5};
double int_aver=AverageFromArray(a,5);
double double_aver=AverageFromArray(b,5);
Print("int_aver=",int_aver," double_aver=",double_aver);
}
//--- Result of the script
// Calculate the average for an array of type int
// Calculate the average for an array of type double
// int_aver= 3.00000000 double_aver= 3.30000000

Overloading is the practice of giving multiple values of.Selecting a specific value depends on the types of arguments derived function.The specific function is selected based on matching the argument list when calling the function parameter list in the function declaration.

When you call an overloaded function, the compiler must have an algorithm to select the appropriate function. Algorithm that performs this choice depends on transformation what type are present.Best Match must be unique.It must be the best for at least one argument, and as well as the other match, for all other arguments.

Below is a matching algorithm for each argument.

Algorithm of Choosing Reloaded Function

1. Use strict compliance (if possible).
2. Try raising the standard type.
3. Try standard type conversion.

The standard type of improvement is better than other standard transformations. Improving - this transformation float to double, and also bool, char, short or enum to int. In addition to the standard transformations include converting arrays similar integer types. With similar types are: bool, char, uchar, since all three types are single-byte integer; dvubaytovye entire short and ushort; 4-byte integer int, uint, and color; long, ulong, and datetime.

Of course, strict compliance is the best. To achieve such consistency can be used typecasting. The compiler can not cope with ambiguous situations. Therefore you should not rely on subtle differences in types and implicit conversions that make the overloaded function unclear.

If in doubt, use explicit conversion to ensure strict compliance.

Examples of overloaded functions in MQL5 You can see an example of functions ArrayInitialize().

Function overloading rules apply to overload class methods.


Description of External Functions

MQL5 Reference / Language Basics / Functions / Description of External Functions

Description of External Functions

Type of external functions defined in another module, should be clearly described.The absence of such a description can lead to errors when compiling, linking, or execution of the program.In describing an external object, use the keyword #import indicating the module.

Examples:

#import "user32.dll"
int MessageBoxW(int hWnd ,string szText,string szCaption,int nType);
int SendMessageW(int hWnd,int Msg,int wParam,int lParam);
#import "lib.ex5"
double round(double value);
#import

With the help of imports can be very easy to describe the functions that are called from external DLL or compiled EX5 libraries.


Events

MQL5 Reference / Language Basics / Functions / Functions of Events Handling

Functions of Events Handling

In the language MQL5 provides some processing predefined events. Functions for handling these events should be defined in the program MQL5; function name, return type, composition parameters (if any) and their types must strictly conform to the description of the event handler function.

That is the type of return value and type of the parameters of the event handler of the client terminal identifies the function that handles an event.If the relevant functions specified otherwise not in accordance with the following descriptions, parameters, or specify a return type, then this function will not be used for handling the event.

OnStart

Function OnStart () event handler is Start, which automatically generated only for running on the execution scripts. Must be of type void, no parameters:

void OnStart();

For function OnStart () is acceptable to specify the return type int.

OnInit

Function OnInit () event handler is Init. Must be of type void or int, no parameters:

void OnInit();

Init event is generated immediately after downloading an expert or an indicator for scripts this event is not generated. Function OnInit () is used for initialization. If OnInit() has the int type of the returned value then non-zero code of return means the unsuccessful initialization and generated the DeInit event with the code of deinitialization reason REASON_INITFAILED.

TheOnInit() function of the void type always means the successful initialization.

OnDeinit

Function OnDeinit () is called when deinitialization and is an event handler Deinit. Must be declared as type void and have one parameter of type const int which contains the code of deinitialization reason. If declared a different type, the compiler will issue a warning, but the function will be called. For scripts Deinit event is not generated and therefore used in scripts function OnDeinit () can not.

void OnDeinit(const int reason);

Event Deinit generated for experts and indicators in the following cases:

· before reinitialization due to change in character or the period chart, which is attached mql5-program;
· before reinitialization due to change input parameters;
· before unloading mql5-program.
OnTick

Event NewTick generated experts only when you receive a new tick for the symbol, which is attached to the chart expert.Function OnTick () is useless to define a custom indicator or script, because the Tick event for them is not generated.

Tick event is generated only for experts, but this does not mean that experts are required to have a function OnTick (), since experts are generated not only the events Tick, but the event Timer, BookEvent and ChartEvent.Must be declared as type void, no parameters:

void OnTick();
OnTimer

Function OnTimer () is called when the event occurs Timer, which is generated by the system timer only for experts - to use it in scripts or indicators can not.Frequency of occurrence of this event is set when you sign up to receive notifications about this event function EventSetTimer().

Unsubscribing from receiving parcels timer event for a particular expert is a function EventKillTimer(). Function must be defined with the type void, no parameters:

void OnTimer();

It is recommended to call a function EventSetTimer () once in the function OnInit (), and the function EventKillTimer () call once in OnDeinit ().

OnTrade

Function is called upon the occurrence of Trade, which occurs when you change the list put up orders and open positions, the history of ordersandtransaction history. In any trading activities (a display of a pending order, the opening / closing position, setting stops, triggered pending orders, etc.) accordingly changed the history of orders and transactions and / or a list of positions and current orders.

void OnTrade();

Users must independently verify the code to implement state trading account upon receipt of this event (if required under the terms of the trading strategy). If the function call OrderSend () completed successfully and returned a value of true - this means that the trading server put in place a order of execution and granted him the ticket number. As soon as the server will process this order will be generated event Trade. And if the user remember the value of ticket, then the processing events OnTrade () it can be on the ticket to find out what happened to the order.

OnBookEvent

Function OnBookEvent () is an event handler BookEvent. Event BookEvent generatedexperts onlya change of a glass prices (Depth of Market). Must be of type void and one parameter of type string:

void OnBookEvent (const string& symbol);

To receive eventsBookEvent for any characterEnough pre-subscribe to receive these events for this character using the MarketBookAdd(). In order to unsubscribe from receiving eventsBookEvent on a particular character, you must call the function MarketBookRelease().

Unlike other events, the event is broadcast BookEvent.This means that one expert is enough to subscribe to receive events BookEvent using the MarketBookAdd, all the other experts who have handler OnBookEvent (), will receive this event.It is therefore necessary to analyze the name of the symbol, which is passed to the handler as a parameter const string& symbol.

OnChartEvent

OnChartEvent () handler is a group of events ChartEvent:

· CHARTEVENT_KEYDOWN - event keystrokes when the chart window is in focus;
· CHARTEVENT_OBJECT_CLICK - event mouse click on the graphical objects belonging to the timetable;
· CHARTEVENT_OBJECT_DRAG - event move a graphic object using the mouse;
· CHARTEVENT_OBJECT_ENDEDIT - event finished editing the text in the box graphic LabelEdit;
· CHARTEVENT_CUSTOM + n - ID of the user event, where n is in the range from 0 to 65535.
· CHARTEVENT_CUSTOM_LAST - the last acceptable ID is a custom event (CHARTEVENT_CUSTOM +65535).

The function can only be called in experts and should be of type void, and 4 parameters:

void OnChartEvent(const int id, // Event ID
const long& lparam, // Parameter of type long event
const double& dparam, // Parameter of type double event
const string& sparam // Parameter of type string events
);
OnCalculate

Function OnCalculate () is invoked only in custom indicators necessary to calculate the indicator values for the event Calculate. This usually happens when you receive a new tick for character, for which the indicator is calculated.This indicator is not required to be attached to any price chart of the character.

Function OnCalculate () must have a return type int. There are two possible definitions. Within a single indicator can not use both versions function.

The first form is intended for those indicators that can be designed for a single data buffer. An example of such an indicator - Custom Moving Average.

int OnCalculate (const int rates_total, // Size of the array price []
const int prev_calculated, // Handle bars on a previous call
const int begin, // Where the significant data start from
const double& price[] // Array to calculate
);

As an array of price [] can be transferred to one of price taymsery a calculated buffer any indicator.To determine the direction of indexing in the array price [], must call the function ArrayGetAsSeries(). In order not to depend on the default, you must surely call the function ArraySetAsSeries() for those arrays, which is expected to work.

The appropriate timeseries or indicator as an array price [] made by the user when starting the indicator on the tab "Parameters".To do this you must specify the desired item in the drop-down box "Apply to".

For values of custom indicator from other mql5-program uses iCustom(), returning Handle indicator for subsequent operations.It can also specify the desired array of price [], or Handle another indicator.This parameter should be transmitted last in the list of input variables, custom indicator.
Example:

void OnStart()
{
//---
string terminal_path=StatusInfoString(STATUS_TERMINAL_PATH);
int handle_customMA=iCustom(Symbol(),PERIOD_CURRENT, "Custom Moving Average",13,0, MODE_EMA,PRICE_TYPICAL);
if(handle_customMA>0)
Print("handle_customMA =",handle_customMA);
else
Print("Cannot open or not EX5 file '"+terminal_path+"\\MQL5\\Indicators\\"+"Custom Moving Average.ex5'");
}

In this example, the last parameter passed value PRICE_TYPICAL (from enumeration ENUM_APPLIED_PRICE), which indicates that the custom indicator will be built on the typical prices obtained as (High + Low + Close) / 3.If this parameter is not specified that the indicator is based on the values PRICE_CLOSE, ie closing prices of each bar.

Another example demonstrating the transfer Handley indicator of the last parameter to specify an array price [], is given in the description of the function iCustom().

The second form is intended for all other indicators, in which the calculation used by more than one timeseries.

int OnCalculate (const int rates_total, // Size of input taymsery
const int prev_calculated, // Handle bars on a previous call
const datetime& time[], // Time
const double& open[], // Open
const double& high[], // High
const double& low[], // Low
const double& close[], // Close
const long& tick_volume[], // Tick Volume
const long& volume[], // Real Volume
const int& spread[] // Spread
);

Options open [], high [], low [] and close [] array contains the prices of opening, maximum, minimum prices and closing prices of the current timeframe.Setting time [] contains an array with the values of the time of opening, the parameter spread [] - array containing the story spreads (if the spread is provided for the trading instrument).Options volume [] and tick_volume [] contain the history of trade and the volume of teak.

To determine the direction of indexing of arrays time [], open [], high [], low [], close [], tick_volume [], volume [] and spread [], must call the function ArrayGetAsSeries(). In order not to depend on the default, you must surely call the function ArraySetAsSeries() for those arrays, which is expected to work.

The first parameter rates_total contains a number of bars, available indicators for the calculation, and does not exceed the maximum number of bars available on the chart.This value is set in the client terminal in the menu "Options" tab "Charts" - "Max bars in chart".

It should be noted the connection between the return value OnCalculate () and the second input parameter prev_calculated. Parameter prev_calculated function call contains a value that back function OnCalculate() on previous call. This allows for economical algorithms for calculating the custom indicator in order to avoid repeated calculations for those bars, which have not changed from the previous run of this function.

This is usually enough to return the value rates_total, which contains a number of bars in the current function call.If since the last call to OnCalculate () price data were changed (disappoint deeper story or stories were filled with blanks), the value of the input parameter prev_calculated will be set to zero by the terminal.

Note: OnCalculate if the function returns zero, then it DataWindow client terminal value of the indicator is not shown.

To better understand the indicator would be useful to run the code which is attached below.

Indicator Example:

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Line
#property indicator_label1 "Line"
#property indicator_type1 DRAW_LINE
#property indicator_color1 DarkBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- indicator buffers
double LineBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,LineBuffer,INDICATOR_DATA);
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime& time[],
const double& open[],
const double& high[],
const double& low[],
const double& close[],
const long& tick_volume[],
const long& volume[],
const int& spread[])
{
//--- Get the number of bars available for the current character and the period of the graph
int bars=Bars(Symbol(),0);
Print("Bars =",bars,", rates_total =",rates_total,", prev_calculated =",prev_calculated);
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+

See also

Running Programs, Client Terminal Events, Working with Events


Variables

MQL5 Reference / Language Basics / Variables

Variables

Declaring variables

Variables must be declared before using.To identify the variables used unique names.Descriptions of variables used for their determination and ad types.Description is not an operator.

Simple types are:

· char, short, int, long, uchar, ushort, uint, ulong - integers;
· color - integer representing the RGB-color;
· datetime - the date and time, an unsigned integer containing the number of seconds since 0 hour January 1, 1970;
· bool - boolean values true and false;
· double - the number of double-precision floating point;
· float - the number of single-precision floating point;
· string - character string.

Examples:

string szInfoBox;
int nOrders;
double dSymbolPrice;
bool bLog;
datetime tBegin_Data = D'2004.01.01 00:00';
color cModify_Color = C'0x44,0xB9,0xE6';

Complex or compound types:

Structures - a composite data types, constructed with other types.

struct MyTime
{
int hour; // 0-23
int minute; // 0-59
int second; // 0-59
};
...
MyTime strTime; // Variable previously declared structure MyTime MyTime

Until the structure has not been declared, can not declare variables of type structure.

Arrays

Array - this is the indexed set of similar data:

int a[50]; // One-dimensional array of 50 integers.
double m[7][50]; // Two-dimensional array of seven arrays,
// Each of which consists of 50 numbers.
MyTime t[100]; // Array containing elements such as MyTime

The index of the array can only be an integer.Allowed no more than four-dimensional arrays.The numbering of the elements of the array starts at 0.The last element of one-dimensional array has the number 1 less than the size of the array, that is an appeal to the last element of an array of 50 integers would look like a [49].The same is true for multidimensional arrays - one dimension is indexed from 0 to size-1 measurement.The last element of a two-dimensional array of examples will look like m [6] [49].

Static arrays can not be represented in the form taymsery, that is, it does not apply to function ArraySetAsSeries(), Which sets access array elements from the end of the array to its beginning. If you want to provide access to an array as in timeseries, use object of dynamic array.

When you access an array beyond performing subsystem generates a critical error and the program will be stopped.

Access specifiers

Access specifiers specify how the compiler can access the variables, members of structures or classes.

Specifier const declares a variable constant, and does not allow to change this variable at runtime.Non single-initialize a variable when you declare. Specifier const does not apply to members of structures and classes.

To access the members of structures and classes use the following qualifiers:

· public- Allow anything unrestricted access to the variable or method
· protected- Allow access by the methods of this class, as well as by the methods ofpublicly inherited classes. Sometimes access is impossible;
· private - allows access to variables and methods of a class only of the methods of this class.
· virtual- Applies only to the methods of the class (but not to the methods of structures) and tells the compiler that this method should be placed in the table of virtual functions in the class.

Storage Classes

There are three classes of memory: static, input and extern. These modifiers are a class of memory clearly indicate to the compiler that the relevant variables are distributed in a predetermined area of memory called the global pool.Besides, these modifiers indicate special processing variables.


Local Variables

MQL5 Reference / Language Basics / Variables / Local Variables

Local Variables

A variable declared inside a function, Is local. The scope of a local variable outside function is limited within which it is declared. Local variable could be initialized with any expression. Initialize the local variable is every time you call the appropriate functions. Local variables are placed in the temporary memory area corresponding function.

Example:

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

Scope (or visibility zone) variable - is part of the program, in which a variable can refer. Variables declared inside a block (at the domestic level), there are areas of block. The scope of a variable declaration block begins and ends with the ultimate right brace.

Local variables declared in the beginning of the function have the scope of the block as well as function parameters, Are local variables. Any block can contain variable declarations. If blocks are nested and identifier the external unit has the same name as the identifier in the indoor unit, outdoor unit identifier "invisible" (hidden) until the completion of the indoor unit.

Example:

void OnStart()
{
//---
int i=5; // Local variable function
{
int i=10; // Variable function
Print("In block i=",i); // Result is i=10;
}
Print("Outside block i=",i); // Result is i=5;
}

This means that while running the indoor unit, he sees the value of its own local identifiers rather than the values of identifiers with identical names in the block.

Example:

void OnStart()
{
//---
int i=5; // Local variable function
for(int i=0;i<3;i++)
Print(Inside for i = ",i);
Print("Outside the block i =",i);
}
/* Result of execution
Inside for i = 0
Inside for i = 1
Inside for i = 2
Outside block i = 5
*/

Local variables declared as static have the scope of the block, despite the fact that they exist at the outset of the program.


Formal Parameters

MQL5 Reference / Language Basics / Variables / Formal Parameters

Formal Parameters

Passed into the function parameters are local. The scope is the block function.Formal parameters must differ from the names of external variables and local variables defined inside a function.In the block function formal parameters can be assigned to some values.If the formal parameter is declared with modifier const, then its value can not be changed inside the function.

Example:

void func(const int x[], double y, bool z)
{
if(y>0.0 && !z)
Print(x[0]);
...
}

Formal parameters can be initialized constants. In this case, the initializing value is the default. Parameters following the initialized parameter must be initialized, too.

Example:

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

When you call such a function is initialized parameters can be omitted, they will be substituted instead of the default values.

Example:

func(123, 0.5);

Parameters of simple types passed by value, that is, change the corresponding local variable this type inside the called function does not affect the calling function.Arrays of any type and data type of structures are always passed by reference.If you do not want change or the contents of the array structure, the parameters of these types must be declared with the const keyword.

There is an opportunity to pass by reference and parameters of simple types.In this case, modification of these parameters will affect the relevant variables in the called function assigned by reference.To specify that a parameter is passed by reference, after the type of data necessary to put the modifier &.

Example:

void func(int& x, double& y, double& z[])
{
double calculated_tp;
...
for(int i=0; i<OrdersTotal(); i++)
{
if(i==ArraySize(z)) break;
if(OrderSelect(i)==false) break;
z[i]=OrderOpenPrice();
}
x=i;
y=calculated_tp;
}

Parameters passed by reference, can not initialize the default values.

The function can not allocate more than 64 parameters.

See also

Input Variables


Static Variables

MQL5 Reference / Language Basics / Variables / Static Variables

Static Variables

Memory class static defines a static variable. Modifier static indicated before the data type.

Example:

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

A static variable can be initialized corresponding to its type constant or constant expression, in contrast to a simple local variable, which can be initialized by any expression.

Static variables exist from the moment of the program and initialized only once before invoking specialized functions OnInit(). If the initial values are not specified, then the variables of static storage class are taking zero initial values.

Local variables declared with the static keyword retain their values throughout lifetime function. With each subsequent call to such local variables contain the values that they had in the previous call.

Any variables in the block, except formal parameters functions can be defined as static.

Example:

int Counter()
{
static int count;
count++;
if(count%100==0) Print("Function Counter has been called",count,"times");
return count;
}
void OnStart()
{
//---
int c=345;
for(int i=0;i<1000;i++)
{
int c=Counter();
}
Print("c =",c);
}


Global Variables

MQL5 Reference / Language Basics / Variables / Global Variables

Global Variables

Global variables are created by placing their ads off the description of a function. Global variables are defined on the same level as the function, ie, not locally in any block.

Example:

int GlobalFlag=10; // Global variable
int OnStart()
{
...
}

The scope of global variables - the whole program, global variables are accessible from all functions defined in the program.Initialized to zero unless you explicitly specify a different starting value.Global variable can be initialized only the appropriate type of constant or constant expression.

Initialization of global variables is performed only once immediately after loading the program in memory of the client terminal.

Note: do not confuse the variables declared at the global level, with global variables of the client terminal, which are accessed using the functions GlobalVariable...().


Input Variables

MQL5 Reference / Language Basics / Variables / Input Variables

Input Variables

Memory class input defines the external variable. Modifierinputindicated before the data type.Change the value of a modifier input inside mql5-programs can not, such variables are read-only.Change the values of input-variables can only user of the program properties window.

Example:

//--- input parameters
input int MA_Period=13;
input int MA_Shift=0;
input ENUM_MA_METHOD MA_Method=MODE_SMMA;

Input variables determine the input parameters of the program, they are available from the Properties window of the program.

There is an opportunity to ask another way to display the names of input parameters on the tab "Inputs".It uses the line comment, which must be placed after the description of the input parameter in the same row.Thus, the input parameters can be compared more understandable for the user names.

Example:

//--- input parameters
input int InpMAPeriod=13; // Smoothing period
input int InpMAShift=0; // Line horizontal shift
input ENUM_MA_METHOD InpMAMethod=MODE_SMMA; // Smoothing method

Note:Arrays and variables of complex types can not act as input-variables.

Passing parameters when calling custom indicators from mql5-programs

Custom Indicators are caused by the function iCustom(). However after the name of the custom indicator should go options in strict accordance with the declaration of input-variables of the custom indicator.If a list is less than the declared input-variables in the called user's display, the missing parameters are filled with the values specified in the declaration of variables.

If the user display using the function OnCalculate the first type (ie, the indicator is on the same array of data), then as the last parameter when calling a custom indicator must speak one of the values ENUM_APPLIED_PRICE or Hendl another indicator. Moreover, all parameters relevant input-variables must be clearly indicated.

Transfers as input-parameter

As the input-variables (input parameters for mql5-programs) can be used not only provided the language MQL5 built enumeration, but enumeration of user -.For example, we can create a listing dayOfWeek, describing the days of the week and use the input-variable to specify a particular day of the week, not as numbers, but in a more familiar form for the user.

Example:

#property script_show_inputs
//--- day of week
enum dayOfWeek
{
S=0, // Sunday
M=1, // Monday
T=2, // Tuesday
W=3, // Wednesday
Th=4, // Thursday
Fr=5, // Friday,
St=6, // Saturday
};
//--- input parameters
input dayOfWeek swapday=W;

In order to startup script the user can select the desired value of the Properties window, we use the preprocessor # property script_show_inputs.Run script for execution, and can choose from one of the values of transfers dayOfWeek.Run script EnumInInput and go to the tab "Options".By default, the value swapday (daily charge triple swap) environment is (W = 3), but we can specify any other value, and use this value to change the program.

Number of possible values of the transfer is limited.Therefore, to select the input values using the drop-down list.As the values displayed in the list, use mnemonic names of the members listing.If the mnemonic name associated comment, as shown in this example, the mnemonic name, instead of using the contents of comments.

Each value of the transfer dayOfWeek has a value from 0 to 6, but the list of options will show the comments listed for each value of.This provides additional flexibility for writing programs with clear descriptions of the input parameters.

See also

iCustom, Enumerations, Properties of Programs


Extern Variables

MQL5 Reference / Language Basics / Variables / Extern Variables

Extern Variables

Keywords extern used to declare variables identifiers as identifiers static storage class with global lifetime. These variables exist from the start of the program and their memory is allocated and initialized immediately after the start of the program.

You can create programs that consist of multiple source files, it uses the preprocessor directive #include. Variables declared as an extern with the same type and identifier can exist in different source files of one project.

When compiling the whole project all the extern-variables with the same type and an identifier associated with a portion of memory pool of global variables.Extern-variables are useful for separate compilation of source files.Extern-variables can be initialized, but only once - not allowed to have multiple initialized extern-variables of the same type and with the same identifier.


Initialization of Variables

MQL5 Reference / Language Basics / Variables / Initialization of Variables

Initialization of Variables

Any variable in the determination can be initialized.If not made explicit initialization variable, the value stored in this variable can be anything.Implicit initialization is not.

Global and static variables can be initialized only by a constant of the type or constant expression. Local variables can be initialized by any expression, not just a constant.

Initialization of global and static variables is performed only once. Initialization of local variables is made every time you call the corresponding functions.

Examples:

int n = 1;
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 } };
//--- from tetris
int right[4]={WIDTH_IN_PIXELS+VERT_BORDER,WIDTH_IN_PIXELS+VERT_BORDER,
WIDTH_IN_PIXELS+VERT_BORDER,WIDTH_IN_PIXELS+VERT_BORDER};

List of values array must be enclosed in curly brackets.Missed initializing the sequence are considered equal to 0.In the initialization sequence must be at least one value: this value is initialized to the first element of the corresponding structure or array, the missing elements are considered equal to zero.

If the size of initialized array is not specified, it is determined by the compiler, based on the size of the initialization sequence. Multi-dimensional arrays cannot be initialized by an one-dimensional sequence (a sequence without additional curly brackets), except one case, when only one initializing element is specified (zero, as a rule).

Arrays (including those announced at the local level) can be initialized only constants.

Examples:

struct str3
{
int low_part;
int high_part;
};
struct str10
{
str3 s3;
double d1[10];
int i3;
};
void OnStart()
{
str10 s10_1={{1,0},{1.0,2.1,3.2,4.4,5.3,6.1,7.8,8.7,9.2,10.0},100};
str10 s10_2={{1,0},{0},100};
str10 s10_3={{1,0},{1.0}};
//---
Print("1. s10_1.d1[5] =",s10_1.d1[5]);
Print("2. s10_2.d1[5] =",s10_2.d1[5]);
Print("3. s10_3.d1[5] =",s10_3.d1[5]);
Print("4. s10_3.d1[0] =",s10_3.d1[0]);
}


Visibility Scope and Lifetime of Variables

MQL5 Reference / Language Basics / Variables / Visibility Scope and Lifetime of Variables

Visibility Scope and Lifetime of Variables

There are two basic types of scope: local scope and global scope.

A variable declared outside all functions that fit into the global scope.Access to such variables can be done from anywhere in your program.These variables are located in the global pool of memory, so the time of their life coincides with the lifetime of the program.

A variable declared inside a block (of code, enclosed in curly brackets), belongs to the local scope.Such a variable is not visible (and therefore not available) outside the block in which it is declared.The most common case of local ads - a variable declared within a function.A variable declared locally, is located on the stack, and the lifetime of a variable coincides with the lifetime of the function.

Since the scope of a local variable is the block in which it is declared, it is possible to declare variables with a name that matches the names of variables declared in the other blocks, as well as pledges for more than the upper levels, up to a global.

Example:

void CalculateLWMA(int rates_total,int prev_calculated,int begin,const double &price[])
{
int i,limit;
static int weightsum=0;
double sum=0;
//---
if(prev_calculated==0)
{
limit=MA_Period+begin;
//--- set empty value for first limit bars
for(i=0; i<limit; i++) LineBuffer[i]=0.0;
//--- calculate first visible value
double firstValue=0;
for(int i=begin; i<limit; i++)
{
int k=i-begin+1;
weightsum+=k;
firstValue+=k*price[i];
}
firstValue/=(double)weightsum;
LineBuffer[limit-1]=firstValue;
}
else
{
limit=prev_calculated-1;
}

for(i=limit;i<rates_total;i++)
{
sum=0;
for(int j=0; j<MA_Period; j++) sum+=(MA_Period-j)*price[i-j];
LineBuffer[i]=sum/weightsum;
}
//---
}

Pay attention to the variable i, declared in line

for(int i=begin; i<limit; i++)
{
int k=i-begin+1;
weightsum+=k;
firstValue+=k*price[i];
}

Its scope - only cycle for, outside of this cycle operates another variable with the same name, announced at the beginning of the function.In addition, in the loop body declares a variable k, whose scope is the loop body.

Local variables can be declared with the access specifier static. In this case, the compiler has a variable in the global pool of memory.Therefore, the lifetime of a static variable coincides with the lifetime of the program.In this scope the variable is limited to outside the block in which it is declared.


Preprocessor

MQL5 Reference / Language Basics / Preprocessor

Preprocessor

Preprocessor - is a special subsystem compiler MQL5, which is engaged in preliminary training program source code immediately before its compilation.

The preprocessor can improve the readability of source code.Structuring the code can be achieved through the inclusion of individual files with source code mql5-programs.Improve readability of code and helps to assign mnemonic names of individual constants.

The preprocessor can also define specific parameters mql5-programs:

· Declare constants
· Set the properties of the pogram
· Include files in text of programs
· Import functions

If the first character in the string program uses the symbol # then this line is a preprocessor directive. Preprocessor directive ends with transfer to a new line.


Declaration of Constants

MQL5 Reference / Language Basics / Preprocessor / Declaration of Constants

Declaration of Constants (#define)

The #define dirctive can be used to assign mnemonic constant names.

#define identifier token_string

The #define dircetive instead of substitutes token_string all subsequent occurrences of the identifier found in the source text.identifier is replaced only if it is a separate token.identifier is not replaced if it is part of the commentary, part of the string, or part of another over a long identifier.

Id constants follows the same rules as for variable names. The value can be any type:

#define ABC 100
#define PI 3.14
#define COMPANY_NAME "MetaQuotes Software Corp."
...
void ShowCopyright()
{
Print("Copyright 2001-2009, ",COMPANY_NAME);
Print("http://www.metaquotes.net");
}

token_string may consist of several tokens, such as keywords, constants, constant and non-const expression.token_string ends with the end of the line and can not be deferred to the next line.

Example:

#define TWO 2
#define THREE 3
#define INCOMPLETE TWO+THREE
#define COMPLETE (TWO+THREE)
void OnStart()
{
Print("2+3*2 =",INCOMPLETE*2);
Print("(2+3)*2 =",COMPLETE*2);
}
/* Result
2+3*2 = 8
(2+3)*2 = 10
*/


Properties of Programs

MQL5 Reference / Language Basics / Preprocessor / Properties of Programs

Properties of Programs (#property)

Each mql5-program you can specify additional specific parameters #property that help the client terminal properly maintain the program without the need to explicitly start.In particular this applies to the external configuration of indicators.Properties described in the included files are completely ignored.Properties must be specified in the main mq5-file.

#property identifier value

The compiler will write the configuration is done in the module declared value.

Constant | Type | Description
link | string | link to the site of the manufacturer
copyright | string | name of the manufacturer
version | string | version of the program, not more than 31 characters
description | string | short text description mql5-program.May be present multiple description, each of which describes a single line of text.The total length of all description can not exceed 511 characters to reflect the transfer lines.
stacksize | int | size of the stack for recursive calls
library |  | library; not assigned to any start function does not remove functions that are not called from other functions
indicator_applied_price | int | specifies the default value for the field "Apply to". You can specify one of the values of the transfer ENUM_APPLIED_PRICE. If the property is not specified, the default value PRICE_CLOSE
indicator_chart_window |  | output indicator in the chart window
indicator_separate_window |  | display indicator in a separate window
indicator_buffers | int | number of buffers for the calculation of the indicator
indicator_plots | int | number graphic series the indicator
indicator_minimum | double | lower limit of the scale of a separate indicator window
indicator_maximum | double | upper limit of the scale of a separate indicator window
indicator_labelN | string | specifies the label for the N-th graphic series displayed in the DataWindow. For graphic series, requiring multiple indicator buffers (DRAW_CANDLES, DRAW_FILLING and others), the tag names are defined by the separator ';'.
indicator_colorN | color | color for the output line N, where N - number graphic series; numbering from 1
indicator_widthN | int | thick line in graphic series, where N - number of graphic series, numbering from 1
indicator_styleN | int | line style in graphic series is specified by the values of ENUM_LINE_STYLE. N - number of graphic series, numbering from 1
indicator_typeN | int | kind of graphical construction is specified by the values of ENUM_DRAW_TYPE. N - number of graphic series, numbering from 1
indicator_levelN | double | horizontal level of N in a separate window indicator
indicator_levelcolor | color | color of horizontal levels of the indicator
indicator_levelwidth | int | thickness of horizontal levels of the indicator
indicator_levelstyle | int | style horizontal levels of the indicator
script_show_confirm |  | display a confirmation window before running the script
script_show_inputs |  | display a window with the properties before running the script and disable this confirmation window

Sample job descriptions and version numbers

#property version "3.70" // Current version of the expert
#property description "ZigZag universal with Pesavento Patterns"
#property description "At the moment in the ZigZag indicator built several different algorithms"
#property description "It is possible to embed a large number of other indicators showing the highs and"
#property description "The minimum and automatically build from these minima and maxima of the various graphical tools"

Examples of specifying a separate label for each indicator buffer ( "C open; C high; C low; C close")

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots 1
#property indicator_type1 DRAW_CANDLES
#property indicator_width1 3
#property indicator_label1 "With open; With high; With low; With close"


Including Files

MQL5 Reference / Language Basics / Preprocessor / Including Files

Including Files (#include)

Command line #include can occur anywhere in the program, but typically include all placed in the beginning of the source file. Call format:

#include <file_name>
#include "file_name"

Examples:

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

The preprocessor replaces the line #include <file_name> content of the file WinUser32.mqh. Angle brackets indicate that the file WinUser32.mqh will be taken from the standard directory (usually it is terminal_installation_directory\MQL5\Include). The current directory is not visible.

If the file name in quotation marks, the search is made in the current directory (which contains the main source file). Standart directory is not visible.


Functions Import

MQL5 Reference / Language Basics / Preprocessor / Functions Import

Function Import (#import)

Import of functions carried out from compiled modules MQL5 (files *. ex5) and from the operating system modules (files *. dll). The module name specified in the directive #import. In order for the compiler can correctly execute the call imported function and organize proper transmission parameters should complete description functions. Function descriptions immediately follow the directive #import "module name". New command #import (can be without parameters) completes the unit descriptions of imported functions.

#import "file_name"
func1 define;
func2 define;
...
funcN define;
#import

Imported functions can have any name.You can also import from different modules function with the same name.Imported functions can have names that coincide with the names of built-in functions. Operation of context permission defines which of the functions should be called.

Since the imported functions outside the module compiled, the compiler can not verify the validity of passed parameters.Therefore, to avoid run-time, must accurately describe the composition and order of parameters passed to the imported functions.Parameters passed to the imported functions (both from the EX5, and from the DLL-module) can have default values.

Examples:

#import "user32.dll"
int MessageBoxW(uint hWnd, string lpText, string lpCaption, uint uType);
#import "stdlib.ex5"
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

To import functions during execution mql5-program uses early binding. This means that the library is loaded at boot using its ex5-program.

Do not use fully qualified name of the loadable module type Drive:\Directory\FileName.Ext. Libraries MQL5 loaded from the folder terminal_dir\MQL5\Libraries.


Object-oriented programming

MQL5 Reference / Language Basics / Object-oriented programming

Object-oriented programming

Object-oriented programming (OOP) is a programming, primarily focused on data, with data and its behavior are inextricably linked. Together, the data and its behavior constitute a class, and objects are class instances.

The components of object-oriented approach are:

· Encapsulation and types extensiblity
· Inheritance
· Polymorphism
· Overloading
· Virtual functions

OOP considers the computation as a behavior modeling.The modeled thing is the object represented by the computational abstractions. Suppose we want to write a well known game "Tetris", for this we must learn how to simulate the appearance of random shapes composed of four squares joined together by ribs.Also required to regulate the rate of incidence figures, to define operations of rotation and shift shapes. Moving shapes on the screen is limited by the glass boundaries , we also have to simulate this requirement to. In addition, the rows filled with cubes in the glass should destroyed and earned points should counted.

Thus, this easy-to-understand game requires the creation of several models - figures model, glass model, figures movement model in the glass and so on. All these models are abstractions, represented in the computer calculations. To describe these models the concept of Abstract Data Type, ATD (or complex data type) is used. Strictly speaking, the model of the "figures" motion in the "glass" is not the type of data, as well as a collection of operations on the "figure" data type using the restrictions of the "glass" data type.

Objects are class variables. Object-oriented programming allows you to easily create and use ADT. Object-oriented programming uses the inheritance mechanism. The advance of the inheritance because it allows to obtain the derivative types from the user-defined data types already defined.

For example, to create the Tetris shapes is convenient to create a base class Shape first, the other seven classes representing all of the possible figure types can be derived on its basis. The base class has defined figure behavior, and it's derivative classes contains an implementation of behavior-specific figures.

In OOP objects are responsible for their behavior. ADT developer should include a code to describe any behavior that would normally be expected from the corresponding objects .The fact that the object itself is responsible for its behavior, greatly simplifies the task of programming for the user of this object.

If we want to draw a figure on the screen, we need to know where will be the center and how to draw. If a separate figure is well aware of what to draw, the programmer should send a "draw" message when using a such figure.

The MQL5 Language is a C++ like, and it also has a encapsulation mechanism for the implementation of the ADT. Encapsulation combines, from the one side, the internal implementation details of a particular type and, from the other side, externally accessible functions that can operate the objects of this type. Implementation details may be inaccessible for a program that uses such types.

The concept of the OOP has a set of related concepts, including the following:

· Simulation of actions from the real world
· Availability of user-defined data types
· Hiding the implementation details
· Possibility of the code reuse through inheritance
· Interpretation of function calls during execution

Some of these concepts are rather vague, Some - are abstract, others have the general character.


Encapsulation and types extensibility

MQL5 Reference / Language Basics / Object-oriented programming / Encapsulation and types extensibility

Encapsulation and types extensibility

OOP is a balanced approach to writing software. Data and its behavior are packed together. This encapsulation creates a user-defined data types, extending the language data types and interacting with them. Types extensibility - it's an opportunity to add to the language the user-defined data types, which are also easy to use, as a basic types.

An abstract data type, for example, the string, is a description of the ideal, well known behavior type.

The string user knows that the string operations such as concatenation or print, have a certain behavior. Concatenation and the print are called methods.

Concrete ADT implementation may have some constraints, for example, strings can be limited by the length. These constraints affect the string behavior opened to all. At the same time, internal or private implementation details do not affect directly the way the user sees the object. For example, the string is often implemented as an array, while the internal base address of this array and its name are not essential for the user.

Encapsulation - the ability to hide the implementation details in the open interfaces to user-defined type. In MQL5, as in C++, a class and structure definitions are used for the encapsulation (class and struct) in combination with access keywords private, protected and public.

The public keyword shows that access to the members who stands behind him, is open without restrictions. Without this keyword, the class members are locked by default. Private members are accessible only by member functions only of its class.

The protected class functions are available to class functions not only in its class, but its in heirs classes. Public class functions are available for any function within the scope of the class declaration. The protection makes possible to hide part of the class implementation, thus preventing for unexpected changes in the structure of data. An access restriction or a data hiding is a feature of object-oriented programming.

Usually, class functions are protecting and declare them with the protected modifier, the reading and writing of the values are performed by using special so-called set-and get-methods that are defined by the publics access modifiers.

Example:

class CPerson{}
{
protected:
string m_name; // name
public:
void SetName(string n){m_name=n;}// sets name
string GetName(){return (m_name);} // returns name
};

This approach offers several advantages. The first, by function name we can understand what it does - sets or gets the value of a class member. Secondly, perhaps in the future, we will need to change the type of variable m_name CPerson in the CPerson class or in any it's derivative classes.

In this case, we would be sufficient to change the implementation of functions SetName () and GetName (), the objects themselves of class CPerson can be used in the program without any code changes because the user will not even know what data type of m_name has changed.

Example:

struct Name
{
string first_name; // name
string last_name; // last name
};
class CPerson{}
{
protected:
Name m_name; // name
public:
void SetName(string n);
string GetName(){return (m_name.first_name+" "+m_name.last_name);}
private:
string GetFirstName(string full_name);
string GetLastName(string full_name);
};

void CPerson::SetName(string n)
{
m_name.first_name=GetFirstName(n);
m_name.last_name=GetLastName(n);
}

string CPerson::GetFirstName(string full_name)
{
int pos=StringFind{full_name," ");
if(pos>0) SetStringCharacter(full_name,pos,0);
return(full_name);
}

string CPerson::GetLastName(string full_name)
{
string ret_string;
int pos=StringFind{full_name," ");
if(pos>0) ret_string=StringSubstring(full_name,pos+1);
else ret_string=full_name;
return(ret_string);
}


Inheritance

MQL5 Reference / Language Basics / Object-oriented programming / Inheritance

Inheritance

The feature of OOP is to encourage the code reuse through inheritance. A new class is made from the existing, called the base class. The derived class uses the members of the base class, but can also modify and supplement them.

Many types are variations of the existing types. It is often tedious to develop new code for each of them. In addition, the new code - new errors.The derived class inherits the description of the base class, making it unnecessary re-development and testing of code. The inheritance relationships are hierarchical.

Hierarchy is a method that allows to copy the elements in all their diversity and complexity. It introduces the objects classification. For example, the periodic table of elements has gases. They possess to properties inherent in all of the periodic elements.

Inert gases - the next important subclass. The hierarchy is that the inert gas, such as argon - a gas, and gas, in turn, is part of the system. Such hierarchy allows to interpret behaviour of inert gases easily. We know that their atoms contain protons and electrons, that is true and for the other elements.

We know that they are in a gaseous state at room temperature, like all the gases. We know that any gas from an inert gases subclass does not enter usual chemical reaction with no one of the elements, and its a property of all inert gases.

Consider an example of the inheritance of geometric figures. To describe the whole variety of simple shapes (circle, triangle, rectangle, square etc.) the best way to create a base class (ATD), which is the ancestor of all of the derived classes.

Lets create a base class CShape, which has a just the most general things describing the figure. These terms describe the features of any figure - the type of shape and of the main anchor point coordinates.

Example:

//--- The base class Shape
class CShape{}
{
protected:
int m_type; // Shape type
int m_xpos; // X - coordinate of the base point
int m_ypos; // Y - coordinate of the base point
public:
CShape(){m_type=0; m_xpos=0; m_ypos=0;} // constructor
void SetXPos(int x){m_xpos=x;} // set X
void SetYPos(int y){m_ypos=y;} // set Y
};

Next, create a new classes derived from base class, which will add the necessary fields, each specifying a specific class. For the Circle shape it is necessary to add a member that contains the radius. The Square shape is characterized by the side value. Therefore, derived classes, inherited from the base class CShape will be declared as follows:

//--- The derived class circle
class CCircle{} : public CShape // After a colon we define the base class
{ // from which inheritance is made
private:
int m_radius; // circle radius

public:
CCircle(){m_type=1;}// constructor, type 1
};

for the Square shape class declaration looks like:

//--- the derived class Square
class CSquare{} : public CShape // After a colon we define the base class
{ // from which inheritance is made
private:
int m_square_side; // square side

public:
CSquare(){m_type=2;} // constructor, type 2
};

It should be noted that while object is created the base class constructor calls first, an then constructor of the derived class. When an object is destroyed the first called the destructor of the derived class, and then a base class destructor.

Thus, by declaring a base class the most general terms in the derived classes, we can add an additional members, which specify a particular class.Inheritance allows you to create powerful code libraries that can be reused many times.

The syntax for creating a derived class from an already existing as follows:

class class_name :
(public | protected | private) opt base_class_name
{
class members declaration
};

The one aspect of the derived class is the visibility (transparency) of its members, successors (heirs). The public, protected and private keywords are used to indicate the extent to which members of the base class will be available for the derived. The public keyword in the header of the derived class, following the colon indicates that the protected and public members of the base class CShape should be inherited as protected and public members of the derived class CCircle.

The private class members of the base class are not available for derived class. The Public inheritance also means that the derived classes (CCircle and CSquare) are CShapes. That is, the Square (CSquare) is a shapee (CShape), but the Shape does not necessarily have to be Square.

The derived class is a modification of the base class, it inherits the protected and public members of the base class. The constructors and destructors of the base class cannot be inherited. In addition to members of the base class, a new members in a derivative class are added.

The derived class may include the implementation of member functions, different from the base class. It has nothing common with an overload, when the meaning of the same function name may be different for different signatures.

In protected inheritance, public and protected members of base class become protected members of derived class.In private inheritance inheritance of the public and protected members of base class become private members of the derived class.

At protected and private inheritance the relation that "the object of a derivative class is object of a base class" is not true. The protected and private inheritance are rare and each of them needs to be used carefully.

MQL5 has no multiple inheritance.


Polymorphism

MQL5 Reference / Language Basics / Object-oriented programming / Polymorphism

Polymorphism

Polymorphism - is an opportunity for different classes of objects, related through inheritance, to respond in various ways when referring to the same function element. It helps to create a universal mechanism describing the behavior of not only the base class, but also the descendant classes.

Lets continue to develop a base class CShape, and define a member function GetArea (), designed to calculate the area of the figure. In all the descendant classes, produced by inheritance from the base class, we override this function in accordance with the rules of calculating the size of a particular shape.

For the Square (class CSquare) area is calculated through the side, for the circle (class CCircle) surface is expressed through the radius etc. We can create an array to store objects of type CShape, which can be stored as an object base class and all its descendants. Further we can call the same function for each element of the array.

Example:

//--- Base class
class CShape{};
{
protected:
int m_type; // Shape type
int m_xpos; // X - coordinate of the base point
int m_ypos; // Y - coordinate of the base point
public:
void CShape(){m_type=0;}; // constructor, type=0
int GetType(){return(m_type);};// returns type of the shape
virtual
double GetArea(){return (0); }// returns area of the shape
};

Now, all of the derived classes have a member function getArea (), which returns a zero value. The implementation of this function in each child will vary.

//--- The derived class Circle
class CCircle{} : public CShape // After a colon we define the base class
{ // from which inheritance is made
private:
int m_radius; // circle radius

public:
void CCircle(){m_type=1;}; // constructor, type=1
void SetRadius(double r){m_radius=r;};
virtual double GetArea(){return (3.14*m_radius*m_radius);}// circle area
};

For the class Square the declaration is the same:

//--- The derived class Square
class CSquare{} : public CShape // After a colon we define the base class
{ // from which inheritance is made
private:
int m_square_side; // square side

public:
void CSquare(){m_type=2;}; // constructor, type=1
void SetSide(double s){m_square_side=s;};
virtual double GetArea(){return (m_square_side*m_square_side);}// square area
};

For calculating the area of the square and the circle, we need the the appropriate values and the members m_radius m_square_side, so we have added the features SetRadius and SetSide () to the declaration of the class. Now we can declare an array of type Shape and fill it with objects of derived classes:

CShape[10] shapes; // array of CShape objects
//... here we fill array by derived objects
for (int i=0; i<10;i++)
{
//--- type and area of the shape
Print("Object type "+shapes[i].GetType()+" has an area "+ shapes[i].GetArea());
};

But in addition to functions redefining in terms of inheritance, polymorphism also includes the realization of one and the same functions with a different set of parameters within a class. This means that the class may have several functions with the same name but with different type and/or set of parameters. In this case, polymorphism is implemented through the function overload.


Overload

MQL5 Reference / Language Basics / Object-oriented programming / Overload

Overload

Within the one class it is possible to define two or more methods that share the same name, but have a different number of parameters. When this occurs, the methods are called overloaded and such process called as a method overloading.

The method overloading is one of the ways of the polymorthism realization. In classes the methods overloading is produced by the same rules as the function overloading.

If the called function has not an exact match, the compiler searches for a suitable function on three levels sequentially:

1. search within the class methods;
2. search within the base class methods, consistently from the nearest ancestor to the very first.
3. search among the other functions.

If there is no exact correspondence at one level has been found, but has been found a suitable functions at different levels, the least level function is used. Within the one level there cannot be more than one suitable function.

MQL5 has no operator overloading.


The virtual functions

MQL5 Reference / Language Basics / Object-oriented programming / The virtual functions

The virtual functions

The virtual keyword is the function qualifier, which provides a mechanism to select dynamically at runtime the appropriate function member among the functions of basic and derived classes, the structures cannot have a virtual functions. It can be used to change the declarations for a member functions only.

The virtual function as an ordinary function, must have a executed body. Its call semantics are the same exactly as for the other functions.

A virtual function may be overridden in a derived class. The choice of the function definition are cause dynamically for the virtual functions (at runtime). A typical case - when the base class contains a virtual function and derived classes have their own versions of this function.

The pointer to the base class can indicate either a base class object or the object of a derived class. The choice of the member function will be performed at run time and will depend on the type of object, not the type of pointer. In the absence of a member of the derived type the virtual function of the base class is used by default.

Consider the use of virtual functions on the example program MT5_Tetris.mq5. In the included file MT5_TetisShape.defined mqh CTetrisShape base class with virtual function Draw (draw). The included file MT5_TetisShape.mqh has a base class CTetrisShape with the virtual function Draw.

//+------------------------------------------------------------------+
class CTetrisShape
{
protected:
int m_type;
int m_xpos;
int m_ypos;
int m_xsize;
int m_ysize;
int m_prev_turn;
int m_turn;
int m_right_border;
public:
void CTetrisShape();
void SetRightBorder(int border) { m_right_border=border; }
void SetYPos(int ypos) { m_ypos=ypos; }
void SetXPos(int xpos) { m_xpos=xpos; }
int GetYPos() { return(m_ypos); }
int GetXPos() { return(m_xpos); }
int GetYSize() { return(m_ysize); }
int GetXSize() { return(m_xsize); }
int GetType() { return(m_type); }
void Left() { m_xpos-=SHAPE_SIZE; }
void Right() { m_xpos+=SHAPE_SIZE; }
void Rotate() { m_prev_turn=m_turn; if(++m_turn>3) m_turn=0; }
virtual void Draw() { return; }
virtual bool CheckDown(int& pad_array[]);
virtual bool CheckLeft(int& side_row[]);
virtual bool CheckRight(int& side_row[]);
};

Then for each derived class, this function is implemented in accordance with the characteristics of a descendant class. For example, the first shape CTetrisShape1 has its own implementation of the function Draw ():

class CTetrisShape1 : public CTetrisShape
{
public:
//--- shape draw
virtual void Draw()
{
int i;
string name;
//---
if(m_turn==0 || m_turn==2)
{
//--- horizontal
for(i=0; i<4; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos+i*SHAPE_SIZE);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos);
}
}
else
{
//--- vertical
for(i=0; i<4; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos+i*SHAPE_SIZE);
}
}
}
}

The Square shape is described by class CTetrisShape6 and has its own implementation of the method Draw ():

class CTetrisShape6 : public CTetrisShape
{
public:
//--- Shape draw
virtual void Draw()
{
int i;
string name;
//---
for(i=0; i<2; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos+i*SHAPE_SIZE);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos);
}
for(i=2; i<4; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos+(i-2)*SHAPE_SIZE);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos+SHAPE_SIZE);
}
}
};

Depending on the object of a class is created, it calls the virtual function of a derived class.

void CTetrisField::NewShape()
{
//--- creating the one of the 7 possible shapes randomly
int nshape=rand()%7;
switch(nshape)
{
case 0: m_shape=new CTetrisShape1; break;
case 1: m_shape=new CTetrisShape2; break;
case 2: m_shape=new CTetrisShape3; break;
case 3: m_shape=new CTetrisShape4; break;
case 4: m_shape=new CTetrisShape5; break;
case 5: m_shape=new CTetrisShape6; break;
case 6: m_shape=new CTetrisShape7; break;
}
//--- draw
m_shape.Draw();
//---
}


Standard constants, enumerations and structures Standard constants, enumerations and structures

MQL5 Reference / Standard constants, enumerations and structures

Standard constants, enumerations and structures

For ease of writing programs, as well as for readability source programs in the language MQL5 provides predefined standard Enumeration structure.

Standard constants are similar macroses and have the type int.

The constants are grouped according to their purpose:

· Chart constants used when working with price charts: discovery, navigation, setting parameters;
· Objects constants intended for processing graphic objects that can create and display the graphs;
· Indicators constants used to work with standard and custom indicators;
· Trade constants allow to specify a variety of information in the course of trade;
· Named constants- Constants language MQL5;
· Data structures describe the used data storage format;
· Codes of errors and warnings- Describe compiler messages and the trading server answers on trade requests;
· In/out constants designed to work with the file functions and display messages on the computer screen function MessageBox().


Charts constants

MQL5 Reference / Standard constants, enumerations and structures / Charts constants

Constants graphs

Constants describing the various properties of graphs, divided into the following groups:

· Types of events- Events that occur during the work chart;
· Chart timeframes- Standard built-in periods;
· Properties of chart- Identifiers that are used as parameterschart functions;
· Positioning constants - Setting function ChartNavigate();
· Displaying charts - setting the appearance chart.


Types of events

MQL5 Reference / Standard constants, enumerations and structures / Charts constants / Types of events

Types of events

There are 5 types of events that can be processed using the predefined functions OnChartEvent(). For custom events provided 65536 identifiers in the range of CHARTEVENT_CUSTOM to CHARTEVENT_CUSTOM_LAST inclusive.To generate a custom event must use the EventChartCustom().

ENUM_CHART_EVENT

ID | Description
CHARTEVENT_KEYDOWN | Keystrokes
CHARTEVENT_OBJECT_CLICK | By clicking on the graphic object
CHARTEVENT_OBJECT_DRAG | Drag and drop a graphic object
CHARTEVENT_OBJECT_ENDEDIT | End text editing in the graphical object Edit
CHARTEVENT_CUSTOM | Initial number of events from a range of custom events
CHARTEVENT_CUSTOM_LAST | The final number of events from a range of custom events

Example:

#define KEY_NUMPAD_5 12
#define KEY_LEFT 37
#define KEY_UP 38
#define KEY_RIGHT 39
#define KEY_DOWN 40
#define KEY_NUMLOCK_DOWN 98
#define KEY_NUMLOCK_LEFT 100
#define KEY_NUMLOCK_5 101
#define KEY_NUMLOCK_RIGHT 102
#define KEY_NUMLOCK_UP 104
//---
void OnChartEvent(const int id,
const long& lparam,
const double& dparam,
const string& sparam)
{
long ldparam=dparam;
if(id==CHARTEVENT_KEYDOWN)
{
switch(lparam)
{
case KEY_NUMLOCK_LEFT:
case KEY_LEFT: ExtField.Left(); break;
case KEY_NUMLOCK_UP:
case KEY_UP: ExtField.Rotate(); break;
case KEY_NUMLOCK_RIGHT:
case KEY_RIGHT: ExtField.Right(); break;
case KEY_NUMLOCK_DOWN:
case KEY_DOWN: ExtField.Down(); break;
case KEY_NUMPAD_5:
case KEY_NUMLOCK_5: ExtField.Drop(); break;
}
ChartRedraw();
}
}


Chart timeframes

MQL5 Reference / Standard constants, enumerations and structures / Charts constants / Chart timeframes

Chart timeframes

All predefined periods of graphs have unique identifiers. Id PERIOD_CURRENT means the current period chart, which started mql5-program.

ENUM_TIMEFRAMES

ID | Description
PERIOD_CURRENT | Current timeframe
PERIOD_M1 | 1 minute
PERIOD_M2 | 2 minutes
PERIOD_M3 | 3 minutes
PERIOD_M4 | 4 minutes
PERIOD_M5 | 5 minutes
PERIOD_M6 | 6 minutes
PERIOD_M10 | 10 minutes
PERIOD_M12 | 12 minutes
PERIOD_M15 | 15 minutes
PERIOD_M20 | 20 minutes
PERIOD_M30 | 30 minutes
PERIOD_H1 | 1 our
PERIOD_H2 | 2 ours
PERIOD_H3 | 3 ours
PERIOD_H4 | 4 ours
PERIOD_H6 | 6 ours
PERIOD_H8 | 8 ours
PERIOD_H12 | 12 ours
PERIOD_D1 | 1 ours
PERIOD_W1 | 1 week
PERIOD_MN1 | 1 month

Example:

string chart_name="test_Object_Chart";
Print("Let's try to create a Chart object with the name ",chart_name);
//--- If such an object does not - create it
if(ObjectFind(0,chart_name)<0)ObjectCreate(0,chart_name,OBJ_CHART,0,0,0,0,0);
//--- Define a symbol
ObjectSetString(0,chart_name,OBJPROP_SYMBOL,"EURUSD");
//--- Setup X coordinate of anchor point
ObjectSetInteger(0,chart_name,OBJPROP_XDISTANCE,100);
//--- Setup Y coordinate of anchor point
ObjectSetInteger(0,chart_name,OBJPROP_YDISTANCE,100);
//--- Set the width of chart
ObjectSetInteger(0,chart_name,OBJPROP_XSIZE,400);
//--- Set the height
ObjectSetInteger(0,chart_name,OBJPROP_YSIZE,300);
//--- Set the timeframe
ObjectSetInteger(0,chart_name,OBJPROP_PERIOD,PERIOD_D1);
//--- Set scale (from 0 to 5)
ObjectSetInteger(0,chart_name,OBJPROP_SCALE,4);
//--- Make unavailable for allocation of a mouse
ObjectSetInteger(0,chart_name,OBJPROP_SELECTABLE,false);


Properties of chart

MQL5 Reference / Standard constants, enumerations and structures / Charts constants / Properties of chart

Properties of chart

Identifiers family transfers ENUM_CHART_PROPERTY used as parameters functions for working with graphics. Abbreviation: r/o in the column "Type property" means that this property is read-only and can not be changed. When accessing certain properties must specify an additional parameter-modifier (modifier), which serves to indicate the number subwindows chart. 0 means the main window.

For functions ChartSetInteger()andChartGetInteger()

ENUM_CHART_PROPERTY_INTEGER
ID | Description | Property Type
CHART_MODE | Chart type (candles, bars or line) | enum ENUM_CHART_MODE
CHART_FOREGROUND | Price chart in the background | bool
CHART_SHIFT | Mode indentation price chart from the right edge | bool
CHART_AUTOSCROLL | Mode to automatically switch to the right edge of the graph | bool
CHART_SCALE | Scale | int from 0 to 5
CHART_SCALEFIX | Mode of fixed scale | bool
CHART_SCALEFIX_11 | Mode scale 1:1 | bool
CHART_SCALE_PT_PER_BAR | Mode indicate the scale of points on the bar | bool
CHART_SHOW_OHLC | Shown in the upper left corner of the values OHLC | bool
CHART_SHOW_BID_LINE | Bid values show a horizontal line on the graph | bool
CHART_SHOW_ASK_LINE | Display values Ask horizontal line on the graph | bool
CHART_SHOW_LAST_LINE | Show values Last horizontal line on the graph | bool
CHART_SHOW_PERIOD_SEP | Display vertical separators between adjacent periods | bool
CHART_SHOW_GRID | Display grid on the chart | bool
CHART_SHOW_VOLUMES | Display volume on the chart | enum ENUM_CHART_VOLUME_MODE
CHART_SHOW_OBJECT_DESCR | Pop-up descriptions of graphical objects | bool
CHART_VISIBLE_BARS | The number of bars on the chart, available for display | int r/o
CHART_WINDOWS_TOTAL | The total number of windows chart, including indicators subwindows | int r/o
CHART_WINDOW_IS_VISIBLE | Visibility of subwindows | bool r / o modifier - the number of subwindows
CHART_WINDOW_HANDLE | Chart window handle (HWND) | int r/o
CHART_FIRST_VISIBLE_BAR | Number of the first visible bar on the graph | int r/o
CHART_WIDTH_IN_BARS | Width of the chart in the bars | int r/o
CHART_WIDTH_IN_PIXELS | Width of graph in pixels | int r/o
CHART_HEIGHT_IN_PIXELS | Height of chart in pixels | int r / o modifier - the number of subwindows
CHART_COLOR_BACKGROUND | Chart background color | color
CHART_COLOR_FOREGROUND | Color of axes, scales and rows OHLC | color
CHART_COLOR_GRID | Grid color | color
CHART_COLOR_VOLUME | Color of levels and levels of opening positions | color
CHART_COLOR_CHART_UP | Color for bar up, shadows and outline of the body bullish candles | color
CHART_COLOR_CHART_DOWN | Color for bar down, the shadows and outline of the body bear candle | color
CHART_COLOR_CHART_LINE | Line chart color and color of Japanese candlesticks Dodge | color
CHART_COLOR_CANDLE_BULL | Bullish candle color body | color
CHART_COLOR_CANDLE_BEAR | bearish candle color body | color
CHART_COLOR_BID | Bid prices level color | color
CHART_COLOR_ASK | Ask prices level color | color
CHART_COLOR_LAST | Last transaction prices level color | color
CHART_COLOR_STOP_LEVEL | Color of stop orders levels (Stop Loss and Take Profit) | color

For functions ChartSetDouble()andChartGetDouble()

ENUM_CHART_PROPERTY_DOUBLE
ID | Description | Property Type
CHART_SHIFT_SIZE | The size of the indent for the zero bar from the right edge percentage | double (from 10 to 50 per cent)
CHART_FIXED_MAX | Fixed chart maximum | double
CHART_FIXED_MIN | Fixed chart minimum | double
CHART_POINTS_PER_BAR | The scale in points a bar | double
CHART_PRICE_MIN | Chart maximum | double r / o modifier - the number of subwindows
CHART_PRICE_MAX | Chart minimum | double r / o modifier - the number of subwindows

For functions ChartSetString()andChartGetString()

ENUM_CHART_PROPERTY_STRING
ID | Description | Property Type
CHART_COMMENT | The text of the commentary on the chart | string

Example:

int chartMode=ChartGetInteger(0,CHART_MODE);
switch(chartMode)
{
case(CHART_BARS): Print("CHART_BARS"); break;
case(CHART_CANDLES): Print("CHART_CANDLES");break;
default:Print("CHART_LINE");
}
bool shifted=ChartGetInteger(0,CHART_SHIFT);
if(shifted) Print("CHART_SHIFT = true");
else Print("CHART_SHIFT = false");
bool autoscroll=ChartGetInteger(0,CHART_AUTOSCROLL);
if(autoscroll) Print("CHART_AUTOSCROLL = true");
else Print("CHART_AUTOSCROLL = false");
int chartHandle=ChartGetInteger(0,CHART_WINDOW_HANDLE);
Print("CHART_WINDOW_HANDLE =",chartHandle);
int windows=ChartGetInteger(0,CHART_WINDOWS_TOTAL);
Print("CHART_WINDOWS_TOTAL =",windows);
if(windows>1)
{
for(int i=0;i<windows;i++)
{
int height=ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,i);
double priceMin=ChartGetDouble(0,CHART_PRICE_MIN,i);
double priceMax=ChartGetDouble(0,CHART_PRICE_MAX,i);
Print(i+": CHART_HEIGHT_IN_PIXELS =",height,"pixels");
Print(i+": CHART_PRICE_MIN =",priceMin);
Print(i+": CHART_PRICE_MAX =",priceMax);
}
}


Positioning constants

MQL5 Reference / Standard constants, enumerations and structures / Charts constants / Positioning constants

Positioning constants

Three ID from the list ENUM_CHART_POSITION are the possible values for position for the function ChartNavigate().

ENUM_CHART_POSITION

ID | Description
CHART_BEGIN | Beginning of a chart (there are the oldest prices)
CHART_CURRENT_POS | Current position
CHART_END | The end of the chart (there are the latest prices)

Example:

long handle=ChartOpen("EURUSD",PERIOD_H12);
if(handle!=0)
{
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
ChartSetInteger(handle,CHART_SHIFT,true);
ChartSetInteger(handle,CHART_MODE,CHART_LINE);
ResetLastError();
bool res=ChartNavigate(handle,CHART_END,150);
if(!res) Print("Navigate failed. Error= ",GetLastError());
ChartRedraw();
}


Displaying charts

MQL5 Reference / Standard constants, enumerations and structures / Charts constants / Displaying charts

Displaying charts

Price charts can be displayed in three ways:

· as bars;
· as candlesticks;
· as line.

The specific way of displaying the price chart is given by the function ChartSetInteger(chart_handle,CHART_MODE, Chart_mode), where where chart_mode - one of the values of the enumeration ENUM_CHART_MODE.

ENUM_CHART_MODE
ID | Description
CHART_BARS | Displays bars
CHART_CANDLES | Display as a candlestick chart
CHART_LINE | Displays in the form of a line drawn at prices Close

To specify the display mode volumes on the price chart using the function ChartSetInteger(chart_handle, CHART_SHOW_VOLUMES, volime_mode), where volime_mode - one of the values of the transfer ENUM_CHART_VOLUME_MODE.

ENUM_CHART_VOLUME_MODE
ID | Description
CHART_VOLUME_HIDE | Volumes are not shown
CHART_VOLUME_TICK | Tick volume
CHART_VOLUME_REAL | Trading volumes

Example:

//--- Get the handle of the current chart
long handle=ChartID();
if(handle>0) // If it turned out, customize
{
//--- Disable autoshift
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
//--- Set the indentation of the right side of the graph
ChartSetInteger(handle,CHART_SHIFT,true);
//--- Display as candlesticks
ChartSetInteger(handle,CHART_MODE,CHART_CANDLES);
//--- Scrolling at 100 bars from the beginning of history
ChartNavigate(handle,CHART_CURRENT_POS,100);
//--- Set the display mode tick volume
ChartSetInteger(handle,CHART_SHOW_VOLUMES,CHART_VOLUME_TICK);
}

See also

ChartOpen,ChartID


Objects constants

MQL5 Reference / Standard constants, enumerations and structures / Objects constants

Constants objects

There are 39 graphical objects that can create and display the price chart. All the constants for working with objects are divided into 9 groups:

· Object types- Identifiers of graphic objects;
· Object properties- Setting and getting the properties of graphical objects;
· Methods of binding sites- The constants of object positioning on the chart;
· Chart angle- An indication of the angle of the schedule, which is positioned on the object;
· Visibility of objects- Setting timeframes in which the object is visible;
· Levels of Elliott Wave- Wave gradation markings;
· Gann objects- The trend constants for the Gann fan and Gann grid;
· Web colors- Constants of the predefined Web-colors;
· Wingdings- Codes of characters in the font Wingdings.


Object types

MQL5 Reference / Standard constants, enumerations and structures / Objects constants / Object types

Object types

When you create a graphic object functionObjectCreate()must specify the type of object being created, which can be one of the values of the transfer ENUM_OBJECT. Further refinementspropertiescreated object, possibly with the help of functions to work withgraphics.

ENUM_OBJECT

ID |  | Description
OBJ_VLINE |  | Vertical line
OBJ_HLINE |  | Horizontal line
OBJ_TREND |  | Trend line
OBJ_TRENDBYANGLE |  | Trend line for the corner
OBJ_CHANNEL |  | Equidistant Channel
OBJ_STDDEVCHANNEL |  | Channel standard deviation
OBJ_REGRESSION |  | The channel on the linear regression
OBJ_PITCHFORK | andrewspitchfork | Andrews' Pitchfork
OBJ_GANNLINE |  | Gann Line
OBJ_GANNFAN |  | Gann Fan
OBJ_GANNGRID |  | Gann Grid
OBJ_FIBO |  | Fibonacci Levels
OBJ_FIBOTIMES |  | Fibonacci Time Zones
OBJ_FIBOFAN |  | Fibonacci Fan
OBJ_FIBOARC |  | Fibonacci Arcs
OBJ_FIBOCHANNEL |  | Fibonacci Channel
OBJ_EXPANSION |  | Fibonacci Expansion
OBJ_ELLIOTWAVE5 |  | 5 volnovka Elliott
OBJ_ELLIOTWAVE3 |  | 3 volnovka Elliott
OBJ_RECTANGLE | rectangle | Rectangle
OBJ_TRIANGLE | triangle | Triangle
OBJ_ELLIPSE | ellipse | Ellipse
OBJ_CYCLES |  | Circular Line
OBJ_ARROW_THUMB_UP |  | Sign "Good" (thumb up)
OBJ_ARROW_THUMB_DOWN |  | Sign "Bad" (thumb down)
OBJ_ARROW_UP |  | Sign up arrow
OBJ_ARROW_DOWN |  | Sign "Down Arrow"
OBJ_ARROW_STOP |  | The sign "Stop"
OBJ_ARROW_CHECK |  | Mark "Bird" (daw)
OBJ_ARROW_LEFT_PRICE |  | Left price tag
OBJ_ARROW_RIGHT_PRICE |  | Right price tag
OBJ_ARROW |  | Object "Arrow"
OBJ_TEXT |  | Object Text
OBJ_LABEL |  | Object Text Label "
OBJ_BUTTON |  | Object button
OBJ_CHART |  | Object Graph "
OBJ_BITMAP |  | Object Drawing "
OBJ_BITMAP_LABEL |  | Object Graphic Label "
OBJ_EDIT |  | Object "input field"


Object properties

MQL5 Reference / Standard constants, enumerations and structures / Objects constants / Object properties

Object properties

Every graphic object on the price chart has a certain set of properties. Setting and getting values of properties of objects are relevantfunctions to work with graphic objects. Eachobject typehas its own set of properties that are listed all the possible values of family remittances ENUM_OBJECT_PROPERTY.Some properties require clarification, such as the level number for the object Fibonacci extension.In such cases it is necessary in the functions.ObjectSet...()andObjectGet...()specify a value formodifier.

For functionsObjectSetInteger()andObjectGetInteger()

ENUM_OBJECT_PROPERTY_INTEGER
ID | Description | Property Type
OBJPROP_COLOR | Color | color
OBJPROP_STYLE | Style | ENUM_LINE_STYLE
OBJPROP_WIDTH | Line thickness | int
OBJPROP_BACK | Object in the background | bool
OBJPROP_SELECTED | Selected object | bool
OBJPROP_TYPE | Type | ENUM_OBJECT
OBJPROP_TIME | Coordinate time | datetime modifier = number anchor point
OBJPROP_SELECTABLE | Availability object | bool
OBJPROP_CREATETIME | Established facility | datetime r/o
OBJPROP_LEVELS | Number of levels | int
OBJPROP_LEVELCOLOR | Color line-level | color modifier = level number
OBJPROP_LEVELSTYLE | Style line-level | ENUM_LINE_STYLEmodifier = level number
OBJPROP_LEVELWIDTH | The thickness of the line-level | int modifier = level number
OBJPROP_FONTSIZE | Fontsize | int
OBJPROP_RAY_LEFT | Ray goes to the left | bool
OBJPROP_RAY_RIGHT | Ray goes to the right | bool
OBJPROP_ELLIPSE | Ellipse | bool
OBJPROP_ARROWCODE | Code arrows to object "Arrow" | char
OBJPROP_TIMEFRAMES | Visibility of the object at the time frames | a set of flagsflags
OBJPROP_ANCHOR | Situation anchor point graphic | ENUM_ARROW_ANCHOR(for OBJ_ARROW), ENUM_ANCHORPOINT(for OBJ_LABEL and OBJ_TEXT)
OBJPROP_XDISTANCE | The distance in pixels on the X axis on the angle of anchor | int
OBJPROP_YDISTANCE | The distance in pixels on the Y axis on the angle of anchor | int
OBJPROP_DIRECTION | Trend Object Gunn | ENUM_GANN_DIRECTION
OBJPROP_DEGREE | Level of the Elliott Wave Counting Marking | ENUM_ELLIOT_WAVE_DEGREE
OBJPROP_DRAWLINES | Displaying lines for marking the Elliott Wave | bool
OBJPROP_STATE | Status button (pressed / depressed) | bool
OBJPROP_XSIZE | The size of the object "graph" on the axis X (the width in pixels) | int
OBJPROP_YSIZE | The size of the object "graph" on the axis Y (height in pixels) | int
OBJPROP_PERIOD | The period for the object "graph" | ENUM_TIMEFRAMES
OBJPROP_DATE_SCALE | Symptom display timeline for the object "graph" | bool
OBJPROP_PRICE_SCALE | Symptom displaying the price scale for the object "graph" | bool
OBJPROP_CHART_SCALE | The scale for the object "graph" | int value in the range 0-5
OBJPROP_BGCOLOR | The background color for the object "Input field" | color
OBJPROP_CORNER | The angle of the schedule to link graphic | ENUM_BASECORNER

For functionsObjectSetDouble()andObjectGetDouble()

ENUM_OBJECT_PROPERTY_DOUBLE
Id | Description | Property Type
OBJPROP_PRICE | Coordinate prices | double modifier = number anchor point
OBJPROP_LEVELVALUE | Level value | double modifier = level number
OBJPROP_SCALE | Scale (a property of objects and object Gunn "Fibonacci Arcs") | double
OBJPROP_ANGLE | Angle | double
OBJPROP_DEVIATION | Deviation for the channel standard deviation | double

For functionsObjectSetString()andObjectGetString()

ENUM_OBJECT_PROPERTY_STRING
Id | Description | Property Type
OBJPROP_NAME | Object Name | string
OBJPROP_TEXT | Description of the object (the text contained in the object) | string
OBJPROP_LEVELTEXT | Description level | string modifier = level number
OBJPROP_FONT | Font | string
OBJPROP_BMPFILE | The name of BMP-file for the object "Graphic Label" | string modifier: 0-state ON, 1 OFF state
OBJPROP_SYMBOL | The symbol for the object "graph" | string

Example:

#define UP "\x0431"
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
string label_name="my_OBJ_LABEL_object";
if(ObjectFind(0,label_name)<0)
{
Print("Object",label_name,"not found. Error code =",GetLastError());
//--- Create the object Label
ObjectCreate(0,label_name,OBJ_LABEL,0,0,0);
//--- Set the coordinates X
ObjectSetInteger(0,label_name,OBJPROP_XDISTANCE,200);
//--- Set the Y coordinate
ObjectSetInteger(0,label_name,OBJPROP_YDISTANCE,300);
//--- Set the color of the text
ObjectSetInteger(0,label_name,OBJPROP_COLOR,White);
//--- Set the text for the Label object
ObjectSetString(0,label_name,OBJPROP_TEXT,UP);
//--- Set the font inscription
ObjectSetString(0,label_name,OBJPROP_FONT,"Wingdings");
//--- Set the font size
ObjectSetInteger(0,label_name,OBJPROP_FONTSIZE,10);
//--- Rotate 45 degrees clockwise
ObjectSetDouble(0,label_name,OBJPROP_ANGLE,-45);
//--- Forbid the selection of the object arm
ObjectSetInteger(0,label_name,OBJPROP_SELECTABLE,false);
//--- Otrisuem on the chart
ChartRedraw(0);
}
}


Methods of binding sites

MQL5 Reference / Standard constants, enumerations and structures / Objects constants / Methods of binding sites

Methods of binding sites

Graphic objects Text and Label (OBJ_TEXT and OBJ_LABEL) may be one of the 9 different ways of linking their coordinates. Indicate the option you want, you can use the function ObjectSetInteger(chart_handle, object_name, OBJPROP_ANCHOR, anchor_point_mode), where anchor_point_mode - one of the values of the transfer ENUM_ANCHORPOINT.

ENUM_ANCHOR_POINT

ID | Description
ANCHOR_LEFT_UPPER | Anchor point on the upper left corner
ANCHOR_LEFT | Anchor point on the left of center
ANCHOR_LEFT_LOWER | Anchor point on the lower left corner
ANCHOR_LOWER | Anchor point below the center
ANCHOR_RIGHT_LOWER | Anchor point on the lower right corner
ANCHOR_RIGHT | Anchor point on the right in the center
ANCHOR_RIGHT_UPPER | Anchor point on the upper right corner
ANCHOR_UPPER | Anchor point above the center
ANCHOR_CENTER | Anchor point strictly in the center of the object

Example:

string text_name="my_OBJ_TEXT_object";
if(ObjectFind(0,text_name)<0)
{
Print("Object",text_name,"not found. Error code =",GetLastError());
//--- Get the maximal price of the chart
double chart_max_price=ChartGetDouble(0,CHART_PRICE_MAX,0);
//--- Create the object Label
ObjectCreate(0,text_name,OBJ_TEXT,0,TimeCurrent(),chart_max_price);
//--- Set the color of the text
ObjectSetInteger(0,text_name,OBJPROP_COLOR,White);
//--- Set the background color
ObjectSetInteger(0,text_name,OBJPROP_BGCOLOR,Green);
//--- Set the text for the Label object
ObjectSetString(0,text_name,OBJPROP_TEXT,TimeToString(TimeCurrent()));
//--- Set the font ot Text
ObjectSetString(0,text_name,OBJPROP_FONT,"Trebuchet MS");
//--- Set the font size
ObjectSetInteger(0,text_name,OBJPROP_FONTSIZE,10);
//--- Bind to the upper right corner
ObjectSetInteger(0,text_name,OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);
//--- Rotate 90 degrees counter-clockwise
ObjectSetDouble(0,text_name,OBJPROP_ANGLE,90);
//--- Forbid the selection of the object by mouse
ObjectSetInteger(0,text_name,OBJPROP_SELECTABLE,false);
//--- redraw object
ChartRedraw(0);
}

Graphic objects Arrow (OBJ_ARROW) are only 2 ways of linking their coordinates. Identifiers are listed in ENUM_ARROW_ANCHOR.

ENUM_ARROW_ANCHOR
ID | Description
ANCHOR_TOP | Anchor on the top side
ANCHOR_BOTTOM | Anchor on the bottom side

Example:

void OnStart()
{
//--- Auxiliary arrays
double Ups[],Downs[];
datetime Time[];
//--- Set the arrays as timeseries
ArraySetAsSeries(Ups,true);
ArraySetAsSeries(Downs,true);
ArraySetAsSeries(Time,true);
//--- Create handle of the Indicator Fractals
int FractalsHandle=iFractals(NULL,0);
Print("FractalsHandle =",FractalsHandle);
//--- Set Last error value to Zero
ResetLastError();
//--- Try to copy the values of the indicator
int copied=CopyBuffer(FractalsHandle,0,0,1000,Ups);
if(copied<=0)
{
Print("Unable to copy the upper fractals. Error =",GetLastError());
return;
}

ResetLastError();
//--- Try to copy the values of the indicator
copied=CopyBuffer(FractalsHandle,1,0,1000,Downs);
if(copied<=0)
{
Print("Unable to copy the bottom fractals. Error =",GetLastError());
return;
}

ResetLastError();
//--- Copy timeseries containing the opening bars of the last 1000 ones
copied=CopyTime(NULL,0,0,1000,Time);
if(copied<=0)
{
Print("Unable to copy the Opening Time of the last 1000 bars");
return;
}

int upcounter=0,downcounter=0; // Will they count the number of arrows
bool created;// Will receive the result of attempts to create an object
for(int i=2;i<copied;i++)// Run through the values of the indicator iFractals
{
if(Ups[i]!=EMPTY_VALUE)// Found the upper fractal
{
if(upcounter<10)// Create no more than 10 arrows "Up"
{
//--- Try to create an object "Up"
created=ObjectCreate(0,string(Time[i]),OBJ_ARROW_THUMB_UP,0,Time[i],Ups[i]);
if(created)// If set up - it would make him tuning
{
//--- Point anchor is below do not cover bar
ObjectSetInteger(0,string(Time[i]),OBJPROP_ANCHOR,ANCHOR_BOTTOM);
//--- Final touch - painted
ObjectSetInteger(0,string(Time[i]),OBJPROP_COLOR,Blue);
upcounter++;
}
}
}
if(Downs[i]!=EMPTY_VALUE)// Found a lower fractal
{
if(downcounter<10)// Create no more than 10 arrows "Down"
{
//--- Try to create an object "Down"
created=ObjectCreate(0,string(Time[i]),OBJ_ARROW_THUMB_DOWN,0,Time[i],Downs[i]);
if(created)// If set up - it would make him tuning
{
//--- Point anchor is above do not cover bar
ObjectSetInteger(0,string(Time[i]),OBJPROP_ANCHOR,ANCHOR_TOP);
//--- Final touch - painted
ObjectSetInteger(0,string(Time[i]),OBJPROP_COLOR,Red);
downcounter++;
}
}
}
}
}

After the script execution chart will look like in this figure.


Chart angle

MQL5 Reference / Standard constants, enumerations and structures / Objects constants / Chart angle

The angle of the schedule, to which is attached object

There are a number graphic objects for which you can set the angle of the chart, on which the coordinates are specified in pixels. These are the types of objects (in brackets the type of object identifiers):

· Label (OBJ_LABEL);
· Button (OBJ_BUTTON);
· Chart (OBJ_CHART);
· Bitmap Label (OBJ_BITMAP_LABEL);
· Edit (OBJ_EDIT).

In order to specify the angle of the chart, which will be counted from the X and Y coordinates in pixels, you have to use the ObjectSetInteger(chartID, name, OBJPROP_CORNER, chart_corner), where:

· chartID - chart ID;
· name - name of a graphic object;
· OBJPROP_CORNER - property ID to specify the angle of the binding;
· chart_corner- The desired angle of the chart, can be one of the values of enumeration ENUM_BASECORNER.

ENUM_BASE_CORNER

ID | Description
CORNER_LEFT_UPPER | Center coordinates in the upper left corner of the chart
CORNER_LEFT_LOWER | Center coordinates in the lower left corner of the chart
CORNER_RIGHT_LOWER | Center coordinates in the lower right corner of the chart
CORNER_RIGHT_UPPER | Center coordinates in the upper right corner of the chart

Example:

void CreateLabel(long chart_id,
string name,
int chart_corner,
string text_label,
int x_ord,
int y_ord)
{
//---
ObjectCreate(chart_id,name,OBJ_LABEL,0,0,0);
ResetLastError();
if(!ObjectSetInteger(chart_id,name,OBJPROP_CORNER,chart_corner))
Print("Unable to set the angle of the binding for the object",
name,", error code ",GetLastError());
ObjectSetInteger(chart_id,name,OBJPROP_XDISTANCE,x_ord);
ObjectSetInteger(chart_id,name,OBJPROP_YDISTANCE,y_ord);
ObjectSetString(chart_id,name,OBJPROP_TEXT,text_label);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int height=ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
int width=ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0);
string arrows[4]={"LEFT_UPPER","RIGHT_UPPER","RIGHT_LOWER","LEFT_LOWER"};
CreateLabel(0,arrows[0],CORNER_LEFT_UPPER,"0",50,50);
CreateLabel(0,arrows[1],CORNER_RIGHT_UPPER,"1",50,50);
CreateLabel(0,arrows[2],CORNER_RIGHT_LOWER,"2",50,50);
CreateLabel(0,arrows[3],CORNER_LEFT_LOWER,"3",50,50);
}


Visibility of objects

MQL5 Reference / Standard constants, enumerations and structures / Objects constants / Visibility of objects

Visibility of objects

The combination of flags determines the periods of visibility of the object graph, where the subject is. To set/get property value OBJPROP_TIMEFRAMES can use the functions ObjectSetInteger()/ObjectGetInteger().

ID | Value | Description
OBJ_PERIOD_M1 | 0x00000001 | The object is drawn on 1-minute chart
OBJ_PERIOD_M2 | 0x00000002 | The object is drawn on 2-minute chart
OBJ_PERIOD_M3 | 0x00000004 | The object is drawn on 3-minute chart
OBJ_PERIOD_M4 | 0x00000008 | The object is drawn on 4-minute chart
OBJ_PERIOD_M5 | 0x00000010 | The object is drawn on 5-minute chart
OBJ_PERIOD_M6 | 0x00000020 | The object is drawn on 6-minute chart
OBJ_PERIOD_M10 | 0x00000040 | The object is drawn on 10-minute chart
OBJ_PERIOD_M12 | 0x00000080 | The object is drawn on 12-minute chart
OBJ_PERIOD_M15 | 0x00000100 | The object is drawn on 15-minute chart
OBJ_PERIOD_M20 | 0x00000200 | The object is drawn on 20-minute chart
OBJ_PERIOD_M30 | 0x00000400 | The object is drawn on 30-minute chart
OBJ_PERIOD_H1 | 0x00000800 | The object is drawn on 1-hour chart
OBJ_PERIOD_H2 | 0x00001000 | The object is drawn on 2-hour chart
OBJ_PERIOD_H3 | 0x00002000 | The object is drawn on 3-hour chart
OBJ_PERIOD_H4 | 0x00004000 | The object is drawn on 4-hour chart
OBJ_PERIOD_H6 | 0x00008000 | The object is drawn on 6-hour chart
OBJ_PERIOD_H8 | 0x00010000 | The object is drawn on 8-hour chart
OBJ_PERIOD_H12 | 0x00020000 | The object is drawn on 12-hour chart
OBJ_PERIOD_D1 | 0x00040000 | The object is drawn on the daily chart
OBJ_PERIOD_W1 | 0x00080000 | The object is drawn on the weekly chart
OBJ_PERIOD_MN1 | 0x00100000 | The object is drawn on the monthly chart
OBJ_ALL_PERIODS | 0 | The object is drawn on all timeframes

Flags of visibility can be combined with the symbol "|", for example, the combination of flags OBJ_PERIOD_M10 | OBJ_PERIOD_H4 means that the object will be visible on the 10-minute and 4-hour time frames.

Example:

void OnStart()
{
//---
string highlevel="PreviousDayHigh";
string lowlevel="PreviousDayLow";
double prevHigh; // The previous day High
double prevLow; // The previous day Low
double highs[],lows[]; // Arrays for High and Low

//--- Reset the last error
ResetLastError();
//--- Get the last 2 High values on the daily timeframe
int highsgot=CopyHigh(Symbol(),PERIOD_D1,0,2,highs);
if(highsgot>0) // If copying was successful
{
Print("High prices for the last 2 days were obtained successfully");
prevHigh=highs[0]; // The previous day High
Print("prevHigh =",prevHigh);
if(ObjectFind(0,highlevel)<0) // Object with the name highlevel not found
{
ObjectCreate(0,highlevel,OBJ_HLINE,0,0,0); // Create object the Horizontal Line
}
//--- Set value for the price level for the line highlevel
ObjectSetDouble(0,highlevel,OBJPROP_PRICE,0,prevHigh);
//--- Set the visibility only PERIOD_M10 and PERIOD_H4
ObjectSetInteger(0,highlevel,OBJPROP_TIMEFRAMES,OBJ_PERIOD_M10|OBJ_PERIOD_H4);
}
else
{
Print("Could not get High prices over the past 2 days, Error =",GetLastError());
}

//--- Reset the last error
ResetLastError();
//--- Get the 2 days values Low on the daily timeframe
int lowsgot=CopyLow(Symbol(),PERIOD_D1,0,2,lows);
if(lowsgot>0) // If copying was successful
{
Print("Low prices for the last 2 days were obtained successfully");
prevLow=lows[0]; // The previous day Low
Print("prevLow =",prevLow);
if(ObjectFind(0,lowlevel)<0) // Object with the name lowlevel not found
{
ObjectCreate(0,lowlevel,OBJ_HLINE,0,0,0); // Create object the Horizontal Line
}
//--- Set value for the price level for the line lowlevel
ObjectSetDouble(0,lowlevel,OBJPROP_PRICE,0,prevLow);
//--- Set the visibility only PERIOD_M10 and PERIOD_H4
ObjectSetInteger(0,lowlevel,OBJPROP_TIMEFRAMES,OBJ_PERIOD_M10|OBJ_PERIOD_H4);
}
else Print("Could not get Low prices for the last 2 days, Error =",GetLastError());

ChartRedraw(0); // draw a graph force again
}


Levels of Elliott Wave

MQL5 Reference / Standard constants, enumerations and structures / Objects constants / Levels of Elliott Wave

Levels of Elliott Wave

Elliott Waves are represented by two types of graphic objects OBJ_ELLIOTWAVE5 and OBJ_ELLIOTWAVE3.To specify the size of the wave (method of labeling the waves), the property OBJPROP_DEGREE, which you can install one of the values of the transfer ENUM_ELLIOT_WAVE_DEGREE.

ENUM_ELLIOT_WAVE_DEGREE

ID | Description
ELLIOTT_GRAND_SUPERCYCLE | Grand Supercycle
ELLIOTT_SUPERCYCLE | Supercycle
ELLIOTT_CYCLE | Cycle
ELLIOTT_PRIMARY | Primary
ELLIOTT_INTERMEDIATE | Intermediate
ELLIOTT_MINOR | Minor
ELLIOTT_MINUTE | Minute
ELLIOTT_MINUETTE | Minuette
ELLIOTT_SUBMINUETTE | Subminuette

Example:

for(int i=0;i<ObjectsTotal(0);i++)
{
string currobj=ObjectName(0,i);
if((ObjectGetInteger(0,currobj,OBJPROP_TYPE)==OBJ_ELLIOTWAVE3) ||
((ObjectGetInteger(0,currobj,OBJPROP_TYPE)==OBJ_ELLIOTWAVE5)))
{
//--- Establish the level of markup in INTERMEDIATE
ObjectSetInteger(0,currobj,OBJPROP_DEGREE,ELLIOTT_INTERMEDIATE);
//--- Opted lines between the tops of the waves
ObjectSetInteger(0,currobj,OBJPROP_DRAWLINES,true);
//--- Set lines color
ObjectSetInteger(0,currobj,OBJPROP_COLOR,Blue);
//--- Set lines width
ObjectSetInteger(0,currobj,OBJPROP_WIDTH,5);
//--- Set description
ObjectSetString(0,currobj,OBJPROP_TEXT,"test script");
}
}


Gann objects

MQL5 Reference / Standard constants, enumerations and structures / Objects constants / Gann objects

Gann objects

For objects fan Gunn (OBJ_GANNFAN) and grid Gunn (OBJ_GANNGRID) you can specify one of the two transfer ENUM_GANN_DIRECTION, which sets the direction of the trend.

ENUM_GANN_DIRECTION

ID | Description
GANN_UP_TREND | Consistent uptrend line
GANN_DOWN_TREND | The line corresponds to the downward trend

To set the scale of the main line of 1x1 using the function ObjectSetDouble(chart_handle, gann_object_name, OBJPROP_SCALE, scale), where:

· chart_handle - window graphics, which is ogbekt;
· gann_object_name - the name of the object;
· OBJPROP_SCALE - property ID "Scale";
· scale - the scale required in units of Pips / Bar.

Example of creating a fan Gunn:

void OnStart()
{
//---
string my_gann="OBJ_GANNFAN object";
if(ObjectFind(0,my_gann)<0)// Object not found
{
//--- Inform the failure
Print("Object",my_gann,"not found. Error code =",GetLastError());
//--- Get the maximal price of chart
double chart_max_price=ChartGetDouble(0,CHART_PRICE_MAX,0);
//--- Get the minimal price of chart
double chart_min_price=ChartGetDouble(0,CHART_PRICE_MIN,0);
//--- How many bars on the chart are shown?
int bars_on_chart=ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- Create the array, where we write the opening of each bar
datetime Time[];
//--- Arrange access to the array as in timeseries
ArraySetAsSeries(Time,true);
//--- Now copy into this array the data seen on the graph bars
int times=CopyTime(NULL,0,0,bars_on_chart,Time);
if(times<=0)
{
Print("Could not copy the array since the opening!");
return;
}
//--- Preliminary preparations completed

//--- Index of the central bar on the chart
int center_bar=bars_on_chart/2;
//--- Chart Equator - between the maximum and minimum
double mean=(chart_max_price+chart_min_price)/2.0;
//--- Set the coordinates of the first anchor point to the center
ObjectCreate(0,my_gann,OBJ_GANNFAN,0,Time[center_bar],mean,
//--- Second anchor point on the right
Time[center_bar/2],(mean+chart_min_price)/2.0);
Print("Time[center_bar]/="+(string)Time[center_bar]+" Time[center_bar/2]="+(string)Time[center_bar/2]);
//Print("Time[center_bar]/="+Time[center_bar]+" Time[center_bar/2]="+Time[center_bar/2]);
//--- Set the scale in units of Pips / Bar
ObjectSetDouble(0,my_gann,OBJPROP_SCALE,10);
//--- Set the line trend
ObjectSetInteger(0,my_gann,OBJPROP_DIRECTION,GANN_UP_TREND);
//--- Set the line width
ObjectSetInteger(0,my_gann,OBJPROP_WIDTH,1);
//--- Define the line style
ObjectSetInteger(0,my_gann,OBJPROP_STYLE,STYLE_DASHDOT);
//--- Set the line color
ObjectSetInteger(0,my_gann,OBJPROP_COLOR,YellowGreen);
//--- Allow the user to select an object
ObjectSetInteger(0,my_gann,OBJPROP_SELECTABLE,true);
//--- Select it yourself
ObjectSetInteger(0,my_gann,OBJPROP_SELECTED,true);
//--- Draw it on the chart
ChartRedraw(0);
}
}


Web colors

MQL5 Reference / Standard constants, enumerations and structures / Objects constants / Web colors

Web colors

For type color identified the following color constants:

Black | DarkGreen | DarkSlateGray | Olive | Green | Teal | Navy | Purple
Maroon | Indigo | MidnightBlue | DarkBlue | DarkOliveGreen | SaddleBrown | ForestGreen | OliveDrab
SeaGreen | DarkGoldenrod | DarkSlateBlue | Sienna | MediumBlue | Brown | DarkTurquoise | DimGray
LightSeaGreen | DarkViolet | FireBrick | MediumVioletRed | MediumSeaGreen | Chocolate | Crimson | SteelBlue
Goldenrod | MediumSpringGreen | LawnGreen | CadetBlue | DarkOrchid | YellowGreen | LimeGreen | OrangeRed
DarkOrange | Orange | Gold | Yellow | Chartreuse | Lime | SpringGreen | Aqua
DeepSkyBlue | Blue | Magenta | Red | Gray | SlateGray | Peru | BlueViolet
LightSlateGray | DeepPink | MediumTurquoise | DodgerBlue | Turquoise | RoyalBlue | SlateBlue | DarkKhaki
IndianRed | MediumOrchid | GreenYellow | MediumAquamarine | DarkSeaGreen | Tomato | RosyBrown | Orchid
MediumPurple | PaleVioletRed | Coral | CornflowerBlue | DarkGray | SandyBrown | MediumSlateBlue | Tan
DarkSalmon | BurlyWood | HotPink | Salmon | Violet | LightCoral | SkyBlue | LightSalmon
Plum | Khaki | LightGreen | Aquamarine | Silver | LightSkyBlue | LightSteelBlue | LightBlue
PaleGreen | Thistle | PowderBlue | PaleGoldenrod | PaleTurquoise | LightGray | Wheat | NavajoWhite
Moccasin | LightPink | Gainsboro | PeachPuff | Pink | Bisque | LightGoldenrod | BlanchedAlmond
LemonChiffon | Beige | AntiqueWhite | PapayaWhip | Cornsilk | LightYellow | LightCyan | Linen
Lavender | MistyRose | OldLace | WhiteSmoke | Seashell | Ivory | Honeydew | AliceBlue
LavenderBlush | MintCream | Snow | White |  |  |  |

To set the color for the objects may be using the ObjectSetInteger() and custom indicators using the PlotIndexSetInteger(). To get color values there are similar functions ObjectGetInteger()andPlotIndexGetInteger().

Example:

//---- indicator settings
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 3
#property indicator_type1 DRAW_LINE
#property indicator_type2 DRAW_LINE
#property indicator_type3 DRAW_LINE
#property indicator_color1 Blue
#property indicator_color2 Red
#property indicator_color3 Lime


Wingdings

MQL5 Reference / Standard constants, enumerations and structures / Objects constants / Wingdings

Wingdings

Characters Font Wingdings, used with the object OBJ_ARROW:

Set the desired character is performed using the ObjectSetInteger().

Example:

void OnStart()
{
//---
string up_arrow="up_arrow";
datetime time=TimeCurrent();
double lastClose[1];
int close=CopyClose(Symbol(),Period(),0,1,lastClose); // Get the price Close
//--- If the price was obtained
if(close>0)
{
ObjectCreate(0,up_arrow,OBJ_ARROW,0,0,0,0,0); // Create the arrow
ObjectSetInteger(0,up_arrow,OBJPROP_ARROWCODE,241); // Set the arrow code
ObjectSetInteger(0,up_arrow,OBJPROP_TIME,time); // Set time
ObjectSetDouble(0,up_arrow,OBJPROP_PRICE,lastClose[0]);// Set price
ChartRedraw(0); // Draw arrow now
}
else
Print("Unable to get the latest price Close!");
}


Indicators constants

MQL5 Reference / Standard constants, enumerations and structures / Indicators constants

Indicators constants

There are 37 predefined technical indicators which can be used in programs in the language MQL5. In addition, there is an opportunity to create their own custom indicators using the iCustom(). All necessary constants are divided into 5 groups:

· Price constants- To select the type of price or volume, which is considered an indicator;
· Smoothing methods- Built-in smoothing methods used in the indicators;
· Indicators lines- Indicator buffer IDs when accessing the values of the indicators usingCopyBuffer();
· Drawing styles- To indicate one of 18 types of drawing and set the line style of drawing;
· Custom indicators properties- Are used in functions for working with acustom indicators.


Price constants

MQL5 Reference / Standard constants, enumerations and structures / Indicators constants / Price constants

Price constants

Technical indicators are required for their calculations indicate the values of prices and / or values of the volume at which they will be considered.There are 7 predefined identifiers enumeration ENUM_APPLIED_PRICE, to specify the desired price base calculations.

ENUM_APPLIED_PRICE
ID | Description
PRICE_CLOSE | Closing price
PRICE_OPEN | Opening price
PRICE_HIGH | The maximum price for the period
PRICE_LOW | The minimum price for the period
PRICE_MEDIAN | Median price, (high + low)/2
PRICE_TYPICAL | Typical price, (high + low + close)/3
PRICE_WEIGHTED | Average price, (high + low + close + close)/4

If used in the calculation of the volume, you must specify one of the two transfer ENUM_APPLIED_VOLUME.

ENUM_APPLIED_VOLUME
ID | Description
VOLUME_TICK | Tick volume
VOLUME_REAL | Trade volume

Technical Indicator iStochastic() there are two variants of calculation, which can be used:

· only the prices or Close;
· High prices and a Low.

To select an option to specify the calculation of one of the values enumeration ENUM_STO_PRICE.

ENUM_STO_PRICE

ID | Description
STO_LOWHIGH | Calculation is based on prices Low/High
STO_CLOSECLOSE | Calculation is based on prices Close/Close

If a technical indicator for its calculations using price data of a type that is defined by transfer ENUM_APPLIED_PRICE, then the input price series can be specified Hendl any indicator (built-in terminal or written by the user).In this case, the calculations will be used the values of zero buffer indicator.This makes it easy to build the value of one indicator to another indicator.Hendl custom indicator is created by calling function iCustom().

Example:

#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 2
//--- input parameters
input int RSIperiod=14; // Period for calculating the RSI
input int Smooth=8; // Smoothing period RSI
input ENUM_MA_METHOD meth=MODE_SMMA; // Method of smoothing
//---- plot RSI
#property indicator_label1 "RSI"
#property indicator_type1 DRAW_LINE
#property indicator_color1 Red
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//---- plot RSI_Smoothed
#property indicator_label2 "RSI_Smoothed"
#property indicator_type2 DRAW_LINE
#property indicator_color2 Navy
#property indicator_style2 STYLE_SOLID
#property indicator_width2 1
//--- indicator buffers
double RSIBuffer[]; // Here we store the values of RSI
double RSI_SmoothedBuffer[]; // Here will be smoothed values of RSI
int RSIhandle; // Handle to the RSI indicator
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,RSIBuffer,INDICATOR_DATA);
SetIndexBuffer(1,RSI_SmoothedBuffer,INDICATOR_DATA);
IndicatorSetString(INDICATOR_SHORTNAME,"iRSI");
IndicatorSetInteger(INDICATOR_DIGITS,2);
//---
RSIhandle=iRSI(NULL,0,RSIperiod,PRICE_CLOSE);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[]
)

{
//--- Reset to zero value of the last error
ResetLastError();
//--- Get RSI indicator data in an array RSIBuffer []
int copied=CopyBuffer(RSIhandle,0,0,rates_total,RSIBuffer);
if(copied<=0)
{
Print("Unable to copy the values of the indicator RSI. Error =",
GetLastError(),", copied =",copied);
return(0);
}
//--- Create the indicator of average values of the RSI indicator
int RSI_MA_handle=iMA(NULL,0,Smooth,0,meth,RSIhandle);
copied=CopyBuffer(RSI_MA_handle,0,0,rates_total,RSI_SmoothedBuffer);
if(copied<=0)
{
Print("Unable to copy the smoothed indicator of RSI. Error =",
GetLastError(),", copied =",copied);
return(0);
}
//--- return value of prev_calculated for next call
return(rates_total);
}


Smoothing methods

MQL5 Reference / Standard constants, enumerations and structures / Indicators constants / Smoothing methods

Smoothing methods

At the heart of many technical indicators are those or other methods of smoothing the price series.Some standard technical indicators need to specify the type of smoothing as a parameter.To specify the desired type of smoothing are identifiers listed in the enumeration ENUM_MA_METHOD.

ENUM_MA_METHOD

ID | Description
MODE_SMA | Simple averaging
MODE_EMA | Exponential averaging
MODE_SMMA | Smoothed averaging
MODE_LWMA | Linear-weighted averaging

Example:

double ExtJaws[];
double ExtTeeth[];
double ExtLips[];
//---- handles for moving averages
int ExtJawsHandle;
int ExtTeethHandle;
int ExtLipsHandle;
//--- get MA's handles
ExtJawsHandle=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN);
ExtTeethHandle=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN);
ExtLipsHandle=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN);


Indicators lines

MQL5 Reference / Standard constants, enumerations and structures / Indicators constants / Indicators lines

Indicators lines

Some technical indicators have several rendered on the chart buffer. Numbering indicator buffers starts with 0. When you copy the values of the indicator function CopyBuffer()vin an array of type double for some indicators may not indicate the number of the copied buffer, and the identifier of the buffer.

Identifiers lines indicators permissible copying the values of indicators iMACD(), iRVI() and iStochastic().

ID | Value | Description
MAIN_LINE | 0 | Main Line
SIGNAL_LINE | 1 | Signal Line

Identifiers lines indicators permissible copying the values of indicators ADX() and ADXW().

ID | Value | Description
MAIN_LINE | 0 | Main Line
PLUSDI_LINE | 1 | Line +DI
MINUSDI_LINE | 2 | Line-DI

Identifiers lines indicators permissible copying the values of indicators iBands().

ID | Value | Description
BASE_LINE | 0 | Main Line
UPPER_BAND | 1 | Upper limit
LOWER_BAND | 2 | Lower limit

Identifiers lines indicators permissible copying the values of indicators iEnvelopes(), iFractals() and iGator().

ID | Value | Description
UPPER_LINE | 0 | Upper line
LOWER_LINE | 1 | Bottom line

Identifiers lines indicators permissible copying the values of indicators iAlligator().

ID | Value | Description
GATORJAW_LINE | 0 | Jaw line
GATORTEETH_LINE | 1 | Teeth line
GATORLIPS_LINE | 2 | Lips line

Identifiers lines indicators permissible copying the values of the indicatoriIchimoku().

ID | Value | Description
TENKANSEN_LINE | 0 | Line Tenkan-sen
KIJUNSEN_LINE | 1 | Line Kijun-sen
SENKOUSPANA_LINE | 2 | Line Senkou Span A
SENKOUSPANB_LINE | 3 | Line Senkou Span B
CHINKOUSPAN_LINE | 4 | Line Chinkou Span


Drawing styles

MQL5 Reference / Standard constants, enumerations and structures / Indicators constants / Drawing styles

Drawing styles

When creating a custom indicator You can specify one of 18 types of graphical construction (as displayed in the main chart window or a pane of the chart), whose values are specified enumeration ENUM_DRAW_TYPE.In one user indicator is permissible to use any type of building / rendering of indicators.Each type of construction requires an indication from one to five global arrays for storing data necessary for drawing.

ENUM_DRAW_TYPE
ID | Description
DRAW_NONE | Not drawn
DRAW_LINE | Line
DRAW_SECTION | Section
DRAW_HISTOGRAM | Histogram from the zero line
DRAW_HISTOGRAM2 | Histogram of the two indicator buffers
DRAW_ARROW | Drawing arrows
DRAW_ZIGZAG | Style Zigzag allow vertical section on the bar
DRAW_FILLING | Color fill between the two levels
DRAW_BARS | Displays in the form of bars
DRAW_CANDLES | Displays in the form of candles
DRAW_COLOR_LINE | Colorful Line
DRAW_COLOR_SECTION | Multicolored section
DRAW_COLOR_HISTOGRAM | Multicolored histogram from the zero line
DRAW_COLOR_HISTOGRAM2 | Multicolored histogram of the two indicator buffers
DRAW_COLOR_ARROW | Drawing colored arrows
DRAW_COLOR_ZIGZAG | Colorful ZigZag
DRAW_COLOR_BARS | Multi-colored bars
DRAW_COLOR_CANDLES | Multi-colored candles

To refine the display of the selected type of rendering used identifiers listed in the transfers ENUM_PLOT_PROPERTY.

For functions PlotIndexSetInteger() and PlotIndexGetInteger()

ENUM_PLOT_PROPERTY_INTEGER
ID | Description | Property type
PLOT_ARROW | Code of arrow for style DRAW_ARROW | uchar
PLOT_ARROW_SHIFT | Offset vertical shooter for the style DRAW_ARROW | int
PLOT_DRAW_BEGIN | Number of primary bars without drawing, and values in the DataWindow | int
PLOT_DRAW_TYPE | Type of graphical plot | ENUM_DRAW_TYPE
PLOT_SHOW_DATA | Symptom display values in constructing the window DataWindow | bool
PLOT_SHIFT | Shift of graphical construction of the indicator on the axis of time in bars | int
PLOT_LINE_STYLE | Line drawing style | ENUM_LINE_STYLE
PLOT_LINE_WIDTH | The thickness of the line drawing | int
PLOT_COLOR_INDEXES | The number of color buffers | int
PLOT_LINE_COLOR | The index buffer containing the color rendering | color modifier = index number of colors

For functionPlotIndexSetDouble()

ENUM_PLOT_PROPERTY_DOUBLE
ID | Description | Property type
PLOT_EMPTY_VALUE | An empty value for the plot, for which there is no draw | double

For functionPlotIndexSetString()

ENUM_PLOT_PROPERTY_STRING
ID | Description | Property type
PLOT_LABEL | The name of the plot for the graphics display in the window, DataWindow | string

There are 5 different styles, which can draw the line in the user's display. They apply only when the thickness of the line of 0 or 1.

ENUM_LINE_STYLE
ID | Description
STYLE_SOLID | Solid line
STYLE_DASH | Broken line
STYLE_DOT | Dotted line
STYLE_DASHDOT | Dash-dot line
STYLE_DASHDOTDOT | Bar - two points

To set the style of drawing the line and the type of drawing function is used PlotIndexSetInteger(). For the Fibonacci extensions indicate the thickness and style of rendering levels can be a function of ObjectSetInteger().

Example:

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//--- indicator buffers
double MABuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- Bind the Array to the indicator buffer with index 0
SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
//--- Set the line drawing
PlotIndexSetInteger(0,PLOT_DRAW_TYPE,DRAW_LINE);
//--- Set the style line
PlotIndexSetInteger(0,PLOT_LINE_STYLE,STYLE_DOT);
//--- Set line color
PlotIndexSetInteger(0,PLOT_LINE_COLOR,Red);
//--- Set line thickness
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,1);
//--- Set label for the plot
PlotIndexSetString(0,PLOT_LABEL,"Moving Average");
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
for(int i=prev_calculated;i<rates_total;i++)
{
MABuffer[i]=close[i];
}
//--- return value of prev_calculated for next call
return(rates_total);
}


Custom indicators properties

MQL5 Reference / Standard constants, enumerations and structures / Indicators constants / Custom indicators properties

Custom indicators properties

The number of indicator buffers that can be used in the user's display is not limited. But each array, which is designated as the indicator buffer using the function SetIndexBuffer(), Must specify the type of data that it will store. This may be one of the values of the transfer ENUM_INDEXBUFFER_TYPE.

ENUM_INDEXBUFFER_TYPE
ID | Description
INDICATOR_DATA | The data for rendering
INDICATOR_COLOR_INDEX | Color rendering
INDICATOR_CALCULATIONS | Auxiliary buffer for intermediate calculations

Custom indicator has a lot of settings for ease of display and perception. These settings are made through the assignment of the properties of the indicator with the help of functions IndicatorSetDouble(), IndicatorSetInteger()andIndicatorSetString(). Identifiers indicator properties listed in the transfers ENUM_CUSTOMIND_PROPERTY.

ENUM_CUSTOMIND_PROPERTY_INTEGER
ID | Description | Property type
INDICATOR_DIGITS | Accuracy of mapping values of the indicator | int
INDICATOR_LEVELS | Number of levels in the indicator window | int
INDICATOR_LEVELCOLOR | Level Line Color | color modifier = level number
INDICATOR_LEVELSTYLE | Level Line Style | ENUM_LINE_STYLE modifier = level number
INDICATOR_LEVELWIDTH | The thickness of the line level | int modifier = level number
ENUM_CUSTOMIND_PROPERTY_DOUBLE
ID | Description | Property type
INDICATOR_MINIMUM | Indicator window Maximum | double
INDICATOR_MAXIMUM | Indicator window Minimum | double
INDICATOR_LEVELVALUE | Level value | double modifier = level number
ENUM_CUSTOMIND_PROPERTY_STRING
ID | Description | Property type
INDICATOR_SHORTNAME | Short indicator name | string
INDICATOR_LEVELTEXT | Level description | string modifier = level number

Examples:

//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots 2
#property indicator_type1 DRAW_LINE
#property indicator_type2 DRAW_LINE
#property indicator_color1 LightSeaGreen
#property indicator_color2 Red
//--- input parameters
extern int KPeriod=5;
extern int DPeriod=3;
extern int Slowing=3;
//--- indicator buffers
double MainBuffer[];
double SignalBuffer[];
double HighesBuffer[];
double LowesBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,MainBuffer,INDICATOR_DATA);
SetIndexBuffer(1,SignalBuffer,INDICATOR_DATA);
SetIndexBuffer(2,HighesBuffer,INDICATOR_CALCULATIONS);
SetIndexBuffer(3,LowesBuffer,INDICATOR_CALCULATIONS);
//--- set accuracy
IndicatorSetInteger(INDICATOR_DIGITS,2);
//--- set levels
IndicatorSetInteger(INDICATOR_LEVELS,2);
IndicatorSetDouble(INDICATOR_LEVELVALUE,0,20);
IndicatorSetDouble(INDICATOR_LEVELVALUE,1,80);
//--- set maximum and minimum for subwindow
IndicatorSetDouble(INDICATOR_MINIMUM,0);
IndicatorSetDouble(INDICATOR_MAXIMUM,100);
//--- sets first bar from what index will be drawn
PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,KPeriod+Slowing-2);
PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,KPeriod+Slowing+DPeriod);
//--- set style STYLE_DOT for second line
PlotIndexSetInteger(1,PLOT_LINE_STYLE,STYLE_DOT);
//--- name for DataWindow and indicator subwindow label
IndicatorSetString(INDICATOR_SHORTNAME,"Stoch("+KPeriod+","+DPeriod+","+Slowing+")");
PlotIndexSetString(0,PLOT_LABEL,"Main");
PlotIndexSetString(1,PLOT_LABEL,"Signal");
//--- sets drawing line empty value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0.0);
//--- initialization done
}


Trade constants

MQL5 Reference / Standard constants, enumerations and structures / Trade constants

Trade constants

The various constants used for a trading strategies programming, are divided into the following groups:

· Client terminal properties- Information about the client terminal;
· Executed MQL5-program properties- MQL5 program properties, which help to control its execution;
· Symbol properties- To obtain information about the symbol;
· Account properties- Information about current account;
· Order properties- To obtain information about trade orders;
· Position properties- To obtain information about current positions;
· Deal properties- Obtain information about deals;
· Trade operation types- Contain a description of trade operations.


Client terminal properties

MQL5 Reference / Standard constants, enumerations and structures / Trade constants / Client terminal properties

Client terminal properties

To obtain an information about the client terminal there are two functions TerminalInfoInteger() and TerminalInfoString() The function parameter values can selected from the corresponding enumerations ENUM_TERMINAL_INFO_INTEGER and ENUM_TERMINAL_INFO_STRING.

ENUM_TERMINAL_INFO_INTEGER
Identifier | Description | Type
TERMINAL_BUILD | The client terminal build number | int
TERMINAL_CONNECTED | Connection state at present time | bool
TERMINAL_DLLS_ALLOWED | Permission state for DLL use | bool
TERMINAL_TRADE_ALLOWED | Permission state for trade | bool
TERMINAL_EMAIL_ENABLED | Permission state for e-mail sending using SMTP-server and login, specified in the terminal settings | bool
TERMINAL_FTP_ENABLED | Permission state for report sending using FTP-server and login, specified in the terminal settings | bool
TERMINAL_MAXBARS | The maximal bars count on the chart | int

The file operations can be performed only in two folders, their names can be obtained using the request for TERMINAL_DATA_PATH and TERMINAL_COMMONDATA_PATH properties.

ENUM_TERMINAL_INFO_STRING
Identifier | Description | Type
TERMINAL_COMPANY | Company name | string
TERMINAL_NAME | Terminal name | string
TERMINAL_PATH | Terminal path | string
TERMINAL_DATA_PATH | Terminal data path | string
TERMINAL_COMMONDATA_PATH | Common path for all of the terminals installed on the computer | string

For a better understanding of the paths, served in properties of TERMINAL_PATH, TERMINAL_DATA_PATH and TERMINAL_COMMONDATA_PATH parameters, it is recommended to execute the script, which print these values for the current copy of the client terminal, installed on your computer.

Example: Script prints an information about the client terminal paths

//+------------------------------------------------------------------+
//| Check_TerminalPaths.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
Print("TERMINAL_PATH =",TerminalInfoString(TERMINAL_PATH));
Print("TERMINAL_DATA_PATH =",TerminalInfoString(TERMINAL_DATA_PATH));
Print("TERMINAL_COMMONDATA_PATH =",TerminalInfoString(TERMINAL_COMMONDATA_PATH));
}

As result of the script execution in the Experts Journal you will see a messages, like the following:


Executed MQL program properties

MQL5 Reference / Standard constants, enumerations and structures / Trade constants / Executed MQL program properties

Executed MQL program properties

To obtain an information about the executed MQL program there are some constants enumerated in ENUM_MQL5_INFO_INTEGER and ENUM_MQL5_INFO_STRING.

ENUM_MQL5_INFO_INTEGER
Identifier | Description | Type
MQL5_PROGRAM_TYPE | Program type, that called the library (script,expert etc) | int
MQL5_DLLS_ALLOWED | The permission to use DLL for the given executed program | bool
MQL5_TRADE_ALLOWED | The permission to trade for the given executed program | bool
MQL5_DEBUGGING | The flag, that indicates for the debug mode | bool
MQL5_TESTING | The flag, that indicates for the tester process | bool
MQL5_OPTIMIZATION | The flag, that indicates for the optimization process | bool
MQL5_VISUAL_MODE | The flag, that indicates for the visual tester process | bool
ENUM_MQL5_INFO_STRING
Identifier | Description | Type
MQL5_PROGRAM_NAME | Name of the mql5-program executed | string
MQL5_PROGRAM_PATH | Path for the given executed program | string


Symbol properties

MQL5 Reference / Standard constants, enumerations and structures / Trade constants / Symbol properties

Symbol properties

To obtain the current price information there are several functions SymbolInfoInteger(), SymbolInfoDouble() and SymbolInfoString(). The first parameter is the symbol name, the values of the second function parameter can selected from the one of the enumerations ENUM_SYMBOL_INFO_INTEGER, ENUM_SYMBOL_INFO_DOUBLE and ENUM_SYMBOL_INFO_STRING.

ENUM_SYMBOL_INFO_INTEGER
Identifier | Description | Type
SYMBOL_SELECT | Symbol is selected in Market Watch | bool
SYMBOL_VOLUME | Volume of the last deal | long
SYMBOL_VOLUMEHIGH | Maximal day volume | long
SYMBOL_VOLUMELOW | Minimal day volume | long
SYMBOL_VOLUMEBID | Volume for current Bid | long
SYMBOL_VOLUMEASK | Volume for current Ask | long
SYMBOL_TIME | Time of the last quote | datetime
SYMBOL_DIGITS | Decimal significant digits | int
SYMBOL_SPREAD | Spread value in points | int
SYMBOL_TICKS_BOOKDEPTH | Ticks booking depth | int
SYMBOL_TRADE_CALC_MODE | Symbol trade calculation mode | ENUM_SYMBOL_CALC_MODE
SYMBOL_TRADE_MODE | Symbol trade mode | ENUM_SYMBOL_TRADE_MODE
SYMBOL_TRADE_STOPS_LEVEL | Symbol stop level in points | int
SYMBOL_TRADE_FREEZE_LEVEL | Symbol freeze level in points | int
SYMBOL_TRADE_EXEMODE | Trade execution mode | ENUM_SYMBOL_TRADE_EXECUTION
SYMBOL_SWAP_MODE | Swap calculation mode | ENUM_SYMBOL_SWAP_MODE
SYMBOL_SWAP_ROLLOVER3DAYS | Swap 3 days rollover | ENUM_DAY_OF_WEEK
ENUM_SYMBOL_INFO_DOUBLE
Identifier | Description | Type
SYMBOL_BID | Symbol Bid | double
SYMBOL_BIDHIGH | Maximal Bid of the day | double
SYMBOL_BIDLOW | Minimal Bid of the day | double
SYMBOL_ASK | Symbol Ask | double
SYMBOL_ASKHIGH | Maximal Ask of the day | double
SYMBOL_ASKLOW | Minimal Ask of the day | double
SYMBOL_LAST | Price of the last deal | double
SYMBOL_LASTHIGH | Maximal Last of the day | double
SYMBOL_LASTLOW | Minimal Last of the day | double
SYMBOL_POINT | Symbol point value | double
SYMBOL_TRADE_TICK_VALUE | Trade tick value | double
SYMBOL_TRADE_TICK_SIZE | Trade tick size | double
SYMBOL_TRADE_CONTRACT_SIZE | Trade contract size | double
SYMBOL_VOLUME_MIN | Minimal volume for trade | double
SYMBOL_VOLUME_MAX | Maximal volume for trade | double
SYMBOL_VOLUME_STEP | Minimal volume step | double
SYMBOL_SWAP_LONG | Long swap value | double
SYMBOL_SWAP_SHORT | Short swap value | double
ENUM_SYMBOL_INFO_STRING
Identifier | Description | Type
SYMBOL_CURRENCY_BASE | Symbol currency | string
SYMBOL_CURRENCY_PROFIT | Profit currency | string
SYMBOL_CURRENCY_MARGIN | Margin currency | string
SYMBOL_BANK | Symbol bank of the quote | string
SYMBOL_DESCRIPTION | Symbol description | string
SYMBOL_PATH | Symbol path in the symbol tree | string
ENUM_SYMBOL_CALC_MODE
Identifier | Description | Formula
SYMBOL_CALC_MODE_FOREX | Forex mode | Margin: (Lots*Contract_Size/Leverage)/100 Profit: (close_price-open_price)*Contract_Size*Lots
SYMBOL_CALC_MODE_CFD | CFD mode | Margin: Lots *ContractSize*MarketPrice*Percentage/100 Profit: (close_price-open_price)*Contract_Size*Lots
SYMBOL_CALC_MODE_FUTURES | Futures mode | Margin: Lots *InitialMargin*Percentage/100 Profit: (close_price-open_price)*TickPrice/TickSize*Lots
SYMBOL_CALC_MODE_CFDINDEX | CFD index mode | Margin: (Lots*ContractSize*MarketPrice)*TickPrice/TickSize Profit: (close_price-open_price)*Contract_Size*Lots
SYMBOL_CALC_MODE_CFDLEVERAGE | CFD Leverage mode | Margin:(Lots*ContractSize*MarketPrice)/Leverage*Percentage/100 Profit: (close_price-open_price)*Contract_Size*Lots
ENUM_SYMBOL_TRADE_MODE
Identifier | Description
SYMBOL_TRADE_MODE_DISABLED | Trade is disabled
SYMBOL_TRADE_MODE_LONGONLY | Allowed only long positions
SYMBOL_TRADE_MODE_SHORTONLY | Allowed only short positions
SYMBOL_TRADE_MODE_CLOSEONLY | Allowed only position close operations
SYMBOL_TRADE_MODE_FULL | No trade restrictions
ENUM_SYMBOL_TRADE_EXECUTION
Identifier | Description
SYMBOL_TRADE_EXECUTION_REQUEST | Execution by request
SYMBOL_TRADE_EXECUTION_INSTANT | Instant execution
SYMBOL_TRADE_EXECUTION_MARKET | Market execution
ENUM_SYMBOL_SWAP_MODE
Identifier | Description
SYMBOL_SWAP_MODE_DISABLED | Swap mode disabled (no swaps)
SYMBOL_SWAP_MODE_BY_POINTS | Swaps in points
SYMBOL_SWAP_MODE_BY_MONEY | Swaps in money, its value is specified in the symbol properties in the deposit currency
SYMBOL_SWAP_MODE_BY_INTEREST | Swaps in yearly percents (bank mode - 360 days in a year)
SYMBOL_SWAP_MODE_BY_MARGIN_CURRENCY | Swaps in money, its value is specified in the symbol properties in the margin currency
ENUM_DAY_OF_WEEK
Identifier | Description
SUNDAY | Sunday
MONDAY | Monday
TUESDAY | Tuesday
WEDNESDAY | Wednesday
THURSDAY | Thursday
FRIDAY | Friday
SATURDAY | Saturday


Historical database properties

MQL5 Reference / Standard constants, enumerations and structures / Trade constants / Historical database properties

Historical database properties

At access to timeseries for additional symbol information the function SeriesInfoInteger() is used. The values of the function parameter can be selected from the enumeration ENUM_SERIES_INFO_INTEGER.

ENUM_SERIES_INFO_INTEGER

Identifier | Description | Type
BARS_COUNT | Bars count for the symbol-period at present time | long
BARS_SERIES_FIRSTDATE | The very first date for the symbol-period at present time | datetime
BARS_FIRSTDATE | The very first date in the history on the server for the symbol-period at present time | datetime
BARS_SYNCRONIZED | Symbol data synchronization flag | bool


Account properties

MQL5 Reference / Standard constants, enumerations and structures / Trade constants / Account properties

Account properties

To obtain an information about the current account there are several functions AccountInfoInteger(), AccountInfoDouble() and AccountInfoString(). The function parameter values can selected from the corresponding enumeration ENUM_ACCOUNT_INFO.

For functionAccountInfoInteger()

ENUM_ACCOUNT_INFO_INTEGER
Identifier | Description | Type
ACCOUNT_LOGIN | Account number | long
ACCOUNT_TRADE_MODE | Account trade mode | ENUM_ACCOUNT_TRADE_MODE
ACCOUNT_LEVERAGE | Account leverage | long
ACCOUNT_MARGIN_SO_MODE | Account margin stop out mode | ENUM_ACCOUNT_STOPOUT_MODE
ACCOUNT_TRADE_ALLOWED | Account trade allowed | bool
ACCOUNT_TRADE_EXPERT | Account expert allowed | bool

For functionAccountInfoDouble()

ENUM_ACCOUNT_INFO_DOUBLE
Identifier | Description | Type
ACCOUNT_BALANCE | Account balance | double
ACCOUNT_CREDIT | Account credit | double
ACCOUNT_PROFIT | Account profit | double
ACCOUNT_EQUITY | Account equity | double
ACCOUNT_MARGIN | Account margin used | double
ACCOUNT_FREEMARGIN | Account free margin | double
ACCOUNT_MARGIN_LEVEL | Account margin level | double
ACCOUNT_MARGIN_SO_CALL | Margin call level | double
ACCOUNT_MARGIN_SO_SO | Margin stop out level | double

For functio AccountInfoString()

ENUM_ACCOUNT_INFO_STRING
Identifier | Description | Type
ACCOUNT_NAME | Client name | string
ACCOUNT_SERVER | Trade server name | string
ACCOUNT_CURRENCY | Account currency | string
ACCOUNT_COMPANY | Company name | string
ENUM_ACCOUNT_TRADE_MODE
Identifier | Description
ACCOUNT_TRADE_MODE_DEMO | Demo account
ACCOUNT_TRADE_MODE_CONTEST | Contest account
ACCOUNT_TRADE_MODE_REAL | Real account
ENUM_ACCOUNT_STOPOUT_MODE
Identifier | Description
ACCOUNT_STOPOUT_MODE_PERCENT | Account stop out mode in percents
ACCOUNT_STOPOUT_MODE_MONEY | Account stop out mode in money


Order properties

MQL5 Reference / Standard constants, enumerations and structures / Trade constants / Order properties

Order properties

ENUM_ORDER_PROPERTY_INTEGER
Identifier | Description | Type
ORDER_TIME_SETUP | Order setup time | datetime
ORDER_TYPE | Order type | ENUM_ORDER_TYPE
ORDER_STATE | Order state | ENUM_ORDER_STATE
ORDER_TIME_EXPIRATION | Order expiration time | datetime
ORDER_TIME_DONE | Order done time | datetime
ORDER_TYPE_FILLING | Order type filling | ENUM_ORDER_TYPE_FILLING
ORDER_TYPE_TIME | Order lifetime | ENUM_ORDER_TYPE_TIME
ORDER_MAGIC | Order expert ID (designed to ensure that each expert pointed out its own unique number) | long
ENUM_ORDER_PROPERTY_DOUBLE
Identifier | Description | Type
ORDER_VOLUME_INITIAL | Order initial volume | double
ORDER_VOLUME_CURRENT | Order current volume | double
ORDER_PRICE_OPEN | Order open price | double
ORDER_SL | Stop Loss value | double
ORDER_TP | Take Profit value | double
ORDER_PRICE_CURRENT | The current price of the order symbol | double
ORDER_PRICE_STOPLIMIT | The limit order price for the StopLimit order | double
ENUM_ORDER_PROPERTY_STRING
Identifier | Description | Type
ORDER_SYMBOL | Order symbol | string
ORDER_COMMENT | Order comment | string
ENUM_ORDER_TYPE
Identifier | Description
ORDER_TYPE_BUY | Buy order
ORDER_TYPE_SELL | Sell order
ORDER_TYPE_BUY_LIMIT | Buy Limit pending order
ORDER_TYPE_SELL_LIMIT | Sell Limit pending order
ORDER_TYPE_BUY_STOP | Buy Stop pending order
ORDER_TYPE_SELL_STOP | Sell Stop pending order
ORDER_TYPE_BUY_STOP_LIMIT | In the case of the order price place Buy Limit pending order at StopLimit price
ORDER_TYPE_SELL_STOP_LIMIT | In the case of the order price place Sell Limit pending order at StopLimit price
ENUM_ORDER_STATE
Identifier | Description
ORDER_STATE_STARTED | Order checked, but not yet accepted by broker
ORDER_STATE_PLACED | Order accepted
ORDER_STATE_CANCELED | Order canceled
ORDER_STATE_PARTIAL | Order partially executed
ORDER_STATE_FILLED | Order fully executed
ORDER_STATE_REJECTED | Order rejected
ORDER_STATE_EXPIRED | Order expired
ENUM_ORDER_TYPE_FILLING
Identifier | Description
ORDER_FILLING_AON | The deal can be executed exclusively with a specified volume at the equal or the better price than the order specified price. If there is no sufficient volume offers on the order symbol, the order will not executed.
ORDER_FILLING_CANCEL | An agreement to execute the deal with maximal market volume at the equal or the better price than the order specified price. In such case an additional order for volume unfilled will not executed.
ORDER_FILLING_RETURN | An agreement to execute the deal with maximal market volume at the equal or the better price than the order specified price. In such case an additional order for volume unfilled will be executed.
ENUM_ORDER_TYPE_TIME
Identifier | Description
ORDER_TIME_GTC | Good till cancel order
ORDER_TIME_DAY | Good till current trade day order
ORDER_TIME_SPECIFIED | Good till expired order


Position properties

MQL5 Reference / Standard constants, enumerations and structures / Trade constants / Position properties

Position properties

ENUM_POSITION_PROPERTY_INTEGER
Identifier | Description | Type
POSITION_TIME | Position open time | datetime
POSITION_TYPE | Position type | ENUM_POSITION_TYPE
POSITION_MAGIC | Position magic number (see ORDER_MAGIC) | long
ENUM_POSITION_PROPERTY_DOUBLE
Identifier | Description | Type
POSITION_VOLUME | Position volume | double
POSITION_PRICE_OPEN | Position open price | double
POSITION_SL | Stop Loss level of opened position | double
POSITION_TP | Take Profit level of opened position | double
POSITION_PRICE_CURRENT | Current price of the position symbol | double
POSITION_COMMISSION | Commission | double
POSITION_SWAP | Cumulative swap | double
POSITION_PROFIT | Current profit | double
ENUM_POSITION_PROPERTY_STRING
Identifier | Description | Type
POSITION_SYMBOL | Position symbol | string
POSITION_COMMENT | Position comment | string
ENUM_POSITION_TYPE
Identifier | Description
POSITION_TYPE_BUY | Buy
POSITION_TYPE_SELL | Sell


Deal properties

MQL5 Reference / Standard constants, enumerations and structures / Trade constants / Deal properties

Deal properties

ENUM_DEAL_PROPERTY_INTEGER
Identifier | Description | Type
DEAL_ORDER | Deal order number | long
DEAL_TIME | Deal time | datetime
DEAL_TYPE | Deal type | ENUM_DEAL_TYPE
DEAL_ENTRY | Deal entry - entry in, entry out, reverse | ENUM_DEAL_ENTRY
DEAL_MAGIC | Deal magic number (see ORDER_MAGIC) | long
ENUM_DEAL_PROPERTY_DOUBLE
Identifier | Description | Type
DEAL_VOLUME | Deal volume | double
DEAL_PRICE | Deal price | double
DEAL_COMMISSION | Deal commission | double
DEAL_SWAP | Cumulative swap on close | double
DEAL_PROFIT | Deal profit | double
ENUM_DEAL_PROPERTY_STRING
Identifier | Description | Type
DEAL_SYMBOL | Deal symbol | string
DEAL_COMMENT | Deal comment | string
ENUM_DEAL_TYPE
Identifier | Description
DEAL_TYPE_BUY | Buy
DEAL_TYPE_SELL | Sell
DEAL_TYPE_BALANCE | Balance
DEAL_TYPE_CREDIT | Credit
DEAL_TYPE_CHARGE | Additional charge
DEAL_TYPE_CORRECTION | Correction

ENUM_DEAL_ENTRY

Identifier | Description
DEAL_ENTRY_IN | Entry in
DEAL_ENTRY_OUT | Entry out
DEAL_ENTRY_INOUT | Reverse
DEAL_ENTRY_STATE | Status record


Trade operation types

MQL5 Reference / Standard constants, enumerations and structures / Trade constants / Trade operation types

Trade operation types

Trading is done by sending orders to open positions using the function OrderSend(), as well as pending orders operations like for order place, modification and delete. Each trade order refers to the type of the requested operation. Trading operations are described in the enumeration ENUM_TRADE_REQUEST_ACTIONS.

ENUM_TRADE_REQUEST_ACTIONS

Identifier | Description
TRADE_ACTION_DEAL | Place a trade order for an immediate execution with the specified parameters (market order)
TRADE_ACTION_PENDING | Place a trade order on the execution under specified conditions (pending order)
TRADE_ACTION_SLTP | Modify Stop Loss and Take Profit values of the opened position
TRADE_ACTION_MODIFY | Modify the parameters of the order placed previously
TRADE_ACTION_REMOVE | Delete the pending order placed previously


Named constants

MQL5 Reference / Standard constants, enumerations and structures / Named constants

Named constants

All of the constants used in MQL5 can be divided into following groups:

· Predefined macrosubstitutions- Its values are substituting during the compilation;
· Mathematical constants- Numerical values of some mathematical expressions;
· Numerical type constants- Some of the simple type restrictions;
· Deinitialization reason codes- Deinitialization reasons codes description;
· Other constants- All other constants.


Predefined macrosubstitutions

MQL5 Reference / Standard constants, enumerations and structures / Named constants / Predefined macrosubstitutions

Predefined macrosubstitutions

To simplify debug process and obtain and information about mql5-program there are special macro constant which values are set at the moment of compilation.The most simple way of use of these constants - an output of its values by function.Print(), as shown in an example.

Constant | Description
__LINE__ | String number in the source code in which macros located
__FILE__ | Name of the current compiled file
__FUNCTION__ | Name of the function in which macros located
__MQ5BUILD__ | Compiler build number

Example:

#property copyright "Copyright Â © 2009, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- an example of information output at expert initialization
Print(" __FUNCTION__ =",__FUNCTION__," __LINE__ =",__LINE__);
//--- set the interval between the timer events
EventSetTimer(5);
//---
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- an example of information output at expert deinitialization
Print(" __FUNCTION__ =",__FUNCTION__," __LINE__ =",__LINE__);
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- information output at tick receipt
Print(" __MQ5BUILD__ =",__MQ5BUILD__," __FILE__ =",__FILE__);
Print(" __FUNCTION__ =",__FUNCTION__," __LINE__ =",__LINE__);
test1(__FUNCTION__);
test2();
//---
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void test1(string par)
{
//--- information output inside the function
Print(" __FUNCTION__ =",__FUNCTION__," __LINE__ =",__LINE__," par=",par);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void test2()
{
//--- information output inside the function
Print(" __FUNCTION__ =",__FUNCTION__," __LINE__ =",__LINE__);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnTimer()
{
//---
Print(" __FUNCTION__ =",__FUNCTION__," __LINE__ =",__LINE__);
test1(__FUNCTION__);
}
//+------------------------------------------------------------------+


Mathematical constants

MQL5 Reference / Standard constants, enumerations and structures / Named constants / Mathematical constants

Mathematical constants

The special constants containing values are reserved for some mathematical expressions. These constants can be used in any place of the program instead of calculation of their values using the mathematical functions.

Constant | Description | Value
M_E | e | 2.71828182845904523536
M_LOG2E | log2(e) | 1.44269504088896340736
M_LOG10E | log10(e) | 0.434294481903251827651
M_LN2 | ln(2) | 0.693147180559945309417
M_LN10 | ln(10) | 2.30258509299404568402
M_PI | pi | 3.14159265358979323846
M_PI_2 | pi/2 | 1.57079632679489661923
M_PI_4 | pi/4 | 0.785398163397448309616
M_1_PI | 1/pi | 0.318309886183790671538
M_2_PI | 2/pi | 0.636619772367581343076
M_2_SQRTPI | 2/sqrt(pi) | 1.12837916709551257390
M_SQRT2 | sqrt(2) | 1.41421356237309504880
M_SQRT1_2 | 1/sqrt(2) | 0.707106781186547524401

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the values of constants
Print("M_E =",DoubleToString(M_E,16));
Print("M_LOG2E =",DoubleToString(M_LOG2E,16));
Print("M_LOG10E =",DoubleToString(M_LOG10E,16));
Print("M_LN2 =",DoubleToString(M_LN2,16));
Print("M_LN10 =",DoubleToString(M_LN10,16));
Print("M_PI =",DoubleToString(M_PI,16));
Print("M_PI_2 =",DoubleToString(M_PI_2,16));
Print("M_PI_4 =",DoubleToString(M_PI_4,16));
Print("M_1_PI =",DoubleToString(M_1_PI,16));
Print("M_2_PI =",DoubleToString(M_2_PI,16));
Print("M_2_SQRTPI =",DoubleToString(M_2_SQRTPI,16));
Print("M_SQRT2 =",DoubleToString(M_SQRT2,16));
Print("M_SQRT1_2 =",DoubleToString(M_SQRT1_2,16));
}


Numerical type constants

MQL5 Reference / Standard constants, enumerations and structures / Named constants / Numerical type constants

Numerical type constants

Each simple numerical type is intended for a certain type of problems and allows to optimize mql5-program work at correct application. For the best code readership and correct calculations results processing there are constants which allow to receive an information about the imposed type restrictions.

Constant | Description | Value
CHAR_MIN | Minimal value, which can be represented by char type | -128
CHAR_MAX | Maximal value, which can be represented by char type | 127
UCHAR_MAX | Maximal value, which can be represented by uchar type | 255
SHORT_MIN | Minimal value, which can be represented by short type | -32768
SHORT_MAX | Maximal value, which can be represented by short type | 32767
USHORT_MAX | Maximal value, which can be represented by ushort type | 65535
INT_MIN | Minimal value, which can be represented by int type | -2147483648
INT_MAX | Maximal value, which can be represented by int type | 2147483647
UINT_MAX | Maximal value, which can be represented by uint type | 4294967295
LONG_MIN | Minimal value, which can be represented by long type | -9223372036854775808
LONG_MAX | Maximal value, which can be represented by long type | 9223372036854775807
ULONG_MAX | Maximal value, which can be represented by ulong type | 18446744073709551615
DBL_MIN | Minimal positive value, which can be represented by double type | 2.2250738585072014e-308
DBL_MAX | Maximal value, which can be represented by double type | 1.7976931348623158e+308
DBL_EPSILON | Minimal value, which satisfies the condition: 1.0+DBL_EPSILON != 1.0 (for double type) | 2.2204460492503131e-016
DBL_DIG | Number of significant decimal digits for double type | 15
DBL_MANT_DIG | Bits count in a mantissa for double type | 53
DBL_MAX_10_EXP | Maximal decimal value of exponent degree for double type | 308
DBL_MAX_EXP | Maximal binary value of exponent degree for double type | 1024
DBL_MIN_10_EXP | Minimal decimal value of exponent degree for double type | (-307)
DBL_MIN_EXP | Minimal binary value of exponent degree for double type | (-1021)
FLT_MIN | Minimal positive value, which can be represented by float type | 1.175494351e-38
FLT_MAX | Maximal value, which can be represented by float type | 3.402823466e+38
FLT_EPSILON | Minimal value, which satisfies the condition: 1.0+DBL_EPSILON != 1.0 (for float type) | 1.192092896e-07
FLT_DIG | Number of significant decimal digits for float type | 6
FLT_MANT_DIG | Bits count in a mantissa for float type | 24
FLT_MAX_10_EXP | Maximal decimal value of exponent degree for float type | 38
FLT_MAX_EXP | Maximal binary value of exponent degree for float type | 128
FLT_MIN_10_EXP | Minimal decimal value of exponent degree for float type | -37
FLT_MIN_EXP | Minimal binary value of exponent degree for float type | (-125)

Example:

void OnStart()
{
//--- print the constant values
printf("CHAR_MIN = %d",CHAR_MIN);
printf("CHAR_MAX = %d",CHAR_MAX);
printf("UCHAR_MAX = %d",UCHAR_MAX);
printf("SHORT_MIN = %d",SHORT_MIN);
printf("SHORT_MAX = %d",SHORT_MAX);
printf("USHORT_MAX = %d",USHORT_MAX);
printf("INT_MIN = %d",INT_MIN);
printf("INT_MAX = %d",INT_MAX);
printf("UINT_MAX = %u",UINT_MAX);
printf("LONG_MIN = %I64d",LONG_MIN);
printf("LONG_MAX = %I64d",LONG_MAX);
printf("ULONG_MAX = %I64u",ULONG_MAX);
printf("EMPTY_VALUE = %.16e",EMPTY_VALUE);
printf("DBL_MIN = %.16e",DBL_MIN);
printf("DBL_MAX = %.16e",DBL_MAX);
printf("DBL_EPSILON = %.16e",DBL_EPSILON);
printf("DBL_DIG = %d",DBL_DIG);
printf("DBL_MANT_DIG = %d",DBL_MANT_DIG);
printf("DBL_MAX_10_EXP = %d",DBL_MAX_10_EXP);
printf("DBL_MAX_EXP = %d",DBL_MAX_EXP);
printf("DBL_MIN_10_EXP = %d",DBL_MIN_10_EXP);
printf("DBL_MIN_EXP = %d",DBL_MIN_EXP);
printf("FLT_MIN = %.8e",FLT_MIN);
printf("FLT_MAX = %.8e",FLT_MAX);
printf("FLT_EPSILON = %.8e",FLT_EPSILON);
}


Deinitalization reason codes

MQL5 Reference / Standard constants, enumerations and structures / Named constants / Deinitalization reason codes

Deinitalization reason codes

The deinitalization reason codes are returned by function UninitializeReason(). The possible values are the following:

Constant | Value | Description
REASON_REMOVE | 1 | Program has been deleted from the chart
REASON_RECOMPILE | 2 | Program has been recompiled
REASON_CHARTCHANGE | 3 | Symbol or chart period has been changed
REASON_CHARTCLOSE | 4 | Chart has been closed
REASON_PARAMETERS | 5 | An input parameters has been changed by user
REASON_ACCOUNT | 6 | A new account has been activated
REASON_TEMPLATE | 7 | A new template has been applied
REASON_INITFAILED | 8 | This value means that OnInit() handler has returned nonzero value.

The deinitialization reason code is also passed as a parameter of the predetermined function OnDeinit(const int reason).

Example:

input int par=7;
//+------------------------------------------------------------------+
//| get text description |
//+------------------------------------------------------------------+
string getUnitReasonText(int reasonCode)
{
string text="";
//---
switch(reasonCode)
{
case REASON_ACCOUNT:
text="Account was changed";break;
case REASON_CHARTCHANGE:
text="Symbol or timeframe was changed";break;
case REASON_CHARTCLOSE:
text="Chart was closed";break;
case REASON_PARAMETERS:
text="Input-parameter was changed";break;
case REASON_RECOMPILE:
text="Program "+__FILE__+" was recompiled";break;
case REASON_REMOVE:
text="Program "+__FILE__+" was removed from chart";break;
case REASON_TEMPLATE:
text="New template was applied to chart";break;
default:text="Another reason";
}
//---
return text;
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- The first way to get the deinitalization reason code
Print(__FUNCTION__,"_Deinitalization reason code =",reason);
//--- The second way to get the deinitalization reason code
Print(__FUNCTION__,"_UninitReason =",getUnitReasonText(_UninitReason));
}


Other constants

MQL5 Reference / Standard constants, enumerations and structures / Named constants / Other constants

Other constants

The CLR_NONE constant used to outline the absence of color, it means that the graphic object or a the indicator graphic series will not be plotted. This constant was not included into the Web-color constants list, but it can be applied everywhere where the color arguments are required.

The INVALID_HANDLE constant can be used for a file handles check (see FileOpen() and FileFindFirst()).

Constant | Description | Value
CLR_NONE | Absence of color | -1
INVALID_HANDLE | Incorrect handle | -1
EMPTY_VALUE | Empty value in indicator buffer | DBL_MAX
NULL | Zero for any types | 0

The NULL constant can be assigned to a variable of any simple type or to the object structure or a class pointer. The NULL assignment for a string variable means the full deinitialization of this variable.

Example:

string label_name="invisible_label";
if(ObjectFind(0,label_name)<0)
{
Print("Object",label_name,"not found. Error code =",GetLastError());
//--- create object Label
ObjectCreate(0,label_name,OBJ_LABEL,0,0,0);
//--- set X coordinate
ObjectSetInteger(0,label_name,OBJPROP_XDISTANCE,200);
//--- set Y coordinate
ObjectSetInteger(0,label_name,OBJPROP_YDISTANCE,300);
//--- set text color
ObjectSetInteger(0,label_name,OBJPROP_COLOR,CLR_NONE);
}


Data structures

MQL5 Reference / Standard constants, enumerations and structures / Data structures

Data structures

MQL5 Language has 5 predefined structures:

· MqlDateTime to work with date and time;
· MqlRates to manipulate the historical data, it contains an information about the price, volume and spread;
· MqlBookInfo to obtain an information about the Price Glass (Market watch);
· MqlTradeRequest to create a trade request for trade operations;
· MqlTradeResult contain a trade server result for the trade request, sent by OrderSend() function;
· MqlTick designed for fast retrieval of the most requested information about current prices.


Structure of the date type

MQL5 Reference / Standard constants, enumerations and structures / Data structures / Structure of the date type

MqlDateTime

The date type structure contains an eight fields of the int type:

struct MqlDateTime
{
int year; // Year
int mon; // Month
int day; // Day
int hour; // Hour
int min; // Minutes
int sec; // Seconds
int day_of_week; // Day of week (0-sunday, 1-monday)
int day_of_year; // Day number of the year (for example, the 1st February is the 32nd day of the year)
};

Note

The day number of the year day_of_year for the leap year, since March, will differ from a number of corresponding day for a not leap year.

Example:

void OnStart()
{
//---
datetime date1=D'2008.03.01';
datetime date2=D'2009.03.01';

MqlDateTime str1,str2;
TimeToStruct(date1,str1);
TimeToStruct(date2,str2);
printf("%02d.%02d.%4d, day of year = %d",str1.day,str1.mon,
str1.year,str1.day_of_year);
printf("%02d.%02d.%4d, day of year = %d",str2.day,str2.mon,
str2.year,str2.day_of_year);
}
/* Result:
01.03.2008, day of year = 60
01.03.2009, day of year = 59
*/

See also

TimeToStruct, Structures and Classes


Structure of historical data

MQL5 Reference / Standard constants, enumerations and structures / Data structures / Structure of historical data

MqlRates

It is a structure to store an information about the prices, volumes and spread.

struct MqlRates
{
datetime time; // Start time
double open; // Open price
double high; // The highest price of the period
double low; // The lowest price of the period
double close; // Close price
long tick_volume; // Tick volume
int spread; // Spread
long volume; // Trade volume
};

Example:

void OnStart()
{
MqlRates rates[];
int copied=iRates(NULL,0,0,100,rates);
if(copied<=0)
Print("Price data copy error number: ",GetLastError());
else Print(" Total bars copied :",ArraySize(rates));
}

See also

CopyRates, An access to the time-series


Structure of the price glass

MQL5 Reference / Standard constants, enumerations and structures / Data structures / Structure of the DOM

MqlBookInfo

It provides an information about the price glass data, also known as a market depth data.

struct MqlBookInfo
{
uchar type; // Type
double price; // Price
long volume; // Volume
};

Note

The price glass is available only for some of the symbols. To use the structure MqlBookInfo, it is sufficient to declare a variable of the such type, so it is not necessary to specify it specially.

Example:

MqlBookInfo priceArray[];
bool getBook=MarketBookGet(NULL,priceArray);
if(getBook)
{
int size=ArraySize(priceArray);
Print("MarketBookInfo about ",Symbol());
}
else
{
Print("The price glass request has been failed for symbol ",Symbol());
}

See also

MarketBookAdd, MarketBookRelease, MarketBookGet, Data types


Structure of the trade request

MQL5 Reference / Standard constants, enumerations and structures / Data structures / Structure of the trade request

The structure of the trade request (MqlTradeRequest)

An interaction between the client terminal and trade server is performed by using the trade requests. The trade request is presented by the special predefined structure of MqlTradeRequest type, which contain all of the fields necessary to perform a trade deals. The trade request result is presented by the structure of MqlTradeResult type.

struct MqlTradeRequest
{
ENUM_TRADE_REQUEST_ACTIONS action; // Trade operation type
ulong magic; // Expert ID (magic mumber)
ulong order; // Order ticket
string symbol; // Trade symbol
double volume; // Requested volume for a deal in lots
double price; // Price
double stoplimit; // StopLimit price of the order
double sl; // Stop Loss price of the order
double tp; // Take Profit price of the order
ulong deviation; // Maximal possible deviation from the requested price
ENUM_ORDER_TYPE type; // Order type
ENUM_ORDER_TYPE_FILLING type_filling; // Order execution type
ENUM_ORDER_TYPE_TIME type_time; // Order execution time
datetime expiration; // Order expiration time (for the orders of ORDER_TIME_SPECIFIED type)
string comment; // Order comment
};

Fields description

Field | Description
action | Trade operation type. Can be one of the enumeration ENUM_TRADE_REQUEST_ACTIONS values.
magic | Expert ID. It allows traders to distinguish the trade operations of the different experts. An each expert can set its own unique ID for a trade request.
order | Order ticket. It is necessary for a pending orders modification.
symbol | Order symbol. It is not necessary for order modification and position close operations.
volume | Requested order volume in lots.Note that the real volume of the deal will depend on the order execution type.
price | The order execution price. For the market orders, which has TRADE_ACTION_DEAL type, the price definition is not necessary.
stoplimit | The price value which the StopLimit pending order will be placed (the price achievement to the stoplimit value is necessary, the pending order will be not placed until this condition).
sl | The Stop Loss price for the case of the unfavorable price movement
tp | Take Profit price for the case of the favorable price movement
deviation | The maximal price deviation, specified in points
type | Order type. Can be one of the enumeration ENUM_ORDER_TYPE values.
type_filling | Order execution type. Can be one of the enumeration ENUM_ORDER_TYPE_FILLING values.
type_time | Order execution type. Can be one of the enumeration ENUM_ORDER_TYPE_TIME values.
expiration | Order expiration time (for orders of ORDER_TIME_SPECIFIED type)
comment | Order comment

For the orders send to perform the trade operations it is necessary to use the function OrderSend(). For each trade operation it is necessary to specify the obligatory fields, the optional fields also may be filled. There are seven possible cases to send order:

Request Execution

Trade order to open position in the Request Execution mode (current prices request trade mode). It requires to specify the following 9 fields:

· action
· symbol
· volume
· price
· sl
· tp
· deviation
· type
· type_filling

Also it is possible to specify the "expert" and "comment" field values.

Instant Execution

Trade order to open position in the Instant Execution mode (streaming prices trade mode). It requires to specify the following 9 fields:

· action
· symbol
· volume
· price
· sl
· tp
· deviation
· type
· type_filling

Also it is possible to specify the "expert" and "comment" field values.

Market Execution

Trade order to open position in the Market Execution mode (market execution trade mode). It requires to specify the following 5 fields:

· action
· symbol
· volume
· type
· type_filling

Also it is possible to specify the "expert" and "comment" field values.

SL & TP Modification

Trade order to modify the StopLoss and/or TakeProfit price levels. It requires to specify the following 5 fields:

· action
· symbol
· sl
· tp
· deviation

Pending Order

Trade order to place a pending order. It requires to specify the following 11 fields:

· action
· symbol
· volume
· price
· stoplimit
· sl
· tp
· type
· type_filling
· type_time
· expiration

Also it is possible to specify the "expert" and "comment" field values.

Modify Pending Order

Trade order to modify the prices of the pending orders. It requires to specify the following 7 fields:

· action
· order
· price
· sl
· tp
· type_time
· expiration

Delete Pending Order

Trade order to delete the pending orders. It requires to specify the following 2 fields:

· action
· order

See also

Structures and Classes, Trade functions, Order properties


Structure of the trade result

MQL5 Reference / Standard constants, enumerations and structures / Data structures / Structure of the trade result

Structure of trade request result (MqlTradeResult)

As result of the trade request, the trade server returns data about the trade request in a special predefined structure of MqlTradeResult type.

struct MqlTradeResult
{
uint retcode; // Operation return code
ulong deal; // Deal ticket, if it has performed
ulong order; // Order ticket, if it has placed
double volume; // Deal volume, confirmed by broker
double price; // Deal price, confirmed by broker
double bid; // Current Bid price
double ask; // Current Ask price
string comment; // Broker comment to operation (by default it filled by the operation description)
};

Fields description

Field | Description
retcode | Return code of the trade server
deal | Deal ticket, if the deal has performed. It is available for a trade operation of TRADE_ACTION_DEAL type
order | Order ticket, if ticket has placed. It is available for a trade operation of TRADE_ACTION_PENDING type
volume | Deal volume, confirmed by broker. It dependent on the order filling type
price | Deal price, confirmed by broker. It dependent on the deviation field of the trade request and/or on the trade operation
bid | The current market Bid price
ask | The current market Ask price
comment | The broker comment to operation (by default it filled by the operation description)

The trade operation result returns to the variable of the MqlTradeResult type, which passed as a second parameter in a function OrderSend() to perform a trade operations.


MqlTick

MQL5 Reference / Standard constants, enumerations and structures / Data structures / Structure for current prices

Structure for current prices (MqlTick)

Structure for storing the latest prices on the symbol. Designed for fast retrieval of the most requested information about current prices.

struct MqlTick
{
datetime time; // Time of last update prices
double bid; // Current Bid price
double ask; // Current price Ask
double last; // Current price of the last transaction (Last)
ulong volume; // The volume for the current price Last
};

Variable type MqlTick allows a single function call SymbolInfoTick() to obtain values of Ask, Bid, Last and Volume.

Example:

void OnTick()
{
//---
Print(__FUNCTION__);
MqlTick last_tick;
bool res=SymbolInfoTick(Symbol(),last_tick);
if(res)
{
Print(last_tick.time,": Bid =",last_tick.bid,
" Ask =",last_tick.ask," Volume =",last_tick.volume);
}
else
{
Print("SymbolInfoTick() failed, error =",GetLastError());
}
}

See also

Structures and Classes


Codes of errors and warnings

MQL5 Reference / Standard constants, enumerations and structures / Codes of errors and warnings

Codes of errors and warnings

Section contains the following descriptions:

· Return codes of the trade server- Analysis of the results of sendingTrade Request sent function OrderSend();
· Compiler warnings- Codes of warning messages that appear when you compile (not an error);
· Compilation errors- Code error messages when an unsuccessful attempt to compile;
· Runtime errors- Error codes in the performance mql5-programs, which can be obtained using functionGetLastErtror().


Return codes of the trade server

MQL5 Reference / Standard constants, enumerations and structures / Codes of errors and warnings / Return codes of the trade server

Return codes of the trade server

Code | Constant | Description
10004 | TRADE_RETCODE_REQUOTE | Requotes
10006 | TRADE_RETCODE_REJECT | Request rejected
10007 | TRADE_RETCODE_CANCEL | Request canceled by trader
10008 | TRADE_RETCODE_PLACED | Order placed
10009 | TRADE_RETCODE_DONE | Order done
10010 | TRADE_RETCODE_DONE_PARTIAL | Order has been partially done
10011 | TRADE_RETCODE_ERROR | Error processing request
10012 | TRADE_RETCODE_TIMEOUT | Request canceled by timeout
10013 | TRADE_RETCODE_INVALID | Invalid request
10014 | TRADE_RETCODE_INVALID_VOLUME | Invalid volume in request
10015 | TRADE_RETCODE_INVALID_PRICE | Invalid price in request
10016 | TRADE_RETCODE_INVALID_STOPS | Invalid stops in request
10017 | TRADE_RETCODE_TRADE_DISABLED | Trade is disabled
10018 | TRADE_RETCODE_MARKET_CLOSED | Market closed
10019 | TRADE_RETCODE_NO_MONEY | There is not enough money to fulfill the request
10020 | TRADE_RETCODE_PRICE_CHANGED | Prices changed
10021 | TRADE_RETCODE_PRICE_OFF | There are no quotes for query processing
10022 | TRADE_RETCODE_INVALID_EXPIRATION | Invalid expiration date of the order in the request
10023 | TRADE_RETCODE_ORDER_CHANGED | Order condition changed
10024 | TRADE_RETCODE_TOO_MANY_REQUESTS | Too frequent requests


Compiler warnings

MQL5 Reference / Standard constants, enumerations and structures / Codes of errors and warnings / Compiler warnings

Compiler warnings

Compiler warnings are for informational purposes only and are not error messages.

Code | Description
21 | Incomplete record date in a string datetime
22 | Wrong number in the string datetime to date, requirements: Year 1970 <= X <= 3000 Month 0 <X <= 12 Day 0 <X <= 31/30/28 (29 )....
23 | Wrong number of line datetime, it should be: Hour 0 <= X <24 Minute 0 <= X <60
24 | Invalid color format RGB: one component RGB less than 0 or greater than 255
25 | Unknown character escapes sequences. Known: \ n \ r \ t \ \ \ "\ '\ X \ x
29 | Enumeration already defined (duplication) - Members will be added to the first definition
30 | Overriding macro
32 | Constructor must be of type void
33 | Destructor must be of type void
34 | Constant does not fit in the range of integers (X> _UI64_MAX | | X <_I64_MIN) and will be converted to type double
35 | Too long HEX more than 16 significant characters (cut senior nibble)
36 | Not a single nibble in HEX string "0x"
37 | There is no function - will have nothing to do
40 | Objects are passed by reference
41 | Function has our body but also not called
42 | Arrays are passed by reference
43 | Possible loss of data when converting types. Example: int x = (double) z;
44 | The loss of accuracy (data) when converting constant. Example: int x = M_PI
45 | The difference between the signs of operands in the operations of comparison. Example: (char) c1> (uchar) c2
46 | Problems with import functions - requires ad # import or the import functions is closed
47 | Description is too big - extra characters will not be included in the executable file
48 | The number of indicator buffers announced less than the required
49 | Not specified color for plot of indicator
50 | There is no plot of the indicator to draw
51 | Not detected function handler 'OnStart "in the script
52 | Function handler 'OnStart "is defined with wrong parameters
53 | Function 'OnStart' can only be defined in a script
54 | Function 'OnInit' is defined with wrong parameters
55 | Function 'OnInit' is not used in scripts
56 | Function 'OnDeinit' is defined with wrong parameters
57 | Function 'OnDeinit' is not used in scripts
58 | Identified two functions 'OnCalculate'. Be used OnCalculate () at a price array
59 | Scope # import finished implicitly (met variable declaration or function definition)


Compilation errors

MQL5 Reference / Standard constants, enumerations and structures / Codes of errors and warnings / Compilation errors

Compilation errors

MetaEdtior 5, editor mql5-programs, error messages the program detected a built-in compiler at compile.The list of these errors is given below in table.To compile the source code into an executable then F7. Program errors can not be compiled until the errors identified by the compiler, will not be eliminated.

Code | Description
100 | Error reading file
101 | *. EX5 Error opening file for writing to save
103 | It is not enough free memory to complete the compilation
104 | Unrecognized compiler empty syntactic unit
105 | Incorrect file name in # include
106 | Error accessing a file in # include (perhaps the file does not exist)
108 | Unfavorable name for # define
109 | Unknown command preprocessor (valid # include, # define, # property, # import)
110 | Unknown to the compiler symbol
111 | Function not implemented (description is present, body is absent)
112 | Omitted double quote ( ")
113 | Omitted opening angle bracket (<) or double quote ( ")
114 | Omitted single quote ( ')
115 | Omitted closing angle bracket ">"
116 | Not specified type of declaration
117 | There is no return statement or return is not available in all branches of the implementation
118 | It was expected opening bracket of call parameters
120 | Invalid access to an array
121 | The function has type void and the return statement must return a value
122 | Incorrect declaration of the destructor
123 | Missing colon ":"
124 | Variable is already declared
125 | Variable with the identifier is declared
126 | Variable name is too long (> 250 characters)
127 | Structure with the identifier is already defined
128 | The structure is not defined
129 | Member of the structure with the same name already defined
130 | No such structure member
131 | Breached pairing of brackets
132 | Expected opening parenthesis "("
133 | Unbalanced braces (no ")")
134 | It is difficult to compile (too much branching, internal levels of the stack is full)
135 | Error opening file for reading
136 | Not enough memory to download the source file in memory
137 | Expected variable
138 | Reference can not be initialized
140 | Expected assignment (if there is declaration)
141 | Expected opening brace "("
143 | Using a type of "void" is unacceptable
144 | No pair for ")" or "]", ie absent "(or" [ "
145 | No pair for "(or" [ ", ie no") "or"] "
146 | Incorrect array size
147 | Too many parameters (> 64)
149 | This token is not expected here
150 | Invalid use of operation (invalid operands)
151 | Expression of type void not allowed
152 | Expected operator
153 | Misuse break
154 | Expected a semicolon ";"
155 | Expected comma ","
157 | Expected expression
158 | In HEX found "not HEX character or too long number (number of digits> 511)
159 | String-constant has more than 65534 characters
160 | Function definition is unacceptable here
161 | Unexpected end of program
163 | Function with that name is already defined and has unlike return type
164 | Function with that name is already defined and has a different set of parameters
165 | Function with that name is already defined and implemented
166 | Overloading function for this call was not found
167 | Function with a return value type void can not return a value
168 | Function is not defined
170 | Expected value
171 | In terms of case are valid only integer constants
172 | The value for the case in this switch is used
173 | Expected integer
174 | In terms of # import is expected to file name
175 | The expressions on a global level is not allowed
176 | Omitted parenthesis ")" before ";"
177 | To the left of the equal sign is assumed variable
178 | The result of expression is not used
179 | Declaring variables in the case is inadmissible
180 | Implicit conversion from string to a number
181 | Implicit conversion of a string
182 | Ambiguous call to overloaded function (fit several overloads)
183 | Illegal else without proper if
184 | Invalid case or default without a switch
185 | Inappropriate use of ellipsis
186 | The initializing sequence has more elements than the variable is initialized
187 | Expected the constant for case
188 | Requires constant expression
189 | A const variable can not be changed
190 | Expected closing bracket or a comma (ad array member)
192 | Enumaeration can not have access modifiers (const, extern, static)
193 | Member of the enumeration is already declared with a different value
194 | There is a variable defined with the same name
195 | There is a structure defined with the same name
196 | Is expected to name a member of the enumeration
197 | Expected integer expression
198 | Division by zero in constant expression
199 | Wrong number of parameters in the function
200 | Parameter of the reference should be variable
201 | Expected variable of the same type to pass by reference
202 | A const variable can not be passed to a non-const reference
203 | Requires a positive integer constant
204 | Failed to access protected members of classes
205 | Imports already defined in another way
208 | The executable file is not created
209 | For indicator entry point not found 'OnCalculate'
210 | The continue statement can only be used inside the loop
211 | Failed to access private (closed), a member of the class
213 | Method of structure or class is not declared
214 | Failed to access private (closed) method of class
216 | Copying of structures with objects unacceptable
218 | Index out of range for the array
219 | An abusive initialize arrays in the structure declaration or a class
220 | Constructor can not have parameters
221 | Destructor can not have parameters
222 | Class method or structure with the same name and parameters have already been declared
223 | Expected operand
224 | Class method or structure with the same name exists, but with different parameters (declaration != implementation)
225 | Imported functions are not described
227 | Ambiguous call to overloaded function (exact match parameters for several overloads)
228 | Expected to variable name
229 | A reference can not be proclaimed in this place
230 | Already in use as the enumeration name
232 | Expected class or structure
235 | Can not call operator 'delete' to delete the array
236 | Expected operator ' while'
237 | In the operator 'delete' must be a pointer
238 | Operator 'default' for this 'switch' is already
239 | Syntax error
240 | Escape-sequence can occur only in lines (starts with '\')
241 | Requires array - square bracket '[' does not apply to an array or an array parameter serves an array
242 | Can not be initialized through the initialization sequence
243 | Import is not defined
244 | Optimizer error on the syntactic tree
245 | Declared too many structures (try to simplify program)
246 | Conversion of parameter is unacceptable
247 | Incorrect use of the 'delete' operator
248 | You can not declare a pointer to a link
249 | It's not allowed to declare a reference to a reference
250 | It's not allowed to declare a pointer to a pointer
251 | Unacceptable structure declaration in the parameter list
252 | Invalid operation casts
253 | The pointer can be declared only for the class or structure
255 | Forward-definition is not supported
256 | Undeclared identifier
257 | Error during optimization of executable code
258 | Error during generating of executable code
259 | Too large amount of local variables (> 512K) function, reduce the number
260 | Invalid expression for the operator 'switch'
261 | Buffer pool string constants, simplify program
262 | Can not convert to enumeration
263 | Do not use 'virtual' for data (members of the class or structure)
264 | Can not call protected method of class
265 | Virtual functions returns a different type
266 | The class can not be inherited from a structure
267 | The structure can not be inherited from a class
268 | Constructor can not be virtual (virtual specifier is not allowed)
269 | The structure can not have virtual methods
270 | Missed a virtual method
271 | Overloading of system function (terminal) is prohibited
272 | Const specifier is invalid for functions that are not a member of the class or structure
273 | You can not use const for the data (the members of the class or structure)
274 | Can not change the class members in constant method
275 | You can not declare more than 64 input parameters (input-variables)
276 | Unsuitable initialization sequence
277 | Missed default value for the parameter (specificity announcements default settings)
278 | Overriding the default setting (in the declaration and implementation of different values)
279 | We can not call non-const method for constant object
280 | To access the members want an object (set point for no class / structure)
281 | The name already declared the structure can not be used when declaring
282 | The name of the structure can not be used as the name of a class member
283 | Incorrect type or a combination of parameters for the entry-point 'OnCalculate'
284 | Unauthorized conversion (with private inheritance)
285 | Structures and arrays can not be used as input-variables
286 | Const specifier is not valid for the constructor/destructor
287 | Incorrect string expression to a datetime
288 | Unknown property (# property)
289 | Incorrect value for the property
290 | Invalid index for properties in the # property
291 | Missing a call option - <func (x,)>


Runtime errors

MQL5 Reference / Standard constants, enumerations and structures / Codes of errors and warnings / Runtime errors

Runtime errors

GetLastError()- A function that returns the last error code that is stored in the predefined variable_LastError. This value can be reset to zero by function ResetLastError().

Constant | Code | Description
ERR_INTERNAL | 4001 | Unexpected internal error
ERR_WRONG_PARAMETER | 4002 | Wrong parameter in the inner call to the client terminal
ERR_INVALID_PARAMETER | 4003 | Wrong parameter when calling the system function
ERR_NOT_ENOUGH_MEMORY | 4004 | Not enough memory to perform the system function
ERR_STRUCT_WITHOBJECTS_ORCLASS | 4005 | The structure contains objects of rows and/or dynamic arrays and/or structure of such objects and/or classes
ERR_INVALID_ARRAY | 4006 | Array wrong type, wrong size or damaged object dynamic array
ERR_ARRAY_RESIZE_ERROR | 4007 | Not enough memory for the relocation of an array or an attempt to change the size of a static array
ERR_STRING_RESIZE_ERROR | 4008 | Not enough memory for the relocation of string
ERR_NOTINITIALIZED_STRING | 4009 | Uninitialized string
ERR_INVALID_DATETIME | 4010 | Invalid date and/or time
ERR_ARRAY_BAD_SIZE | 4011 | Requested array size exceeds 2 GB
ERR_INVALID_POINTER | 4012 | Wrong pointer
ERR_INVALID_POINTER_TYPE | 4013 | Wrong type of pointer
ERR_FUNCTION_NOT_ALLOWED | 4014 | System function is not allowed to call
Charts |  |
ERR_CHART_WRONG_ID | 4101 | Wrong chart ID
ERR_CHART_NO_REPLY | 4102 | Chart does not answer
ERR_CHART_NOT_FOUND | 4103 | Chart not found
ERR_CHART_NO_EXPERT | 4104 | There is no chart expert, who could handle an event
ERR_CHART_CANNOT_OPEN | 4105 | Error opening chart
ERR_CHART_CANNOT_CHANGE | 4106 | Failed to change a chart symbol and the period
ERR_CHART_WRONG_TIMER_PARAMETER | 4107 | Wrong parameter for timer
ERR_CHART_CANNOT_CREATE_TIMER | 4108 | Failed to create timer
ERR_CHART_WRONG_PROPERTY | 4109 | Wrong chart property ID
ERR_CHART_SCREENSHOT_FAILED | 4110 | Error creating screenshots
ERR_CHART_NAVIGATE_FAILED | 4111 | Error navigation charts
ERR_CHART_TEMPLATE_FAILED | 4112 | Error creating tempalte
Graphic objects |  |
ERR_OBJECT_ERROR | 4201 | Error working with a graphic object
ERR_OBJECT_NOT_FOUND | 4202 | Graphic Object Not Found
ERR_OBJECT_WRONG_PROPERTY | 4203 | Wrong ID features graphic
ERR_OBJECT_GETDATE_FAILED | 4204 | Unable to get date corresponding to the value
ERR_OBJECT_GETVALUE_FAILED | 4205 | Unable to get the value corresponding to the date
MarketInfo |  |
ERR_MARKET_UNKNOWN_SYMBOL | 4301 | Unknown symbol
ERR_MARKET_SELECT_ERROR | 4302 | Symbol is not selected in MarketWatch
ERR_MARKET_WRONG_PROPERTY | 4303 | Wrong identifier properties of the symbol
ERR_MARKET_LASTTIME_UNKNOWN | 4304 | Time of the last tick is not known (no ticks)
Access to history |  |
ERR_HISTORY_NOT_FOUND | 4401 | Asking story not found
ERR_HISTORY_WRONG_PROPERTY | 4402 | Wrong property ID of the data history
Global_Variables |  |
ERR_GLOBALVARIABLE_NOT_FOUND | 4501 | Global variable client terminal is not found
ERR_GLOBALVARIABLE_EXISTS | 4502 | Global variable client terminal with the same name already exists
ERR_MAIL_SEND_FAILED | 4510 | Email sending failed
ERR_PLAY_SOUND_FAILED | 4511 | Sound playing failed
ERR_MQL5_WRONG_PROPERTY | 4512 | Wrong MQL5 property ID for #property
ERR_TERMINAL_WRONG_PROPERTY | 4513 | Wrong terminal property ID
ERR_FTP_SEND_FAILED | 4514 | Sending a file via ftp failed
Buffer custom indicators |  |
ERR_BUFFERS_NO_MEMORY | 4601 | Not enough memory for the distribution of indicator buffers
ERR_BUFFERS_WRONG_INDEX | 4602 | Wrong index of own indicator buffer
Properties custom indicators |  |
ERR_CUSTOM_WRONG_PROPERTY | 4603 | Wrong custom indicator property ID
Account |  |
ERR_ACCOUNT_WRONG_PROPERTY | 4701 | Wrong account property ID
ERR_TRADE_WRONG_PROPERTY | 4751 | Wrong trade property ID
ERR_TRADE_DISABLED | 4752 | Trading through expert prohibited
ERR_TRADE_POSITION_NOT_FOUND | 4753 | Position not found
ERR_TRADE_ORDER_NOT_FOUND | 4754 | Order not found
ERR_TRADE_DEAL_NOT_FOUND | 4755 | Deal not found
ERR_TRADE_SEND_FAILED | 4756 | Trade request failed
ERR_TRADE_SELECT_TIMEOUT | 4757 | Exceeding a timeout in the selection (searching) of specified data
Indicators |  |
ERR_INDICATOR_UNKNOWN_SYMBOL | 4801 | Unknown symbol
ERR_INDICATOR_CANNOT_CREATE | 4802 | The indicator can not be called
ERR_INDICATOR_NO_MEMORY | 4803 | Not enough memory to add the indicator
ERR_INDICATOR_CANNOT_APPLY | 4804 | The indicator can not be applied to other indicator
ERR_INDICATOR_CANNOT_ADD | 4805 | Error applying an indicator to chart
ERR_INDICATOR_DATA_NOT_FOUND | 4806 | Requested data not found
ERR_INDICATOR_WRONG_INDEX | 4807 | Wrong index of the requested indicator buffer
Glass prices |  |
ERR_BOOKS_CANNOT_ADD | 4901 | Depth Of Market can not be added
ERR_BOOKS_CANNOT_DELETE | 4902 | Depth Of Market can not be removed
ERR_BOOKS_CANNOT_GET | 4903 | The data from Depth Of Market can not be obtained
ERR_BOOKS_CANNOT_SUBSCRIBE | 4904 | Error in subscribing to receive new data from Depth Of Market
File operations |  |
ERR_TOO_MANY_FILES | 5001 | Can not be opened simultaneously for more than 64 files
ERR_WRONG_FILENAME | 5002 | Invalid filename
ERR_TOO_LONG_FILENAME | 5003 | Too long file name
ERR_CANNOT_OPEN_FILE | 5004 | Error opening file
ERR_FILE_CACHEBUFFER_ERROR | 5005 | Not enough memory for cache to read
ERR_CANNOT_DELETE_FILE | 5006 | Error deleting file
ERR_INVALID_FILEHANDLE | 5007 | A file with this handle to have been closed or not opening at all
ERR_WRONG_FILEHANDLE | 5008 | Wrong file handle
ERR_FILE_NOTTOWRITE | 5009 | The file should be opened for writing
ERR_FILE_NOTTOREAD | 5010 | The file should be opened for reading
ERR_FILE_NOTBIN | 5011 | The file should be opened as a binary
ERR_FILE_NOTTXT | 5012 | The file should be opened as a text
ERR_FILE_NOTTXTORCSV | 5013 | The file should be opened as a text or CSV
ERR_FILE_NOTCSV | 5014 | The file should be opened as CSV
ERR_FILE_READERROR | 5015 | Error reading file
ERR_FILE_BINSTRINGSIZE | 5016 | Should be given size of the string, because the file is opened as a binary
ERR_INCOMPATIBLE_FILE | 5017 | For string arrays should be a text file, for the other - a binary
ERR_FILE_IS_DIRECTORY | 5018 | This is not a file and directory
ERR_FILE_NOT_EXIST | 5019 | File does not exist
ERR_FILE_CANNOT_REWRITE | 5020 | File can not be rewritten
ERR_WRONG_DIRECTORYNAME | 5021 | Mistaken directory name
ERR_DIRECTORY_NOT_EXIST | 5022 | The directory does not exist
ERR_FILE_ISNOT_DIRECTORY | 5023 | This is a file and not directory
ERR_CANNOT_DELETE_DIRECTORY | 5024 | The directory can not be removed
String conversion |  |
ERR_NO_STRING_DATE | 5030 | There is no date in string string
ERR_WRONG_STRING_DATE | 5031 | The erroneous date in the string
ERR_WRONG_STRING_TIME | 5032 | The wrong time in the string
ERR_STRING_TIME_ERROR | 5033 | Error converting string to date
ERR_STRING_OUT_OF_MEMORY | 5034 | Not enough memory for the string
ERR_STRING_SMALL_LEN | 5035 | The string length is less than expected
ERR_STRING_TOO_BIGNUMBER | 5036 | Too many, more than ULONG_MAX
ERR_WRONG_FORMATSTRING | 5037 | Invalid format string
ERR_TOO_MANY_FORMATTERS | 5038 | Amount of format specifiers more than the parameters
ERR_TOO_MANY_PARAMETERS | 5039 | Amount of parameters more than the format specifiers
ERR_WRONG_STRING_PARAMETER | 5040 | Spoiled parameter of type string
ERR_STRINGPOS_OUTOFRANGE | 5041 | Position outside the string
ERR_STRING_ZEROADDED | 5042 | By the end of the string added to 0, a useless operation
ERR_STRING_UNKNOWNTYPE | 5043 | Unknown data type when converting to a string
ERR_WRONG_STRING_OBJECT | 5044 | Spoiled string object
Working with Arrays |  |
ERR_INCOMPATIBLE_ARRAYS | 5050 | Copying incompatible arrays. String array can be copied only in string and numeric array - in numerical
ERR_SMALL_ASSERIES_ARRAY | 5051 | The receiving array is declared as AS_SERIES, and it is insufficient size
ERR_SMALL_ARRAY | 5052 | Too small array, the starting position outside the array
ERR_ZEROSIZE_ARRAY | 5053 | An array of zero length
ERR_NUMBER_ARRAYS_ONLY | 5054 | Must be a numeric array
ERR_ONEDIM_ARRAYS_ONLY | 5055 | Must be a one-dimensional array
ERR_SERIES_ARRAY | 5056 | Timeseries can not be used
ERR_DOUBLE_ARRAY_ONLY | 5057 | Should be an array of type double
ERR_FLOAT_ARRAY_ONLY | 5058 | Should be an array of float
ERR_LONG_ARRAY_ONLY | 5059 | Should be an array of float
ERR_INT_ARRAY_ONLY | 5060 | Should be an array of type int
ERR_SHORT_ARRAY_ONLY | 5061 | Should be an array of short
ERR_CHAR_ARRAY_ONLY | 5062 | Should be an array of type char
User error |  |
ERR_USER_ERROR_FIRST | 65536 | With this number start errors defined by user


In/out constants

MQL5 Reference / Standard constants, enumerations and structures / In/out constants

Input and output constants

Constants:

· File opening flags
· File position
· MessageBox


File opening flags

MQL5 Reference / Standard constants, enumerations and structures / In/out constants / File opening flags

File opening flags

These file opening flag values specify the file access mode. Flags are defined as follows:

Identified | Description
FILE_READ | File open for read
FILE_WRITE | File open for write
FILE_BIN | Binary mode access for read/write (without use of the strings)
FILE_CSV | CSV file (all its elements are converted to strings of the appropriate type, unicode or ansi and separated by separator)
FILE_TXT | The simple text file (as csv file, but without taking into account of the separators)
FILE_ANSI | Strings of ANSI type (one byte symbols)
FILE_UNICODE | Strings of UNICODE type (two byte symbols)
FILE_SHARE_READ | Shared access for read from the several programs
FILE_SHARE_WRITE | Shared access for write from the several programs
FILE_REWRITE | Possibility for the file rewrite with the functions FileCopy and FileMove. The file should exist or open for write overwise file will not be opened.
FILE_COMMON | The file path in the common folder for all of the client terminals


File position

MQL5 Reference / Standard constants, enumerations and structures / In/out constants / File position

Positioning within a file

ENUM_FILE_POSITION

Id | Description
SEEK_SET | Begin position
SEEK_CUR | Current position
SEEK_END | End position


Constants windows MessageBox

MQL5 Reference / Standard constants, enumerations and structures / In/out constants / MessageBox

MessageBox dialog window constants

This section contains the MessageBox() function return codes. If a message window has a Cancel button, the function returns IDCANCEL in the case if ESC or Cancel button has been pressed. If the window message hasn't a Cancel button, ESC press does not gives any effect.

Constant | Value | Description
IDOK | 1 | "OK" button has been pressed
IDCANCEL | 2 | "Cancel" button has been pressed
IDABORT | 3 | "Abort" button has been pressed
IDRETRY | 4 | "Retry" button has been pressed
IDIGNORE | 5 | "Ignore" button has been pressed
IDYES | 6 | "Yes" button has been pressed
IDNO | 7 | "No" button has been pressed
IDTRYAGAIN | 10 | "Try Again" button has been pressed
IDCONTINUE | 11 | "Continue" button has been pressed

The main flags of the MessageBox() function defines contents and behavior of the dialog window. This value can be a combination of the following flag groups:
Constant | Value | Description
MB_OK | 0x00000000 | Message window contain only one button: OK. Default
MB_OKCANCEL | 0x00000001 | Message window contain two buttons: OK and Cancel
MB_ABORTRETRYIGNORE | 0x00000002 | Message window contain three buttons: Abort, Retry and Ignore
MB_YESNOCANCEL | 0x00000003 | Message window contain three buttons: Yes, No and Cancel
MB_YESNO | 0x00000004 | Message window contain two buttons: Yes and No
MB_RETRYCANCEL | 0x00000005 | Message window contain two buttons: Retry and Cancel
MB_CANCELTRYCONTINUE | 0x00000006 | Message window contain three buttons: Cancel, Try Again, Continue

To display an icon in the message window it is necessary to specify an additional flags:

Constant | Value | Description
MB_ICONSTOP, MB_ICONERROR, MB_ICONHAND | 0x00000010 | The STOP sign icon
MB_ICONQUESTION | 0x00000020 | The question sign icon
MB_ICONEXCLAMATION, MB_ICONWARNING | 0x00000030 | The exclamation/warning sign icon
MB_ICONINFORMATION, MB_ICONASTERISK | 0x00000040 | The Asterisk sign icon

The default buttons are defined by the following flags:

Constant | Value | Description
MB_DEFBUTTON1 | 0x00000000 | The first button MB_DEFBUTTON1 - is default, if the other buttons MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 are not specified
MB_DEFBUTTON2 | 0x00000100 | The second button is default
MB_DEFBUTTON3 | 0x00000200 | The third button is default
MB_DEFBUTTON4 | 0x00000300 | The fourth button is default


MQL5 programs

MQL5 Reference / MQL5 programs

MQL5 Programs

For the mql5-program execution it should be compiled (button "Compile" or F7 key). Compilation should pass without errors (maybe some warnings which are necessary to analyse). Thus in a corresponding directory, terminal_dir\MQL5\Experts, terminal_dir\MQL5\indicators or terminal_dir\MQL5\scripts, the out file with the same name and EX5 extension should be created. This file can be executed.

The features of mql5 programs are described in sections:

· Program running- About the order of predefined event-handlers calls;
· Client terminal events- For the description of events, which could be processed in programs
· Imported functions call- Contain an information about the the description order, possible parameters, search details and call agreement for the imported functions;
· The order of description, the permissible parameters, the search order and the agreement on the links imported functions
· Runtime errors- Contains an information about runtime and critical errors.

Experts, custom indicators and scripts are attaching to the one of the opened charts by the mouse "drag and drop" on the corresponding chart from the Navigator window of the client terminal (Drag'n'Drop technology).

To stop the expert work, it is necessary to delete it from the chart by using the "Advisors - Delete" from the chart context menu. The work of the advisor is also influenced by the state of the expert advisors option of the client terminal (Button "Allow or prohibit AutoTrading")

To stop the expert advisor it is necessary to delete it from the chart.

Custom indicators and advisors are working until deattaching from the chart; an information about the advisors and custom indicators attached are saved between the client terminal runs.

Scripts are runs one time and deletes automatically on end of their work or on closing or change of a condition of the current chart, or on the client terminal close. At restart of the client terminal scripts are not started, because the information on them does not saved.

On the one chart could be a one expert and script and an unlimited number of indicators.


Programs running

MQL5 Reference / MQL5 programs / Program running

Programs running

Immediately after attaching the program to the chart it is loading into the memory of the client terminal and performs an initialization of global variables. If some global variable of the class-type has a constructor, it will be called during the initialization of the global variables.

After that the program is waiting for the events from the client terminal. An each of the mql5-program should has at least one of the event-handler, overwise the loaded program will not executed. The event handlers has a predefined set of names, parameters and return types.

Type | Function name | Parameters | Application | Comment
int | OnInit | none | experts and indicators | Init event handler. It allows to use the void return type.
void | OnDeinit | const int reason | experts and indicators | Deinit event handler.
void | OnStart | none | scripts | Start event handler.
int | OnCalculate | const int rates_total, const int prev_calculated, const datetime &Time[], const double &Open[], const double &High[], const double &Low[], const double &Close[], const long &TickVolume[], const long &Volume[], const int &Spread[] | indicators | Calculate event handler for all prices.
int | OnCalculate | const int rates_total, const int prev_calculated, const int begin, const double &price[] | indicators | Calculate event handler on the single data array. Indicator could not has a two event handlers simultaneously. In such case the only one event handler will work on the data array.
void | OnTick | none | experts | NewTick event handler. During the time of the new tick event processing, there is no other events of this type.
void | OnTimer | none | experts | Timer event handler.
void | OnTrade | none | experts | Trade event handler.
void | OnChartEvent | const int id, const long &lparam, const double &dparam, const string &sparam | experts | ChartEvent event handler.
void | OnBookEvent | const string &symbol_name | experts | BookEvent event handler.

Client terminal adds to the events queue all of the events arising. So the events are processed one after another in order of receipt. There is an exception for the NewTick event. If the queue already has an event or such event is in the process, the new NewTick event is not adding to the events queue.

Queue of events is limited in size. At queue overflow case the old events are removed without processing in order to allow for new incoming events. Therefore, it is recommended to write an efficient event handlers, and not recommended to use an infinite loops (there is an exception of scripts, which handle a single event Start only).

Events are adding to the expert events queue only if experts are allowed in the client terminal.

Libraries does not handle any events.

Loading and unloading of indicators

Indicators are loaded in the following cases:

· attaching an indicator to the chart;
· launch the terminal (if the indicator was attached to the chart prior to the closure of the terminal);
· download the template (if specified in the template attached to the graphics display);
· change the profile (if the indicator is attached to one of the graphs profile);
· change character and / or time schedule, is attached to the indicator;
· after the successful recompilation of the indicator if the indicator was attached to the chart;
· change input parameters of the indicator.

Indicators are unloaded in the following cases:

· when detaching an indicator of the graph;
· closure of the terminal (if the indicator was attached to the chart);
· download the template, if the schedule is attached to the indicator;
· closure chart, to which was attached to the indicator;
· change the profile, if the indicator is attached to one of the charts are subject to recall your profile;
· change character and / or time schedule, is attached to the indicator;
· change input parameters of the indicator.

Loading and unloading of the experts

Expert loading is performed in the following cases:

· expert attaching to the chart;
· terminal run (if expert has been attached before the previous terminal close);
· template loading (if template has an expert attached to the chart);
· profile change (if expert attached to the one of profile charts).

Expert unloading attached to the chart is performed in the following cases:

· in the case of expert deattaching from the chart;
· during the new expert attaching to the chart, if there another expert has been attached already, an old expert unloads.
· terminal close (if expert has been attached to the chart);
· template load, if chart has an attached expert;
· chart close with the expert attached.
· profile change, if expert has been attached to the one of the new profile charts

In the case of the symbol or a timeframe changes on the expert's chart, experts unload and load does not perform. In such case client terminal subsequently executes the handler functions OnDeinit() on the old symbol/timeframe and OnInit() on the new symbol/timeframe (if they are exist),

the values of the global variables and static variables are not reset. All events, which have been received for expert are skipped until the initialization (OnInit() function) complete.

In the cases of the account change, expert load and unload does not perform.

Loading and unloading scripts

Scripts are loaded immediately after attaching to the chart and unloaded immediately after the end of their work. This function OnInit () and OnDeinit () for scripts are not called.

After the program unload (delete from the chart) the client terminal performs the deinitialization of the global variables and deletes the events queue. In such case the deinitialization means the reset of all of the string type variables, deallocation of the object's dynamical arrays and calls of their destructors if they are exist.

For better understanding the expert work we recommend to compile the code of the following expert and perform the actions to load/unload the experts, template change, symbol change, timeframe change etc:

Value of double type.

Example:

//+------------------------------------------------------------------+
//| TestExpert.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"

class CTestClass
{
public:
CTestClass() { Print("CTestClass constructor"); }
~CTestClass() { Print("CTestClass destructor"); }
};
CTestClass global;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
Print("Initialisation");
//---
return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print("Deinitialisation with reason",reason);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---

}
//+------------------------------------------------------------------+

See also

Events client terminal, Event handler function


Client terminal events

MQL5 Reference / MQL5 programs / Client terminal events

Client terminal events

Init

Immediately after the client terminal will load the program (expert or custom indicator) and start the process of initializing the global variables, an Init event will be sent, which will be processed by OnInit() event handler, if it exist. This event is also generated after the change of the financial instrument and/or timeframe of the chart, after recompiling the program in MetaEditor, after changing of the input parameters from the expert settings or custom indicator window. Expert advisor also initializes after the account change. The Init event does not generated for scripts.

Deinit

Before deinitialization of the global variables and the program unload (expert or custom indicator), the client terminal sends a program the Deinitevent. Deinit event is also generated when you close the client terminal, at the close of the chart, immediately before the change of the financial instrument and / or time chart, after the successful program recompile, by changing the input parameters, as well as by changing the account.

The deinitialization reason can be obtained from the parameter, passed to the function OnDeinit(). The OnDeinit() function run is restricted to 2.5 seconds. If during this time, the function hasn't been completed, then it is forcibly terminated. The Deinit event does not generated for scripts.

Start

The Start event is a special event for a script activization after its load. This event processed by OnStart handler. The Start event does not send to experts and custom indicators.

NewTick

The NewTick event is generated if there are new quotes and processed by function OnTick() of the experts attached. In case when OnTick function is still processing for the old quote, the new quote will be ignored by expert, because the corresponding event will not be put in the expert events queue.

All of the new quotes are coming are ignored by program until the OnTick() complete. After that function will run only after the new quote. The NewTick event does not generated if expert advisors option of the client terminal are not allowed (Button "Allow or prohibit AutoTrading").

However, the expert advisor disable by pressing the specified button does not interrupt the execution of the function OnTick (). Function OnTick () is not started when the advisor properties is open. The advisor properties window cannot be opened during the expert run.

Calculate

The Calculate event is generated only for the indicators immediately after sending the Init event and any change of the price data. It is processed by function OnCalculate.

Timer

The Timer event periodically generated by the client terminal for the expert, who has activated the timer by EventSetTimer. Usually, this function is called by the OnInit function. Timer events processing is performed by OnTimer function. After the expert finish, it is necessary to to destroy the timer by using the function EventKillTimer, it usually call in the OnDeinit function.

Trade

Trade Event is generated when the end of trading on the trading server. Trading:

· installation, modification or removal of a pending order;
· cancellation of a pending order with a shortage of funds or expiration;
· activation pending order;
· opening, adding or close a position (or part of the position);
· modification of the open position (change stops).
ChartEvent

The ChartEvent event is generated by the client terminal during the user operations with chart:

· keyboard press, when the chart window in focus;
· mouse press on the graphic object of the chart;
· move of the graphic object using the mouse
· end of the text edit in LabelEdit input of the graphic object.

Also there is a custom event ChartEvent, which could be send to expert by any mql5-program by using the function EventChartCustom. The event is processed by the function OnChartEvent.

BookEvent

The BookEvent event is generated by the client terminal after the price glass change and processed by function OnBookEvent. To start generation of BookEvent event for the specified symbol, it is necessary to subscribe the symbol to this event by using the function MarketBookAdd.

To unsubscribe from the BookEvent event for a specified symbol, it is necessary to call the function MarketBookRelease. The BookEvent event is a broadcasting-type event - it means that it is sufficient to subscribe just one expert for it's generating, and all other experts which has an OnBookEvent event, will receive it. That's why it is necessary to analyse the symbol name, which passed in the handler as parameter.

See also

Event handler function, Running programs


Imported functions call

MQL5 Reference / MQL5 programs / Imported functions call

Imported functions call

To import functions during mql5-program execution the client terminal uses an early binding. This means that if the program has call of the imported functions, the corresponding module (ex5 or dll) is loaded during the program load. MQL5 and DLL libraries are executed in it's calling thread.

It is not recommended to use the fully specified name of the module to be loaded like Drive:\Directory\FileName.Ext. The MQL5 libraries are loaded from the terminal_dir\MQL5\Libraries folder. If the library hasn't been found, then the client terminal performs an attempt to load it from terminal_dir\experts folder.

The system libraries (DLL) are loaded by the operating system rules. If the library is already loaded (for example, another expert, and even from another client terminal, running in parallel), then it uses requests to the library already loaded. Otherwise, it performs a search in the following sequence:

1. Directory terminal_dir\Libraries.

2. Client terminal directory terminal_dir.

3. The current directory.

4. The system directory windows_dir\SYSTEM32

5. The operating system directory windows_dir.

6. Directories, listed in the PATH system environment variable.

If the DLL library uses an another DLL during his work, the first cannot be loaded in the case of the second DLL absence.

Unlike system libraries the user libraries (MQL5) are loaded for each module separately irrespective of, whether the caused library has been loaded by any other module. For example, the module caller.ex5 calls the functions from the library lib1.ex5 and lib2.ex5. In turn, the library lib1.ex5 calls the functions from the library lib2.ex5. In this case one copy of library lib1.ex5 and two copies of library lib2.ex5 will be loaded, despite of the fact that all calls starts from the caller.ex5.

The imported functions from the DLL in mql5-program must ensure the Windows API calls agreement.

To ensure such an agreement in the source text of programs, written in C or C++, use the keyword __stdcall, which is specific to the compilers of the company's Microsoft (r).

The agreement is characterized as follows:.

Â · Caller (in our case mq5-program) should "see" a prototype called (imported from the DLL) functions, in order to properly combine the parameters to the stack;

Â · Caller (in our case mql5-program) puts the parameters to the stack in reverse order, from left to right - in that order imported function reads the parameters passed to it;

Â · Parameters are passed by value, except those explicitly passed by reference (in our case lines)

Â · Imported functions by reading the parameters passed to it, cleans the stack independently.

In describing the prototype of the imported function it is possible to use the default parameters.

If the corresponding library was unable to load, or there was a prohibition on the DLL use, either imported function hasn't been found - the expert stops its work with the appropriate message "expert stopped" in the Journal (log file). Thus the expert will not run until you reinitialize it. The expert may be reinitialized as a result of recompile or after the opening of its properties and clicking OK.


Runtime errors

MQL5 Reference / MQL5 programs / Runtime errors

Runtime errors

The execution subsystem has an opportunity to save the error code in the case of its occurrence during the mql5-program run. For each of the executable mql5-program there is a predefined variable _LastError.

Before starting the function OnInit the _LastError variable reset. In the case of the erroneous situations during the calculation or in the process of internal function calls, the variable _LastError has an error code. The value stored in this variable can be obtained by using the GetLastError() function.

There are several critical errors at which occurrence the program interrupts immediately :

· division by zero;
· going beyond the array ranges;
· using the incorrect object pointer;


Predefined variables

MQL5 Reference / Predefined variables

The predefined variables

For each mql5-program there are the several predefined variables are available, which contains an information about the current state of the price chart at the mql5-program run, as expert, script or a custom indicator.

The values of predefined variables are set by the client terminal before the mql5-program run. The predefined variables are constant and cannot be changed from the mql5-program. As exception, there is a special variable _LastError, which can be set to 0 by function ResetLastError.

Variable | Value
_Digits | Decimal digits count
_Point | Point size of the current symbol in the quote currency
_LastError | The last error code
_Period | Timeframe of the current chart
_StopFlag | Program stop flag
_Symbol | Symbol name of the current chart
_UninitReason | Deinitialization reason code

The libraries are used the variable values of the program called.


_Digits

MQL5 Reference / Predefined variables / _Digits

int _Digits

The variable _Digits contains the decimal digits count, which correspond to the price accuracy of the symbol of the current chart.

Also you may use the function Digits().


_Point

MQL5 Reference / Predefined variables / _Point

int _Point

The _Point variable contains a point size of the current symbol in the currency quote values.

Also you may use the function Point().


_LastError

MQL5 Reference / Predefined variables / _LastError

int _LastError

The _LastError variable contains code of the last error, during the mql5-program run. It is possible to reset its value to zero by using the function ResetLastError().

To obtain the code of the last error, you may also use the function GetLastError().


_Period

MQL5 Reference / Predefined variables / _Period

int _Period

The _Period variable contains a timeframe value for the current chart.

Also you may use the function Period().


_StopFlag

MQL5 Reference / Predefined variables / _StopFlag

bool _StopFlag

The _StopFlag variable contain a flag of the mql5-program run. When the client terminal is trying to stop the program, it sets the _StopFlag variable to true.

To check the state of the _StopFlag you may use the function IsStopped.


_Symbol

MQL5 Reference / Predefined variables / _Symbol

string _Symbol

The _Symbol variable contains a symbol name of the current chart.

You may also use the function Symbol().


_UninitReason

MQL5 Reference / Predefined variables / _UninitReason

int _UninitReason

The _UninitReason variable contains the code of the deinitialization reason of the program.

Usually, this code obtained by function UninitializeReason().


Common Functions

MQL5 Reference / Common Functions

Common Functions

General-purpose functions not included into any specialized group are listed here.

Function | Action
CheckPointer | Checks correctness of a pointer at an object
Comment | Outputs a comment in the left top corner of the chart
DebugBreak | Program breakpoint in debugging
GetTickCount | Returns the number of milliseconds that have elapsed since the system was started
MessageBox | Creates, displays a message box and manages it
PeriodSeconds | Returns the number of seconds in the period
PlaySound | Plays a sound file
Print | Displays a message in the log
PrintFormat | Formats and prints the sets of symbols and values in a log file in accordance with a preset format
ResetLastError | Sets the value of a predetermined variable _LastError to zero
SendFTP | Sends a file at the address specified in the settings window of the "Publisher" tab
SendMail | Sends an email at the address specified in the settings window of the "Mailbox" tab
Sleep | Suspends execution of the current Expert Advisor or script within a specified interval
ZeroMemory | Resets variable passed by reference. Variable type can be any, with the exception of only the classes and structures that have constructors.


CheckPointer

MQL5 Reference / Common Functions / CheckPointer

CheckPointer

This function checks correctness of a pointer at an object.

bool CheckPointer(
object *anyobject // pointer at an object
);

Parameters

anyobject

[in] Pointer at an object created using the new operator that need to be checked.

Returned Value

Returns 'true', if the pointer is correct. Otherwise returns 'false'.

Note

A pointer can be incorrect in the following cases:

· pointer is equal to NULL;
· is a pointer hasn't been obtained using the 'new' operator;
· if the object has been deleted using the delete operator.

Attempt to call an incorrect pointer leads to the critical completion of a program. That's why the CheckPointer function must be used before pointer.


Comment

MQL5 Reference / Common Functions / Comment

Comment

This function outputs a comment defined by a user in the top left corner of a chart.

void Comment(
argument, // first value
... // next values
);

Parameters

...

[in] Any values, separated by commas. To delimit output information into several lines, a line break symbol "\n" or "\r\n" is used. Number of parameters cannot exceed 64. Total length of the input comment (including invisible symbols) cannot exceed 511 symbols (excess symbols will be cut out during output).

Returned Value

No returned value

Note

Arrays can't be passed to the Comment() function.Arrays must be entered element-by-element.

Data of double type are shown with the accuracy of up to 16 digits after a decimal point, and can be output either in traditional or in scientific format, depending on what entry will be more compact. Data of float type are output with 5 digits after a decimal point. To output real numbers with another accuracy or in a predefined format, use the DoubleToString() function.

Data of bool type are output as "true" or "false" lines. Dates are shown as YYYY.MM.DD HH:MI:SS. To show data in another format, use TimeToString(). Data of color type are returned either as R,G,B line or as a color name, if this color is present in the color set.

During input all parameters are space separated.

The Comment function can't be called from a custom indicator, because a custom indicator can't access chart, to which it is attached.

Example:

void OnTick()
{
//---
double Ask,Bid;
int Spread;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);
//--- Output values in three lines
Comment(StringFormat("Show prices\nAsk = %G\nBid = %G\nSpread = %d",Ask,Bid,Spread));
}

See also

ChartSetString, ChartGetString


DebugBreak

MQL5 Reference / Common Functions / DebugBreak

DebugBreak

It is a program breakpoint in debugging.

void DebugBreak();

Returned Value

No returned value.

Note

Execution of an mql5 program is broken only if a program is started in a debugging mode. The function can be used for viewing values fo variables and/or for further step-by-step execution.


GetTickCount

MQL5 Reference / Common Functions / GetTickCount

GetTickCount

The GetTickCount() function returns the number of milliseconds that elapsed since the system start.

int GetTickCount();

Returned Value

Value of int type.

Note

Counter is limited by the restrictions of the system timer. Time is stored as an unsigned integer, so it's overfilled every 49.7 if a computer works uninterruptedly.


MessageBox

MQL5 Reference / Common Functions / MessageBox

MessageBox

It creates and shows a message box and manages it. A message box contains a message and header, any combination of predefined signs and command buttons.

int MessageBox(
string text, // message text
string caption=NULL, // box header
int flags=0 // defines set of buttons in the box
);

Parameters

text

[in] Text, containing message to output.

caption=NULL

[in] Optional text to be displayed in the box header. If the parameter is empty, Expert Advisor name is shown in the box header.

flags=0

[in] Optional flagsdefining appearance and behavior of a message box. Flags can be a combination of a special group of flags.

Returned Value

If the function is successfully performed, the returned value is one of values of MessageBox() return codes.

Note

The function can't be called from custom indicators, because indicators are executed in the interface thread and shouldn't slow down it.


PeriodSeconds

MQL5 Reference / Common Functions / PeriodSeconds

PeriodSeconds

This function returns number of seconds in a period.

int PeriodSeconds(
ENUM_TIMEFRAMES period=PERIOD_CURRENT // chart period
);

Parameters

period=PERIOD_CURRENT

[in] Value of a chart period from the enumeration ENUM_TIMEFRAMES. If the parameter isn't specified, it returns the number of seconds of the current chart period, at which the program runs.

Returned Value

Number of seconds in a selected period.


PlaySound

MQL5 Reference / Common Functions / PlaySound

PlaySound

It plays a sound file.

bool PlaySound(
string filename // file name
);

Parameters

filename

[in] Path to a sound file.

Returned Value

true - if the file is found, otherwise - false.

Note

The file must be located in terminal_directory\Sounds ot its sub-directory. Only WAV files are played.


Print

MQL5 Reference / Common Functions / Print

Print

It enters a message in the Expert advisor log. parameters can be of any type..

void Print(
argument, // first value
... // next values
);

Parameters

...

[in] Any values separated by commas. Number of parameters can't exceed 64.

Note

Arrays cannot be passed to the Print() function. Arrays must be input element-by-element.

Data of double type are shown with the accuracy of up to 16 digits after a decimal point, and can be output either in traditional or in scientific format, depending on what entry will be more compact. Data of float type are output with 5 digits after a decimal point. To output real numbers with another accuracy or in a predefined format, use the DoubleToString() function.

Data of bool type are output as "true" or "false" lines. Dates are shown as YYYY.MM.DD HH:MI:SS. To show data in another format, use TimeToString(). Data of color type are returned either as R,G,B line or as a color name, if this color is present in the color set.

When shown, all parameters are space separated.

Example:

Print("Time of the last received quote ",TimeCurrent());

See also

PrintFormat, StringFormat


PrintFormat

MQL5 Reference / Common Functions / PrintFormat

PrintFormat

It formats and enters sets of symbols and values in the Expert Advisor log in accordance with a preset format.

void PrintFormat(
string format_string, // format line
... // values of simple types
);

Parameters

format_string

[in] A format line consists of simple symbols, and if the format line is followed by arguments, it also contains format specifications.

...

[in] Any values of simple types separated by commas. Total number of parameters can't exceed 64 including the format line.

Note

Instead of PrintFormat() you can use printf().

If the format line is followed by parameters, this line must contain format specifications that denote output format of these parameters. Specification of format always starts with the percent sign (%).

A format line is read from left to right. When the first format specification is met (if there is any), the value of the first parameter after the format line is transformed and output according to the preset specification. The second format specification calls transformation and output of the second parameter, and so on till the format line end. If there are more parameters than format specifications, these additional parameters are ignored.

The format specification has the following form:

%[flags][width][.precision][{h | l | ll | I32 | I64}]type

Each field of the format specification is either a simple symbol, or a number denoting a simple format option. The simplest format specification contains only the percent sign (%) and a symbol defining the type of the output parameter (for example, %s). If you need to output the percent sign in the format line, use the format specification %%.

flags

Flag | Description | Default Behavior
- (Minus) | Left justification within the set width | Right justification
+ (plus) | Output of the + or - sign for values of sign types | The sign is shown only of the value is negative
0 (zero) | Zeroes are added before an output value within the preset width. If 0 flag is specified with an integer format (i, u, x, X, o, d) and accuracy specification is set (for example, %04.d), then 0 is ignored. | Nothing is added
space | A space is shown before an output value, if it is a sign and positive value | Spaces aren't inserted
# | If used together with the format o, x or X, then before the output value 0, 0x or 0X is added respectively. | Nothing is added
 | If used together with the format e, E, a or A, value is always shown with a decimal point. | Decimal point is shown only if there is a non-zero fractional part.
 | If used together with the format g or G, flag defines presence of a decimal point in the output value and prevents the cutting off of leading zeroes. Flag # is ignored when used together with formats c, d, i, u, s. | Decimal point is shown only if there is a non-zero fractional part. Leading zeroes are cut off.
width

A non-negative decimal number that sets the minimal number of output symbols of the formatted value.If the number of output symbols is less than the set width, the corresponding number of spaces is added from the left or right depending on the alignment (flag -).If there is flag zero (0), the corresponding number of zeroes is added before the output value.If the number of output values is larger than the the preset width, the output value is never cut off.

If an asterisk (*) is specified as width, value of int type must be indicated in the corresponding place of the list of passed parameters. It will be used for specifying width of the output value.

precision

A non-negative decimal number that sets the output accuracy - number of digits after a decimal point. As distinct from width specification, accuracy specification can cut off the part of fractional type with or without rounding.

The use of accuracy specification is different for different format types.

Types | Description | Default Behavior
a, A | Accuracy specification sets the number of digits after a decimal point. | Default accuracy - 6.
c, C | Not used |
d, i, u, o, x, X | Sets minimal number of output digits. If number of digits in a corresponding parameter is less than this accuracy, zeroes are added to the left of the output value. The output value isn't cut off, if the number of output digits is larger than th specified accuracy. | Default accuracy - 1.
e, E, f | Sets number of output digits after a decimal point. The last digit is rounded off. | Default accuracy - 6. If set accuracy is 0 or decimal part is absent, the decimal point is not shown.
g, G | Sets maximal number of meaningful numbers. | 6 meaningful numbers are output.
s, S | Sets number of output symbols of a line. If the line length exceeds the accuracy, the line is cut off. | The whole line is output.

h | l | ll | I32 | I64

Specification of data sizes, passed as a parameter.

Parameter Type | Used Prefix | Joint Specifier of Type
int | l (lower case L) | d, i, o, x, or X
uint | l (lower case L) | o, u, x, or X
long | ll (two lower case L) | d, i, o, x, or X
short | h | d, i, o, x, or X
ushort | h | o, u, x, or X
int | I32 | d, i, o, x, or X
uint | I32 | o, u, x, or X
long | I64 | d, i, o, x, or X
ulong | I64 | o, u, x, or X
type

Type specifier is the only obligatory field for formatted output.

Symbol | Type | Output Format
c | int | Symbol of short type (Unicode)
C | int | Symbol of char type (ANSI)
d | int | Sign decimal integer
i | int | Sign decimal integer
o | int | Unsigned octal integer
u | int | Unsigned decimal integer
x | int | Unsigned hexadecimal integer, using "abcdef"
X | int | Unsigned hexadecimal integer, using "ABCDEF"
e | double | A real value in the format [-] d.dddde[sign] ddd, where d - one decimal digit, dddd - one or more decimal digits, ddd - a three-digit number that determines the size of the exponent, sign - plus or minus
E | double | Similar to the format of e, except that the sign of exponent is output by upper case letter (E instead of e)
f | double | A real value in the format [-] dddd.dddd, where dddd - one or more decimal digits. Number of displayed digits before the decimal point depends on the size of number value. Number of digits after the decimal point depends on the required accuracy.
g | double | A real value output in f or e format depending on what output is more compact.
G | double | A real value output in F or E format depending on what output is more compact.
a | double | A real number in format [−]0xh.hhhh pÂ ± dd, where h.hhhh - mantissa in the form of hexadecimal digits, using "abcdef", dd - One or more digits of exponent. Number of decimal places is determined by theaccuracy specification
A | double | A real number in format [−]0xh.hhhh PÂ ± dd, where h.hhhh - mantissa in the form of hexadecimal digits, using "ABSDEF", dd - One or more digits of exponent. Number of decimal places is determined by theaccuracy specification
s | string | Line output

Instead of PrintFormat() you can use printf().

Example:

PrintFormat("Output DBL_MAX in a compact scientific form %e",DBL_MAX);
printf("Output double %.15e",DBL_MAX);
printf("Output double %15e",DBL_MAX);
printf("Output double %15.10e",DBL_MAX);
printf("Output double %15.10f",DBL_MAX);

printf("Output DBL_MAX %e",10);
printf("Output double %d",DBL_MAX);
printf("Output DBL_MAX %s",10);
printf("Output double %s",DBL_MAX);

See also

StringFormat, DoubleToString, Real types (double, float)


ResetLastError

MQL5 Reference / Common Functions / ResetLastError

ResetLastError

Sets the value of the predefined variable _LastError into zero.

void ResetLastError();

Returned Value

No returned value.

Note

It should be noted that the GetLastError() function doesn't zero _LastError variable. Usually ResetLastError() is called befor function call, after which error appearance is checked.


SetUserError

MQL5 Reference / Common Functions / SetUserError

SetUserError

Sets the predefined variable _LastError into the value equal to ERR_USER_ERROR_FIRST + user_error

void SetUserError(
ushort user_error, // error number
);

Parameters

user_error

[in] Error number set by a user.

Returned Value

No returned value.

Note

After an error has been set using the SetUserError(user_error) function, GetLastError() returns value equal to ERR_USER_ERROR_FIRST + user_error.

Example:

void OnStart()
{
//--- set error number 65537=(ERR_USER_ERROR_FIRST +1)
SetUserError(1);
//--- get last error code
Print("GetLastError =",GetLastError());
/*
Result
GetLastError = 65537
*/
}


SendFTP

MQL5 Reference / Common Functions / SendFTP

SendFTP

Sends a file at the address, specified in the setting window of the "Publisher" tab.

bool SendFTP(
string filename, // file to send by ftp
string ftp_path=NULL // file to upload on ftp server
);

Parameters

filename

[in] Name of sent file.

ftp_path=NULL

[in] FTP catalog. If a directory is not specified, directory described in settings is usesd.

Returned Value

In case of failure returns 'false'.

Note

Sent file must be located in the folder terminal_directory\MQL5\files or its subfolders. Sending isn't performed if FTP address and/or access password are not specified in settings.


SendMail

MQL5 Reference / Common Functions / SendMail

SendMail

Sends an email at the address specified in the settings window of the "Mailbox" tab.

bool SendMail(
string subject, // header
string some_text // email text
);

Parameters

subject

[in] Email header.

some_text

[in] Email body.

Returned Value

true - if an email is put into the send queue, otherwise - false.

Note

Sending can be prohibited in settings, email address can be not specified. For the error information call GetLastError().


Sleep

MQL5 Reference / Common Functions / Sleep

Sleep

The function suspends execution of the current Expert Advisor or script within a specified interval.

void Sleep(
int milliseconds // interval
);

Parameters

milliseconds

[in] Delay interval in milliseconds.

Returned Value

No returned value.

Note

The Sleep() function can't be called for custom indicators, because indicators are executed in the interface thread and must not slow down it. The function has the built-in check of EA halt flag every 0.1 seconds.


ZeroMemory

MQL5 Reference / Common Functions / ZeroMemory

ZeroMemory

The function resets the variable passed to it by reference. Variable type can be any, with the exception of only the classes and structures that have constructors.

void ZeroMemory(
void & variable // Reset variable
);

Options

variable

[in] [out] variable passed by reference, you want to reset (initialize zero values).

Return value

No return value.

Note

If the parameter function is a string, then the call will be equivalent to the direction of its value to NULL.
For simple types and arrays, and structures / classes, consisting of such types, a simple reset.
For objects containing strings and dynamic arrays, made the call ZeroMemory () for each member.
For all arrays, not protected by the modifier const, is zeroing all elements.
For arrays of complex objects is a challenge ZeroMemory () for each element.

Function ZeroMemory () is not applicable to classes with protectedMemberorinheritance.


Array Functions

MQL5 Reference / Array Functions

Group of Functions for Working 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].

Function | Action
ArrayBsearch | Returns index of the firs found element in the first array dimension
ArrayCopy | Copies one array into another
ArrayFree | Frees up buffer of any dynamic array and sets the size of the zero dimension in 0.
ArrayGetAsSeries | Checks direction of array indexing
ArrayInitialize | Sets all elements of a numeric array into a single value
ArrayIsSeries | Checks whether an array is a timeseries
ArrayIsDynamic | Checks whether an array is dynamic
ArrayMaximum | Search for an element with the maximal value
ArrayMinimum | Search for an element with the minimal value
ArrayRange | Returns the number of elements in the specified dimension of the array
ArrayResize | Sets the new size in the first dimension of the array
ArraySetAsSeries | Sets the direction of array indexing
ArraySize | Returns the number of elements in the array
ArraySort | Sorting of numeric arrays by the first dimension


ArrayBsearch

MQL5 Reference / Array Functions / ArrayBsearch

ArrayBsearch

The function searches for a specified value in a one-dimension numeric array.

For searching in an array of double type

int ArrayBsearch(
double array[], // array for search
double searched_value // what is searched for
);

For searching in an array of float type

int ArrayBsearch(
float array[], // array for search
float searched_value // what is searched for
);

For searching in an array of long type

int ArrayBsearch(
long array[], // array for search
long searched_value // what is searched for
);

For searching in an array of int type

int ArrayBsearch(
int array[], // array for search
int searched_value // what is searched for
);

For searching in an array of short type

int ArrayBsearch(
short array[], // array for search
short searched_value // what is searched for
);

For searching in an array of char type

int ArrayBsearch(
char array[], // array for search
char searched_value // what is searched for
);

Parameters

array[]

[in] Numeric array for search.

searched_value

[in] Value for search.

Returned Value

The function returns index of a found element. If the wanted value isn't found, the function returns the index of an element nearest in value.

Note

Binary search processes only sorted arrays. To sort numeric arrays use the ArraySort() function.


ArrayCopy

MQL5 Reference / Array Functions / ArrayCopy

ArrayCopy

It copies an array into another one.

int ArrayCopy(
void dst_array[], // destination array
void src_array[], // source array
int dst_start=0, // index starting from which write into destination array
int src_start=0, // first index of a destination array
int cnt=-1 // number of elements
);

Parameters

dst_array[]

[out] Destination array

src_array[]

[in] Source array

dst_start=0

[in] Starting index fro the destination array. By default, start index is 0.

src_start=0

[in] Starting index for the source array. By default, start index is 0.

cnt=-1

[in] Number of elements that should be copied. By default, the whole array is copied (cnt=-1).

Returned Value

It returns the number of copied elements.

Note

If cnt<0 or cnt>src_size-src_start, all the remaining array part is copied. Arrays are copied from left to right. For series arrays, the starting position is correctly defined adjusted for copying from left to right. If an array is copied to itself, the result is undefined.

If arrays are of different types, during copying it tries to transform each element of a source array into the type of the destination array. A string array can be copied into a string array only. Array of classes and structures containing objects that require initialization aren't copied. An array of structures can be copied into an array of the same type only.


ArrayFree

MQL5 Reference / Array Functions / ArrayFree

ArrayFree

It frees up a buffer of any dynamic array and sets the size of the zero dimension to 0.

void ArrayFree(
void array[] // array
);

Parameters

array[]

[in] Dynamic array.

Returned Value

No returned value.


ArrayGetAsSeries

MQL5 Reference / Array Functions / ArrayGetAsSeries

ArrayGetAsSeries

It checks direction of an array index.

bool ArrayGetAsSeries(
void array // array for checking
);

Parameters

array

[in] Checked array.

Returned Value

Returns true, if the specified array has the AS_SERIES flag set, i.e. access to the array is performed back to front as in timeseries. A timeseries differs from a usual array in that the indexing of timeseries elements is performed from its end to beginning (from the newest data to old).

Note

To check whether an array belongs to timeseries, use the ArrayIsSeries() function. Arrays of price data passed as input parameters into the OnCalculate() function do not obligatorily have the indexing direction the same as in timeseries. The necessary indexing direction can be set using the ArraySetAsSeries() function.

See also

Access to timeseries, ArraySetAsSeries


ArrayInitialize

MQL5 Reference / Array Functions / ArrayInitialize

ArrayInitialize

The function initializes a numeric array by a preset value.

void ArrayInitialize(
double array[], // initialized array
double value // value that will be set
);

Parameters

array[]

[out] Numeric array that should be initialized.

value

[in] New value that should be set to all array elements.

Returned Value

Returns the number of initialized elements.

Note

It's not recommended to initialize index buffers in the OnInit() function of custom indicators, because they are automatically initialized byEMPTY_VALUE when buffers are distributed and re-distributed.


ArrayIsDynamic

MQL5 Reference / Array Functions / ArrayIsDynamic

ArrayIsDynamic

The function checks whether an array is dynamic.

bool ArrayIsDynamic(
void array[] // checked array
);

Parameters

array[]

[in] Checked array.

Returned Value

It returns true if the selected array is dynamic, otherwise it returns false.

See also

Access to timeseries and indicators


ArrayIsSeries

MQL5 Reference / Array Functions / ArrayIsSeries

ArrayIsSeries

The function checks whether an array is a timeseries.

bool ArrayIsSeries(
void array[] // checked array
);

Parameters

array[]

[in] Checked array.

Returned Value

It returns true, if a checked array is an array timeseries, otherwise it returns false. Arrays passed as a parameter to the OnCalculate() function must be checked for the order of accessing the array elements by ArrayGetAsSeries().

Example:

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Label1
#property indicator_label1 "Label1"
#property indicator_type1 DRAW_LINE
#property indicator_color1 Red
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- indicator buffers
double Label1Buffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
if(ArrayIsSeries(open))
{
Print("open[] is timeseries");
}
else
{
{
Print("open[] is not timeseries!!!");
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}

See also

Access to timeseries and indicators


ArrayMaximum

MQL5 Reference / Array Functions / ArrayMaximum

ArrayMaximum

The function searches a maximal element in a one-dimension numeric array.

int ArrayMaximum(
double array[], // array for search
int start=0 // index to start checking with
int count=WHOLE_ARRAY, // number of checked elements
);

Parameters

array[]

[in] A numeric array, in which search is made.

start=0

[in] Index to start checking with.

count=WHOLE_ARRAY

[in] Number of elements for search.

Returned Value

The function returns an index of a found element taking into account the array serial. In case of failure it returns -1.


ArrayMinimum

MQL5 Reference / Array Functions / ArrayMinimum

ArrayMinimum

The function searches a minimal element in a one-dimension numeric array.

int ArrayMinimum(
double array[], // array for search
int start=0 // index to start checking with
int count=WHOLE_ARRAY, // number of checked elements
);

Parameters

array[]

[in] A numeric array, in which search is made.

start=0

[in] Index to start checking with.

count=WHOLE_ARRAY

[in] Number of elements for search.

Returned Value

The function returns an index of a found element taking into account the array serial. In case of failure it returns -1.


ArrayRange

MQL5 Reference / Array Functions / ArrayRange

ArrayRange

The function returns the number of elements in a selected array dimension.

int ArrayRange(
void array[], // array for check
int rank_index // number of dimension
);

Parameters

array[]

[in] Checked array.

rank_index

[in] Index of dimension.

Returned Value

Number of elements in a selected array dimension.

Note

Since indexes are zero-based, the size of dimension is 1 greater than the largest index.


ArrayResize

MQL5 Reference / Array Functions / ArrayResize

ArrayResize

The function sets a new size for the first dimension

int ArrayResize(
void array[], // array passed by reference
int new_size, // new array size
int allocated_size=0 // reserve size value (excess)
);

Parameters

array[]

[out] Array for changing sizes.

new_size

[in] New size for the first dimension.

allocated_size=0

[in] Distributed size to get reserve.

Returned Value

If executed successfully, it returns count of all elements contained in the array after resizing, otherwise, returns -1, and array is not resized.

Note

During memory allocation the allocated_size parameter is taken into account. If this account is present, it must be larger than new_size value - thus additional memory is reserved for the array. Re-calls of ArrayResize do not result in physical re-allocation of memory, only the first array dimension is resized within the reserved memory.

The function can be applied only to dynamic arrays.


ArraySetAsSeries

MQL5 Reference / Array Functions / ArraySetAsSeries

ArraySetAsSeries

The function sets the AS_SERIES flag to a selected object of a dynamic array, and elements will be indexed like in timeseries.

bool ArraySetAsSeries(
void array[], // array by reference
bool set // true denotes reverse order of indexing
);

Parameters

array[]

[in][out] Numeric array to set.

set

[in] Array indexing direction.

Note

The AS_SERIES flag can't be set for multi-dimensional arrays or static arrays (arrays, whose size in square brackets is preset already on the compilation stage). Indexing in timeseries differs from a common array in that the elements of timeseries are indexed from the end toeards the beginning (from the newest to oldest data).

Example: Indicator that shows bar number

//+------------------------------------------------------------------+
//| BarNumber.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Numeration
#property indicator_label1 "Numeration"
#property indicator_type1 DRAW_LINE
#property indicator_color1 CLR_NONE
//--- indicator buffers
double NumerationBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,NumerationBuffer,INDICATOR_DATA);
//--- set indexing for the buffer like in timeseries
ArraySetAsSeries(NumerationBuffer,true);
//--- set accuracy of showing in DataWindow
IndicatorSetInteger(INDICATOR_DIGITS,0);
//--- how the name of the indicator arry is displayed in DataWindow
PlotIndexSetString(0,PLOT_LABEL,"Bar #");
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- we'll store the time of the current zero bar opening
static datetime currentBarTimeOpen=0;
//--- Revert access to array the array time [] - do it like in timeseries
ArraySetAsSeries(time,true);
//--- If time of zero bar differs from the stored one
if(currentBarTimeOpen!=time[0])
{
//--- enumerate all bars fromthe current to the chart depth
for(int i=rates_total-1;i>=0;i--) NumerationBuffer[i]=i;
currentBarTimeOpen=time[0];
}
//--- return value of prev_calculated for next call
return(rates_total);
}

See also

Access to timeseries, ArrayGetAsSeries


ArraySize

MQL5 Reference / Array Functions / ArraySize

ArraySize

The function returns the number of elements of a selected array.

int ArraySize(
void array[] // checked array
);

Parameters

array[]

[in] Array of any type.

Returned Value

Value of int type.

Note

For a one-dimensional array, the value to be returned by the ArraySize is equal to that of ArrayRange(array,0).


ArraySort

MQL5 Reference / Array Functions / ArraySort

ArraySort

The function sorts numeric arrays in ascending order from left to right.

bool ArraySort(
number& array[] // array for sorting
);

Parameters

array[]

[in][out] Numeric array for sorting.

Note

An array marked by the AS_SERIES flag is sorted in descending order.


Conversion Functions

MQL5 Reference / Conversion Functions

Conversion Functions

This is 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.

Function | Action
CharToString | Converting a symbol code into a one-character string
DoubleToString | Converting a numeric value to a text line with a specified accuracy
NormalizeDouble | Rounding of a floating point number to a specified accuracy
StringToDouble | Converting a string containing a symbol representation of number into number of double type
StringToInteger | Converting a string containing a symbol representation of number into number of int type
StringToTime | Converting a string containing time or date in "yyyy.mm.dd [hh:mi]" format into datetime type
TimeToString | Converting a value containing time in seconds elapsed since 01.01.1970 into a string of "yyyy.mm.dd hh:mi" format
IntegerToString | Converting int into a string of preset length
ShortToString | Converting symbol code (unicode) into one-symbol string
ShortArrayToString | Copying array part into a string
StringToShortArray | Symbol-wise copying a string to a selected part of array of ushort type
CharArrayToString | Converting symbol code (ansi) into one-symbol array
StringToCharArray | Symbol-wise copying a string converted from Unicode to ANSI, to a selected place of array of uchar type
ColorToString | Converting color value into string as "R,G,B"
StringToColor | Converting "R,G,B" string or string with color name into color type value
StringFormat | Converting number into string according to preset format


CharToString

MQL5 Reference / Conversion Functions / CharToString

CharToString

Converting a symbol code into a one-character string.

string CharToString(
int char_code // numeric code of symbol
);

Parameters

char_code

[in] Code of Unicode symbol.

Returned Value

String with a Unicode symbol.


CharArrayToString

MQL5 Reference / Conversion Functions / CharArrayToString

CharArrayToString

It copies and converts part of array of uchar type into a returned string.

string CharArrayToString(
uchar array[], // array
int start=0, // starting position in the array
int count=-1 // number of sumbols
);

Parameters

array[]

[in] Array of uchar type.

start=0

[in] Position from which copying starts. by default 0 is used.

count=-1

[in] Number of array elements for copying. Defines the length of a resulting string. Default value is -1, which means copying up to the array end, or till terminal 0.

Returned Value

String.


ColorToString

MQL5 Reference / Conversion Functions / ColorToString

ColorToString

It converts color value into string of "R,G,B" form.

string ColorToString(
color color_value, // color value
bool color_name // show color name or not
);

Parameters

color_value

[in] Color value in color type variable.

color_name

[in] Sign of the necessity to return color name, if color name is identical to one of predefined color constants.

Returned Value

String presentation of color as "R,G,B", where R, G and B are decimal constants from 0 to 255 converted into a string. If the color_name=true parameter is set, it will try to convert color value into color name.

Example:

string clr=ColorToString(C'0,255,0'); // green color
Print(clr);

clr=ColorToString(C'0,255,0',true); // get color constant
Print(clr);


DoubleToString

MQL5 Reference / Conversion Functions / DoubleToString

DoubleToString

Converting numeric value into text string.

string DoubleToString(
double value, // number
int digits=8 // number of digits after decimal point
);

Parameters

value

[in] Value with a floating point.

digits

[in] Accuracy format. If the digits value is in the range between 0 and 16, a string presentation of a number with the specified digits after the point will be obtained. In all other cases the string value will contain 8 digits after the decimal point.

Returned Value

String containing a symbol representation of a number with the specified accuracy.

Example:

Print("DoubleToString(120.0+M_PI) : ",DoubleToString(120.0+M_PI));
Print("DoubleToString(120.0+M_PI,16) : ",DoubleToString(120.0+M_PI,16));
Print("DoubleToString(120.0+M_PI,-16) : ",DoubleToString(120.0+M_PI,-16));
Print("DoubleToString(120.0+M_PI,-1) : ",DoubleToString(120.0+M_PI,-1));
Print("DoubleToString(120.0+M_PI,-20) : ",DoubleToString(120.0+M_PI,-20));

See also

NormalizeDouble, StringToDouble


IntegerToString

MQL5 Reference / Conversion Functions / IntegerToString

IntegerToString

This function converting value of integer type into a string of a specified length and returns the obtained string.

string IntegerToString(
long number, // number
int str_len=0, // length of result string
ushort fill_symbol=' ' // filler
);

Parameters

number

[in] Number for conversion.

str_len=0

[in] String length. If the resulting string length is larger than the specified one, the string is not cut off. If it is smaller, filler symbols will be added to the left.

fill_symbol=' '

[in] Filler symbol. By default it is a space.

Returned Value

String.


ShortToString

MQL5 Reference / Conversion Functions / ShortToString

ShortToString

It converts the symbol code (unicode) into one-symbol string and returns resulting string.

string ShortToString(
ushort symbol_code // symbol
);

Parameters

symbol_code

[in] Symbol code. Instead of a symbol code you can use literal string containing a symbol or a literal string with 2-byte hexadecimal code corresponding to the symbol from the Unicode table.

Returned Value

String.


ShortArrayToString

MQL5 Reference / Conversion Functions / ShortArrayToString

ShortArrayToString

It copies part of array into a returned string.

string ShortArrayToString(
ushort array[], // array
int start=0, // starting position in the array
int count=-1 // number of symbols
);

Parameters

array[]

[in] Array of ushort type (analog of wchar_t type).

start=0

[in] Position, from which copying starts, Default - 0.

count=-1

[in] Number of array elements to copy. Defines the length of a resulting string. Default value is -1, which means copying up to the array end, or till terminal 0.

Returned Value

String.


TimeToString

MQL5 Reference / Conversion Functions / TimeToString

TimeToString

Converting a value containing time in seconds elapsed since 01.01.1970 into a string of "yyyy.mm.dd hh:mi" format.

string TimeToString(
datetime value, // number
int mode=TIME_DATE|TIME_MINUTES // output format
);

Parameters

value

[in] Time in seconds from 00:00 1970/01/01.

mode=TIME_DATE|TIME_MINUTES

[in] Additional data input mode. Can be one or combined flag: TIME_DATE gets result as "yyyy.mm.dd", TIME_MINUTES gets result as "hh:mi", TIME_SECONDS gets results as "hh:mi:ss".


NormalizeDouble

MQL5 Reference / Conversion Functions / NormalizeDouble

NormalizeDouble

Rounding floating point number to a specified accuracy.

double NormalizeDouble(
double value, // normalized number
int digits // number of digits after decimal point
);

Parameters

value

[in] Value with a floating point.

digits

[in] Accuracy format, number of digits after point (0-8).

Returned Value

Value of double type with preset accuracy.

Note

Calculated values of StopLoss, TakeProfit, and values of open prices for pending orders must be normalized with the accuracy, the value of which can be obtained by Digits().

Example:

double pi=M_PI;
Print("pi=",DoubleToString(pi,16));

double pi_3=NormalizeDouble(M_PI,3);
Print("NormalizeDouble(pi,3)=",DoubleToString(pi_3,16))
;
double pi_8=NormalizeDouble(M_PI,8);
Print("NormalizeDouble(pi,8)=",DoubleToString(pi_8,16));

double pi_0=NormalizeDouble(M_PI,0);
Print("NormalizeDouble(pi,0)=",DoubleToString(pi_0,16));
/*
Result:
pi= 3.1415926535897931
NormalizeDouble(pi,3)= 3.1419999999999999
NormalizeDouble(pi,8)= 3.1415926499999998
NormalizeDouble(pi,0)= 3.0000000000000000
*/

See also

DoubleToString, Real types (double, float), Reduction of types,


StringToCharArray

MQL5 Reference / Conversion Functions / StringToCharArray

StringToCharArray

Symbol-wise copies a string converted from Unicode to ANSI, to a selected place of array of uchar type. It returns the number of copied elements.

string StringToCharArray(
string text_string, // source string
uchar& array[], // array
int start=0, // starting position in the array
int count=-1 // number of symbols
);

Parameters

text_string

[in] String to copy.

array[]

[out] Array of uchar type.

start=0

[in] Position from which copying starts. Default - 0.

count=-1

[in] number of array elements to copy. Defines length of a resulting string. Default value is -1, which means copying up to the array end, or till terminal 0.

Returned Value

String.


StringToColor

MQL5 Reference / Conversion Functions / StringToColor

StringToColor

Converting "R,G,B" string or string with color name into color type value.

color StringToColor(
string color_string // string representation of color
);

Parameters

color_string

[in] String representation of a color of "R,G,B" type or name of one of predefined Web-colors.

Returned Value

Color value.

Example:

color str_color=StringToColor("0,127,0");
Print(str_color);
Print((string)str_color);
//--- change color a little
str_color=StringToColor("0,128,0");
Print(str_color);
Print((string)str_color);


StringToDouble

MQL5 Reference / Conversion Functions / StringToDouble

StringToDouble

The function converts string containing a symbol representation of number into number of double type.

double StringToDouble(
string value // string
);

Parameters

value

[in] String containing a symbol representation of a number.

Returned Value

Value of double type.


StringToInteger

MQL5 Reference / Conversion Functions / StringToInteger

StringToInteger

The function converts string containing a symbol representation of number into number of int (integer) type.

long StringToInteger(
string value // string
);

Parameters

value

[in] String containing a number.

Returned Value

Value of int type.


StringToShortArray

MQL5 Reference / Conversion Functions / StringToShortArray

StringToShortArray

The function symbol-wise copies a string into a specified place of an array of ushort type.

string StringToShortArray(
string text_string, // source string
ushort& array[], // array
int start=0, // starting position in the array
int count=-1 // number of symbols
);

Parameters

text_string

[in] String to copy

array[]

[out] Array of ushort type (analog of wchar_t type).

start=0

[in] Position, from which copying starts. Default - 0.

count=-1

[in] Number of array elements to copy. Defines length of a resulting string. Default value is -1, which means copying up to the array end, or till terminal 0.

Returned Value

Number of copied elements.


StringToTime

MQL5 Reference / Conversion Functions / StringToTime

StringToTime

The function converts a string containing time or date in "yyyy.mm.dd [hh:mi]" format into datetime type.

datetime StringToTime(
string value // date string
);

Parameters

value

[in] String in " yyyy.mm.dd hh:mi " format.

Returned Value

Value of datetime type containing total number of seconds that elapsed since 01.01.1970.


StringFormat

MQL5 Reference / Conversion Functions / StringFormat

StringFormat

The function formats obtained parameters and returns a string.

string StringFormat(
string format, // string with format description
... ... // parameters
);

Parameters

format

[in] String containing method of formatting. Formatting rules are the same as for the PrintFormat function.

...

[in] Parameters, separated by a comma.

Returned Value

String.

See also

PrintFormat, DoubleToString,ColorToString, TimeToString


Math Functions

MQL5 Reference / Math Functions

Mathematical Functions

A set of mathematical and trigonometric functions.

Function | Action
MathAbs | Returns absolute value (modulus) of the specified numeric value
MathArccos | Returns the arc cosine of x in radians
MathArcsin | Returns the arc sine of x in radians
MathArctan | Returns the arc tangent of x in radians
MathCeil | Returns integer numeric value closest from above
MathCos | Returns the cosine of a number
MathExp | Returns exponent of a number
MathFloor | Returns integer numeric value closest from below
MathLog | Returns natural logarithm
MathMax | Returns the maximal value of the two numeric values
MathMin | Returns the minimal value of the two numeric values
MathMod | Returns the real remainder after the division of two numbers
MathPow | Raises the base to the specified power
MathRand | Returns a pseudorandom value within the range of 0 to 32767
MathRound | Rounds of a value to the nearest integer
MathSin | Returns the sine of a number
MathSqrt | Returns a square root
MathSrand | Sets the starting point for generating a series of pseudorandom integers
MathTan | Returns the tangent of a number
MathIsValidNumber | Checks the correctness of a real number


MathAbs

MQL5 Reference / Math Functions / MathAbs

MathAbs

The function returns the absolute value (modulus) of the specified numeric value.

double MathAbs(
double value // numeric value
);

Parameters

value

[in] Numeric value.

Returned Value

Value of double type more than or equal to zero.

Note

Instead the MathAbs() function you can use fabs().


MathArccos

MQL5 Reference / Math Functions / MathArccos

MathArccos

The function returns the arccosine of x within the range 0 to π in radians.

double MathArccos(
double val // -1<val<1
);

Parameters

val

[in] The val value between -1 and 1, the arc cosine of which is to be calculated.

Returned Value

Arc cosine of a number in radians. If val is less than -1 or more than 1, the function returns NaN (indeterminate value).

Note

Instead of the MathArccos() function you can use acos().

See also

Real types (double, float)


MathArcsin

MQL5 Reference / Math Functions / MathArcsin

MathArcsin

The function the arc sine of x within the range of -π/2 to π/2 radians.

double MathArcsin(
double val // -1<value<1
);

Parameters

val

[in] The val value between -1 and 1, the arc sine of which is to be calculated.

Returned Value

Arc sine of the val number in radians within the range of -π/2 to π/2 radians. If val is less than -1 or more than 1, the function returns NaN (indeterminate value).

Note

Instead of the MathArcsin() function you can use asin().

See also

Real types (double, float)


MathArctan

MQL5 Reference / Math Functions / MathArctan

MathArctan

The function returns the arc tangent of x. If x is equal to 0, the function returns 0.

double MathArctan(
double value // tangent
);

Parameters

value

[in] A number representing a tangent.

Returned Value

MathArctan returns a value within the range of -π/2 to π/2 radians.

Note

Instead of the MathArctan() function you can use atan().


MathCeil

MQL5 Reference / Math Functions / MathCeil

MathCeil

The function returns integer numeric value closest from above.

double MathCeil(
double val // number
);

Parameters

val

[in] Numeric value.

Returned Value

Numeric value representing the smallest integer that exceeds or equals to val.

Note

instead of the MathCeil() function you can use ceil().


MathCos

MQL5 Reference / Math Functions / MathCos

MathCos

The function returns the cosine of an angle.

double MathCos(
double value // number
);

Parameters

value

[in] Angle in radians.

Returned Value

Value of double type within the range of -1 to 1.

Note

Instead of MathCos() you can use cos().


MathExp

MQL5 Reference / Math Functions / MathExp

MathExp

The function returns the value of e raised to the power of d.

double MathExp(
double value // power for the number e
);

Parameters

value

[in] A number specifying the power.

Returned Value

A number of double type. At overflow, the function returns INF (infinity), in case of order loss MathExp returns 0.

Note

Instead of MathExp() you can use exp().

See also

Real types (double, float)


MathFloor

MQL5 Reference / Math Functions / MathFloor

MathFloor

The function returns integer numeric value closest from below.

double MathFloor(
double val // number
);

Parameters

val

[in] Numeric value.

Returned Value

A numeric value representing the largest integer that is less than or equal to val.

Note

Instead of MathFloor() you can use floor().


MathLog

MQL5 Reference / Math Functions / MathLog

MathLog

The function returns a natural logarithm.

double MathLog(
double val // value to take the logarithm
);

Parameters

val

[in] Value logarithm of which is to be found.

Returned Value

The natural logarithm of val in case of success. If val is negative, the function returns NaN (undetermined value). If val is equal to 0, the function returns INF (infinity).

Note

Instead of MathLog() you can use log().

See also

Real types (double, float)


MathLog10

MQL5 Reference / Math Functions / MathLog10

MathLog

Returns the logarithm of a number by base 10.

double MathLog10(
double val // number to take logarithm
);

Parameters

val

[in] Numeric value the common logarithm of which is to be calculated.

Returned Value

The common logarithm in case of success. If val is negative, the function returns NaN (undetermined value). If val is equal to 0, the function returns INF (infinity).

Note

Instead of MathLog10() you can use log10().

See also

Real types (double, float)


MathMax

MQL5 Reference / Math Functions / MathMax

MathMax

The function returns the maximal value of two values.

double MathMax(
double value1, // first value
double value2 // second value
);

Parameters

value1

[in] First numeric value.

value2

[in] Second numeric value.

Returned Value

The largest of the two values.

Note

Instead of MathMax() you can use fmax().


MathMin

MQL5 Reference / Math Functions / MathMin

MathMin

The function returns the minimal value of two values.

double MathMin(
double value1, // first value
double value2 // second value
);

Parameters

value1

[in] First numeric value.

value2

[in] Second numeric value.

Returned Value

The smallest of the two values.

Note

Instead of MathMin() you can use fmin().


MathMod

MQL5 Reference / Math Functions / MathMod

MathMod

The function returns the real remainder of division of two numbers.

double MathMod(
double value, // divident value
double value2 // divisor value
);

Parameters

value

[in] Dividend value.

value2

[in] Divisor value.

Returned Value

The MathMod function calsulates the real value of f of val / y such that val = i * y + f , where i is an integer, f has the same sign as val, and the absolute value of f is less than the absolute value of y.

Note

Instead of MathMod() you can use fmod().


MathPow

MQL5 Reference / Math Functions / MathPow

MathPow

The function raises a base to a specified power.

double MathPow(
double base, // base
double exponent // exponent value
);

Parameters

base

[in] Base.

exponent

[in] Exponent value.

Returned Value

Value of base raised to the specified power.

Note

Instead of MathPow() you can use pow().


MathRand

MQL5 Reference / Math Functions / MathRand

MathRand

Returns a pseudorandom integer within the range of 0 to 32767.

int MathRand();

Returned Value

Integer value within the range of 0 to 32767.

Note

Before the first call of the function, it's necessary to call MathSrand to set the generator of pseudorandom numbers to the initial state.

Note

Instead of MathRand() you can use rand().


MathRound

MQL5 Reference / Math Functions / MathRound

MathRound

The function returns a value rounded off to the nearest integer of the specified numeric value.

double MathRound(
double value // value to be rounded
);

Parameters

value

[in] Numeric value before rounding.

Returned Value

Value rounded till to the nearest integer.

Note

Instead of MathRound() you can use round().


MathSin

MQL5 Reference / Math Functions / MathSin

MathSin

Returns the sine of a specified angle.

double MathSin(
double value // argument in radians
);

Parameters

value

[in] Angle in radians.

Returned Value

sine of an angle measured in radians. Returns value within the range of -1 to 1.

Note

Instead of MathSin() you can use sin().


MathSqrt

MQL5 Reference / Math Functions / MathSqrt

MathSqrt

Returns the square root of a number.

double MathSqrt(
double value // positive number
);

Parameters

value

[in] Positive numeric value.

Returned Value

Square root of value. Of value is negative, MathSqrt returns NaN (indeterminate value).

Note

Instead of MathSqrt() you can use sqrt().

See also

Real types (double, float)


MathSrand

MQL5 Reference / Math Functions / MathSrand

MathSrand

Sets the starting point for generating a series of pseudorandom integers.

void MathSrand(
int seed // initializing number
);

Parameters

seed

[in] Starting number for the row of random numbers.

Returned Value

no returned value.

Note

Ti re-initialize the generator (i.e. set generator into previous initial state), it's necessary to use value 1 as the initializing parameter. Any other value for the initial number sets the generator to the random starting point.

MathRand returns pseudorandom numbers that are generated in succession. Calling MathRand before any call to MathSrand generates the same sequence as calling MathSrand with parameter 1.

Instead of MathSrand() you can use srand().


MathTan

MQL5 Reference / Math Functions / MathTan

MathTan

The function returns a tangent of a number.

double MathTan(
double rad // argument in radians
);

Parameters

rad

[in] Angle in radians.

Returned Value

Tangent of rad. If rad 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.

Note

Instead of MathTan() you can use tan().

See also

Real types (double, float)


MathIsValidNumber

MQL5 Reference / Math Functions / MathIsValidNumber

MathIsValidNumber

It checks the correctness of a real number.

bool MathIsValidNumber(
double number // number to check
);

Parameters

number

[in] Checked numeric value.

Returned Value

It returns true, if the checked value is an acceptable real number. If the checked value is a plus or minus infinity, or "not a number" (NaN), the function returns false.

Example:

double abnormal=MathArcsin(2.0);
if(!MathIsValidNumber(abnormal)) Print("Attention! MathArcsin(2.0) =",abnormal);

See also

Real types (double, float)


String Functions

MQL5 Reference / String Functions

String Functions

This is a group of functions intended for working with data of the string type.

Function | Action
StringAdd | Adds a string at the place of indicated substring
StringBufferLen | Returns the size of buffer distributed for the string
StringConcatenate | Forms a string of parameters passed
StringFill | Fills out a specified string by selected symbols
StringFind | Search for a substring in a string
StringGetCharacter | Returns the value of a number located in the specified string position
StringInit | Initializes string by specified symbols and provides the specified string length
StringLen | Returns the number of symbols in a string
StringSetCharacter | Returns a copy of a string with a changed value of a symbol in a specified position
StringSubstr | Extracts a substring from a text string starting from a specified position
StringToLower | Transforms all symbols of a selected string into capitals by location
StringToUpper | Transforms all symbols of a selected string to lowercase by location
StringTrimLeft | Cuts line feed characters, spaces and tabs in the left part of the string
StringTrimRight | Cuts line feed characters, spaces and tabs in the right part of the string


StringAdd

MQL5 Reference / String Functions / StringAdd

StringAdd

The function adds a substring to the end of a string.

bool StringAdd(
string& string_var, // string, to which we add
string add_substring // string, which is added
);

Parameters

string_var

[in][out] String, to which another one is added.

add_substring

[in] String that is added ti the end of a source string.

Returned Value

In case of success returns true, otherwise false. In order to get an error code, the GetLastError() function should be called.

Note

The StringAdd() add functions is faster and memory saving, as compared to binding strings using addition operations.

Example:

void OnStart()
{
string a="a",b="b",c;
//--- first method
int start=GetTickCount(),stop;
long i;
for(i=0;i<length;i++)
{
c=a+b;
}
stop=GetTickCount();
Print("time for 'c=a+b'=",(stop-start),"milliseconds, i =",i);

//--- second method
start=GetTickCount();
for(i=0;i<length;i++)
{
StringAdd(a,b);
}
stop=GetTickCount();
Print("time for 'StringAdd(a,b)'=",(stop-start),"milliseconds, i =",i);

//--- third method
start=GetTickCount();
a="a"; // re-initialize variable a
for(i=0;i<length;i++)
{
int k=StringConcatenate(c, a, b);
}
stop=GetTickCount();
Print("time for 'StringConcatenate(c,a,b)'=",(stop-start),"milliseconds, i =",i);
}

See also

StringConcatenate


StringBufferLen

MQL5 Reference / String Functions / StringBufferLen

StringBufferLen

The function returns the size of buffer distributed for the string.

int StringBufferLen(
string string_var // string
)

Parameters

string_var

[in] String.

Returned Value

The value 0 means that the string is constant and buffer size can't be changed. -1 means that the string belongs to the client terminal, and modification of the buffer contents can have indeterminate results.

Note

Minimal buffer size is equal to 16.

Example:

void OnStart()
{
string a="a",b="b";
//---
long i;
Print("before: StringBufferLen(a) =",StringBufferLen(a),
" StringLen(a) =",StringLen(a));
for(i=0;i<length;i++)
{
StringAdd(a,b);
}
Print("after: StringBufferLen(a) =",StringBufferLen(a),
" StringLen(a) =",StringLen(a));
}

See also

StringAdd, StringInit, StringLen, StringFill


StringConcatenate

MQL5 Reference / String Functions / StringConcatenate

StringConcatenate

The function forms a string of passed parameters and returns the size of the formed string. Parameters can be of any type. Number of parameters can't be less than 2 or more than 64.

int StringConcatenate(
string& string_var, // string to form
void argument1 // first parameter of any simple type
void argument2 // second parameter of any simple type
... // next parameter of any simple type
);

Parameters

string_var

[in][out] String that will be formed as a result of concatenation.

argumentN

[in] Any comma separated values. From 2 to 63 parameters of any simple type.

Returned Value

Returns the string length, formed by concatenation of parameters transformed into string type. Parameters are transformed into strings according to the sane rules as in Print() and Comment(). As distinct from Print, in the resulting string concatenated parameters are not separated by a space.

Note

StringConcatenate() is faster and memory saving, as compared to binding strings using addition operations, because they don't use temporary variables of string type.

See also

StringAdd


StringFill

MQL5 Reference / String Functions / StringFill

StringFill

It fills out a selected string by specified symbols.

bool StringFill(
string& string_var, // string to fill
short character // symbol that will fill the string
);

Parameters

string_var

[in][out] String, that will be filled out by the selected symbol.

character

[in] Symbol, by which the string will be filled out.

Returned Value

In case of success returns true, otherwise - false. To get the error code call GetLastError().

Note

Filling out a string at place means that symbols are inserted directly to the string without transitional operations of new string creation or copying. This allows to save the operation time.

Example:

void OnStart()
{
string str;
StringInit(str,20,'_');
Print("str =",str);
StringFill(str,0);
Print("str =",str,": StringBufferLen(str) =", StringBufferLen(str));
}
// Result
// str = ____________________
// str = : StringBufferLen(str) = 20
//

See also

StringBufferLen, StringLen, StringInit


StringFind

MQL5 Reference / String Functions / StringFind

StringFind

Search for a substring in a string.

int StringFind(
string string_value, // string in which search is made
string match_substring, // what is searched
int start_pos=0 // from what position search starts
);

Parameters

string_value

[in] String, in which search is made.

match_substring

[in] Searched substring.

start_pos=0

[in] Position in the string from which search is started.

Returned Value

Returns position number in a string, from which the searched substring starts, or -1, if the substring is not found.


StringGetCharacter

MQL5 Reference / String Functions / StringGetCharacter

StringGetCharacter

Returns value of a symbol, located in the specified position of a string.

int StringGetCharacter(
string string_value, // string
int pos // symbol position in the string
);

Parameters

string_value

[in] String.

pos

[in] Position of a symbol in the string. Can be from 0 to StringLen(text) -1.

Returned Value

Symbol code or 0 in case of an error. To get the error code call GetLastError().


StringInit

MQL5 Reference / String Functions / StringInit

StringInit

Initializes a string by specified symbols and provides the specified string size.

bool StringInit(
string& string_var, // string to initialize
int new_len=0, // required string length after initialization
short character=0 // symbol, by which the string will be filled
);

Parameters

string_var

[in][out] String that should be initialized and deinitialized.

new_len=0

[in] String length after initialization. If length=0, it deinitializes the string, i.e. the string buffer is cleared and the buffer address is zeroed.

character=0

[in] Symbol to fill the string.

Returned Value

In case of success returns true, otherwise - false. To get the error code call GetLastError().

Note

If character=0 and the length new_len>0, the buffer of the string of indicated length will be distributed and filled by zeroes. The string length will be equal to zero, because the whole buffer is filled out by string terminators.

Example:

void OnStart()
{
//---
string str;
StringInit(str,200,0);
Print("str =",str,": StringBufferLen(str) =",
StringBufferLen(str)," StringLen(str) =",StringLen(str));
}
/* Result
str = : StringBufferLen(str) = 200 StringLen(str) = 0
*/

See also

StringBufferLen, StringLen


StringLen

MQL5 Reference / String Functions / StringLen

StringLen

Returns the number of symbols in a string.

int StringLen(
string string_value // string
);

Parameters

string_value

[in] String to calculate length.

Returned Value

number of symbols in a string without the ending zero.


StringSetCharacter

MQL5 Reference / String Functions / StringSetCharacter

StringSetCharacter

Returns copy of a string with a changed character in a specified position.

bool StringSetCharacter(
string& string_var, // string
int pos, // position
short character // character
);

Parameters

string_var

[in][out] String.

pos

[in] Position of a character in a string. Can be from 0 to StringLen(text).

character

[in] Symbol code Unicode.

Note

If pos is less than string length and the symbol code value = 0, the string is cut off (but the buffer size, distributed for the stringremains unchanged). The string length becomes equal to pos.

If pos is equal to string length, the specified symbol is added at the string end, and the length is enlarged by one.

Example:

void OnStart()
{
string str="0123456789";
Print("before: str =",str,",StringBufferLen(str) =",
StringBufferLen(str)," StringLen(str) =",StringLen(str));
//--- add zero value in the middle
StringSetCharacter(str,6,0);
Print(" after: str =",str,",StringBufferLen(str) =",
StringBufferLen(str)," StringLen(str) =",StringLen(str));
//--- add symbol at the end
int size=StringLen(str);
StringSetCharacter(str,size,'+');
Print("addition: str =",str,",StringBufferLen(str) =",
StringBufferLen(str)," StringLen(str) =",StringLen(str));
}
/* Result
before: str = 0123456789 ,StringBufferLen(str) = 0 StringLen(str) = 10
after: str = 012345 ,StringBufferLen(str) = 16 StringLen(str) = 6
addition: str = 012345+ ,StringBufferLen(str) = 16 StringLen(str) = 7
*/

See also

StringBufferLen, StringLen, StringFill, StringInit


StringSubstr

MQL5 Reference / String Functions / StringSubstr

StringSubstr

Extracts a substring from a text string starting from the specified position.

string StringSubstr(
string string_value, // string
int start_pos, // position to start with
int length=-1 // length of extracted string
);

Parameters

string_value

[in] String to extract a substring from.

start_pos

[in] Initial position of a substring. Can be from 0 to StringLen(text) -1.

length=-1

[in] Length of an extracted substring. If the parameter value is equal to -1 or parameter isn't set, the substring will be extracted from the indicated position till the string end.

Returned Value

Copy of a extracted substring, if possible. Otherwise returns an empty string.


StringToLower

MQL5 Reference / String Functions / StringToLower

StringToLower

Transforms all all symbols of a selected string into lowercase by location.

bool StringToLower(
string& string_var // string to process
);

Parameters

string_var

[in][out] String.

Returned Value

In case of success returns true, otherwise - false. To get the error code call GetLastError().


StringToUpper

MQL5 Reference / String Functions / StringToUpper

StringToUpper

Transforms all all symbols of a selected string into capitals by location.

bool StringToUpper(
string& string_var // string to process
);

Parameters

string_var

[in][out] String.

Returned Value

In case of success returns true, otherwise - false. To get the error code call GetLastError().


StringTrimLeft

MQL5 Reference / String Functions / StringTrimLeft

StringTrimLeft

The function cuts line feed characters, spaces and tabs in the left part of the string till the first meaningful symbol. The string is modified at place.

int StringTrimLeft(
string& string_var // string to cut
);

Parameters

string_var

[in][out] String that will be cut from the left.

Returned Value

Returns the number of cut symbols.


StringTrimRight

MQL5 Reference / String Functions / StringTrimRight

StringTrimRight

The function cuts line feed characters, spaces and tabs in the right part of the string after the last meaningful symbol. The string is modified at place.

int StringTrimRight(
string& string_var // string to cut
);
);

Parameters

string_var

[in][out] String that will be cut from the right.

Returned Value

Returns the number of cut symbols.


Date and Time

MQL5 Reference / Date and Time

Date and Time

This is the group of functions for working with data of datetime type (an integer that represents the number of seconds elapsed from 0 hours of January 1, 1970).

Function | Action
TimeCurrent | Returns the last known server time (time of the last quote receipt) in the datetime format
TimeTradeServer | Returns the current calculation time of the trade server
TimeLocal | Returns the local computer time in datetime format
TimeGMT | Returns GMT in datetime format with the Daylight Saving Time by local time of the computer, where the client terminal is running
TimeDaylightSavings | Returns the sign of Daylight Saving Time switch
TimeGMTOffset | Returns the current difference between the local computer time and GMT time in seconds, taking into account DST switch
TimeToStruct | Converts a datetime value into a variable of MqlDateTime structure type
StructToTime | Converts a variable of MqlDateTime structure type into a datetime value


TimeCurrent

MQL5 Reference / Date and Time / TimeCurrent

TimeCurrent

Returns the last known server time server, time of the last quote receipt for one of the symbols selected in the "Market Watch" window. In the OnTick() handler, this function returns the time of the received handled tick. In other cases (for example, call in handlers OnInit(), OnDeinit(), OnTimer() and so on) this is the time of the last quote receipt for any symbol available in the "Market Watch" window, the time shown in the title of this window. The time value is formed on a trade server and does not depend on the time settings on your computer. There are 2 variants of the function.

Call without parameters

datetime TimeCurrent();

Call with MqlDateTime type parameter

datetime TimeCurrent(
MqlDateTime& dt_struct // structure type variable
);

Parameters

dt_struct

[out] MqlDateTime structure type variable.

Returned Value

Value of datetime type

Note

If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.


TimeTradeServer

MQL5 Reference / Date and Time / TimeTradeServer

TimeTradeServer

Returns the calculated current time of the trade server. Unlike TimeCurrent(), the calculation of the time value is performed in the client terminal and depends on the time settings on your computer. There are 2 variants of the function.

Call without parameters

datetime TimeTradeServer();

Call with MqlDateTime type parameter

datetime TimeTradeServer(
MqlDateTime& dt_struct // Variable of structure type
);

Parameters

dt_struct

[out] Variable of structure type MqlDateTime.

Returned Value

Value of datetime type

Note

If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.


TimeLocal

MQL5 Reference / Date and Time / TimeLocal

TimeLocal

Returns the local time of a computer, where the client terminal is running. There are 2 variants of the function.

Call without parameters

datetime TimeLocal();

Call with MqlDateTime type parameter

datetime TimeLocal(
MqlDateTime& dt_struct // Variable of structure type
);

Parameters

dt_struct

[out] Variable of structure type MqlDateTime.

Returned Value

Value of datetime type

Note

If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.


TimeGMT

MQL5 Reference / Date and Time / TimeGMT

TimeGMT

Returns the GMT, which is calculated taking into account the DST switch by the local time on the computer where the client terminal is running. There are 2 variants of the function.

Call without parameters

datetime TimeGMT();

Call with MqlDateTime type parameter

datetime TimeGMT(
MqlDateTime& dt_struct // Variable of structure type
);

Parameters

dt_struct

[out] Variable of structure type MqlDateTime.

Returned Value

Value of datetime type

Note

If the MqlDateTime structure type variable has been passed as a parameter, it is filled accordingly.


TimeDayLightsavings

MQL5 Reference / Date and Time / TimeDaylightSavings

TimeDaylightSavings

Returns correction for daylight saving time in seconds, switch to summer time has been made. It depends on the time settings of your computer.

int TimeDaylightSavings();

Returned Value

If switch to winter (standard) time has been made, it returns 0.


TimeGMTOffset

MQL5 Reference / Date and Time / TimeGMTOffset

TimeGMTOffset

Returns the current difference between the local computer time and GMT time in seconds, taking into account switch to winter or summer time. Depends on the time settings of your computer.

int TimeGMTOffset();

Returned Value

The value of int type, representing the current difference between the local time of the computer and GMT time in seconds.


TimeToStruct

MQL5 Reference / Date and Time / TimeToStruct

TimeToStruct

Converts a value of datetime type (number of seconds since 01.01.1970) into a structure variable MqlDateTime.

void TimeToStruct(
datetime dt, // date and time
MqlDateTime& dt_struct // structure for the adoption of values
);

Parameters

dt

[in] Date value to convert.

dt_struct

[out] Variable of structure type MqlDateTime.

Returned Value

No returned value.


StructToTime

MQL5 Reference / Date and Time / StructToTime

StructToTime

Converts a structure variable MqlDateTime into a value of datetime type and returns the resulting value.

datetime StructToTime(
MqlDateTime dt_struct // structure of the date and time
);

Parameters

dt_struct

[in] Variable of structure type MqlDateTime.

Returned Value

The value of datetime type containing the number of seconds since 01.01.1970.


Account Information

MQL5 Reference / Account Information

Account Information

Functions that return parameters of the current account.

Function | Action
AccountInfoDouble | Returns a value of double type of the corresponding account property
AccountInfoInteger | Returns a value of integer type (bool, int or long) of the corresponding account property
AccountInfoString | Returns a value string type corresponding account property
AccountFreeMarginCheck | Returns the free margin that remains after the specified position is opened at the current price on the current account


AccountInfoDouble

MQL5 Reference / Account Information / AccountInfoDouble

AccountInfoDouble

Returns the value of the corresponding account property.

double AccountInfoDouble(
int property_id // identifier of the property
);

Parameters

property_id

[in] Identifier of the property. The value can be one of the values of ENUM_ACCOUNT_INFO_DOUBLE.

Returned Value

Value of double type.

Example:

void OnStart()
{
//--- show all the information available from the function AccountInfoDouble()
printf("ACCOUNT_BALANCE = %G",AccountInfoDouble(ACCOUNT_BALANCE));
printf("ACCOUNT_CREDIT = %G",AccountInfoDouble(ACCOUNT_CREDIT));
printf("ACCOUNT_PROFIT = %G",AccountInfoDouble(ACCOUNT_PROFIT));
printf("ACCOUNT_EQUITY = %G",AccountInfoDouble(ACCOUNT_EQUITY));
printf("ACCOUNT_MARGIN = %G",AccountInfoDouble(ACCOUNT_MARGIN));
printf("ACCOUNT_FREEMARGIN = %G",AccountInfoDouble(ACCOUNT_FREEMARGIN));
printf("ACCOUNT_MARGIN_LEVEL = %G",AccountInfoDouble(ACCOUNT_MARGIN_LEVEL));
printf("ACCOUNT_MARGIN_SO_CALL = %G",AccountInfoDouble(ACCOUNT_MARGIN_SO_CALL));
printf("ACCOUNT_MARGIN_SO_SO = %G",AccountInfoDouble(ACCOUNT_MARGIN_SO_SO));
}

See also

SymbolInfoDouble, SymbolInfoString, SymbolInfoInteger, PrintFormat


AccountInfoInteger

MQL5 Reference / Account Information / AccountInfoInteger

AccountInfoInteger

Returns the value of the properties of the account.

long AccountInfoInteger(
int property_id // Identifier of the property
);

Parameters

property_id

[in] Identifier of the property. The value can be one of the values of ENUM_ACCOUNT_INFO_INTEGER.

Returned Value

Value of long type.

Note

The property must be one of the bool, int or long types.

Example:

void OnStart()
{
//--- show all the information available from the function AccountInfoInteger()
printf("ACCOUNT_LOGIN = %d",AccountInfoInteger(ACCOUNT_LOGIN));
printf("ACCOUNT_LEVERAGE = %d",AccountInfoInteger(ACCOUNT_LEVERAGE));
bool thisAccountTradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_ALLOWED);
bool EATradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_EXPERT);
ENUM_ACCOUNT_TRADE_MODE tradeMode=AccountInfoInteger(ACCOUNT_TRADE_MODE);
ENUM_ACCOUNT_STOPOUT_MODE stopOutMode=AccountInfoInteger(ACCOUNT_MARGIN_SO_MODE);

//--- Inform about the possibility to perform a trade operation
if(thisAccountTradeAllowed)
Print("Trade for this account is permitted");
else
Print("Trade for this account is prohibited!");

//--- Find out if it is possible to trade on this account by Expert Advisors
if(EATradeAllowed)
Print("Trade by Expert Advisors is permitted for this account");
else
Print("Trade by Expert Advisors is prohibited for this account!");

//--- Find out the account type
switch(tradeMode)
{
case(ACCOUNT_TRADE_MODE_DEMO):
Print("This is a demo account");
break;
case(ACCOUNT_TRADE_MODE_CONTEST):
Print("This is a competition account");
break;
default:Print("This is a real account!");
}

//--- Find out the StopOut level setting mode
switch(stopOutMode)
{
case(ACCOUNT_STOPOUT_MODE_PERCENT):
Print("The StopOut level is specified percentage");
break;
default:Print("The StopOut level is specified in monetary terms");
}
}

See also

Account Information


AccountInfoString

MQL5 Reference / Account Information / AccountInfoString

AccountInfoString

Returns the value of the corresponding account property.

string AccountInfoString(
int property_id // Identifier of the property
);

Parameters

property_id

[in] Identifier of the property. The value can be one of the values of ENUM_ACCOUNT_INFO_STRING.

Returned Value

Value of string type.

Example:

void OnStart()
{
//--- Show all the information available from the function AccountInfoString()
Print("The name of the broker =",AccountInfoString(ACCOUNT_COMPANY));
Print("Deposit currency =",AccountInfoString(ACCOUNT_CURRENCY));
Print("Client name =",AccountInfoString(ACCOUNT_NAME));
Print("The name of the trade server =",AccountInfoString(ACCOUNT_SERVER));
}

See also

Account Information


AccountFreeMarginCheck

MQL5 Reference / Account Information / AccountFreeMarginCheck

AccountFreeMarginCheck

Returns the free margin that remains after the specified position is opened at the current price on the current account.

double AccountFreeMarginCheck(
string symbol, // Name of the symbol
int trade_operation, // Type of operation
double volume // Volume
);

Parameters

symbol

[in] Symbol, for which the trade operation will be performed.

trade_operation

[in] Trade operation.

volume

[in] The volume of the opened position.

Returned Value

Value of double type.


Checkup

MQL5 Reference / Checkup

State Checking

Functions that return parameters of the current state of the client terminal

Function | Action
GetLastError | Returns the last error
IsStopped | Returns true, if an mql5 program has been commanded to stop its operation
UninitializeReason | Returns the code of the reason for deinitialization
TerminalInfoInteger | Returns an integer value of a corresponding property of the mql5 program environment
TerminalInfoString | Returns a string value of a corresponding property of the mql5 program environment
MQL5InfoInteger | Returns an integer value of a corresponding property of a running mql5 program
MQL5InfoString | Returns a string value of a corresponding property of a running mql5 program
Symbol | Returns the name of a symbol of the current chart
Period | Returns the current chart timeframe
Digits | Returns the number of decimal digits determining the accuracy of the price value of the current chart symbol
Point | Returns the point size of the the current symbol in the quote currency


GetLastError

MQL5 Reference / Checkup / GetLastError

GetLastError

Returns the contents of the system variable _LastError.

int GetLastError();

Returned Value

Returns the value of the last error that occurred during the execution of an mql5 program.

Note

After the function call, the contents of _LastError are not reset. To reset this variable, you need to call ResetLastError().


IsStopped

MQL5 Reference / Checkup / IsStopped

IsStopped

Checks the forced shutdown of an mql5 program.

bool IsStopped();

Returned Value

Returns true, if the _StopFlag system variable contains a value other than 0. A nonzero value is written into _StopFlag, if a mql5 program has been commanded to complete its operation. In this case, you must immediately terminate the program, otherwise the program will be completed forcibly from the outside after 3 seconds.


UninitializeReason

MQL5 Reference / Checkup / UninitializeReason

UninitializeReason

Returns the code of a reason for deinitialization.

int UninitializeReason();

Returned Value

Returns the value of _UninitReason which is formed before OnDeinit() is called. Value depends on the reasons that led to deinitialization.


TerminalInfoInteger

MQL5 Reference / Checkup / TerminalInfoInteger

TerminalInfoInteger

Returns the value of a corresponding property of the mql5 program environment.

int TerminalInfoInteger(
int property_id // identifier of a property
);

Parameters

property_id

[in] Identifier of a property. Can be one one of the values of the enumeration ENUM_TERMINAL_INFO_INTEGER.

Returned Value

Value of int type.


TerminalInfoString

MQL5 Reference / Checkup / TerminalInfoString

TerminalInfoString

the function returns the value of a corresponding property of the mql5 program environment. The property must be of string type.

string TerminalInfoString(
int property_id // identifier of a property
);

Parameters

property_id

[in] Identifier of a property. Perhaps one of the values of the enumeration ENUM_TERMINAL_INFO_STRING.

Returned Value

Value of string type.


MQL5InfoInteger

MQL5 Reference / Checkup / MQL5InfoInteger

MQL5InfoInteger

Returns the value of a corresponding property of a running mql5 program.

int MQL5InfoInteger(
int property_id // identifier of a property
);

Parameters

property_id

[in] Identifier of a property. Cam be one of values of the MQL5InfoInteger enumeration.

Returned Value

Value of int type.


MQL5InfoString

MQL5 Reference / Checkup / MQL5InfoString

MQL5InfoString

Returns the value of a corresponding property of a running mql5 program.

int MQL5InfoString(
int property_id // Identifier of a property
);

Parameters

property_id

[in] Identifier of a property. Can be one of the MQL5InfoString enumeration.

Returned Value

Value of string type.


Symbol

MQL5 Reference / Checkup / Symbol

Symbol

Returns the name of a symbol of the current chart.

string Symbol();

Returned Value

Value of the _Symbol system variable, which stores the name of the current chart symbol.


Period

MQL5 Reference / Checkup / Period

Period

Returns the current chart timeframe.

ENUM_TIMEFRAMES Period();

Returned Value

The contents of the _Period variable that contains the value of the current chart timeframe. The value can be one of the values of the ENUM_TIMEFRAMES enumeration.


Digits

MQL5 Reference / Checkup / Digits

Digits

Returns the number of decimal digits determining the accuracy of price of the current chart symbol.

int Digits();

Returned Value

The value of the _Digits variable which stores the number of decimal digits determining the accuracy of price of the current chart symbol.


Point

MQL5 Reference / Checkup / Point

Point

Returns the point size of the current symbol in the quote currency.

double Point();

Returned Value

The value of the _Point variable which stores the point size of the current symbol in the quote currency.


Market Info

MQL5 Reference / Market Info

Getting Market Information

These are functions intended for receiving information about the market state.

Function | Action
SymbolsTotal | Returns the number of available (selected in Market Watch or all) symbols
SymbolName | Returns the name of a specified symbol
SymbolSelect | Selects a symbol in the Market Watch window or removes a symbol from the window
SymbolInfoDouble | Returns the double value of the symbol for the corresponding property
SymbolInfoInteger | Returns a value of an integer type (long, datetime, int or bool) of a specified symbol for the corresponding property
SymbolInfoString | Returns a value of the string type of a specified symbol for the corresponding property
SymbolInfoTick | Returns the current prices for the specified character in a variableMqlTick
MarketBookAdd | Provides opening of Depth of Market for a selected symbol, and subscribes for receiving notifications of the DOM changes
MarketBookRelease | Provides closing of Depth of Market for a selected symbol, and cancels the subscription for receiving notifications of the DOM changes
MarketBookGet | Returns a structure array MqlBookInfo containing records of the Depth of Market of a specified symbol


SymbolsTotal

MQL5 Reference / Market Info / SymbolsTotal

SymbolsTotal

Returns the number of available (selected in Market Watch or all) symbols.

int SymbolsTotal(
bool selected // True - only symbols in MarketWatch
);

Parameters

selected

[in] Request mode. Can be true or false.

Returned Value

If the 'selected' parameter is true, the function returns the number of symbols selected in MarketWatch. If the value is false, it returns the total number of all symbols.


SymbolName

MQL5 Reference / Market Info / SymbolName

SymbolName

Returns the name of a symbol.

string SymbolName(
int pos, // number in the list
bool selected // true - only symbols in MarketWatch
);

Parameters

pos

[in] Order number of a symbol.

selected

[in] Request mode. If the value is true, the symbol is taken from the list of symbols selected in MarketWatch. If the value is false, the symbol is taken from the general list.

Returned Value

Value of string type with the symbol name.


SymbolSelect

MQL5 Reference / Market Info / SymbolSelect

SymbolSelect

Selects a symbol in the Market Watch window or removes a symbol from the window.

bool SymbolSelect(
string name, // symbol name
bool select // add or remove
);

Parameters

name

[in] Symbol name.

select

[in] Switch. If the value is false, a symbol should be removed from MarketWatch, otherwise a symbol should be selected in this window. A symbol can't be removed if the symbol chart is open, or there are open positions for this symbol.

Returned Value

In case of failure returns false.


SymbolInfoDouble

MQL5 Reference / Market Info / SymbolInfoDouble

SymbolInfoDouble

Returns the corresponding property of a specified symbol. There are 2 variants of the function.

1. Immediately returns the property value.

double SymbolInfoDouble(
string name, // symbol
int prop_id // identifier of the property
);

2. Returns true or false depending on whether a function is successfully performed. In case of success, the value of the property is placed into a recipient variable, passed by reference by the last parameter.

bool SymbolInfoDouble(
string name, // symbol
int prop_id, // identifier of the property
double& double_var // here we assume the property value
);

Parameters

name

[in] Symbol name.

prop_id

[in] Identifier of a symbol property. The value can be one of the values of the ENUM_SYMBOL_INFO_DOUBLE enumeration.

double_var

[out] Variable of double type receiving the value of the requested property.

Returned Value

The value of double type.


SymbolInfoInteger

MQL5 Reference / Market Info / SymbolInfoInteger

SymbolInfoInteger

Returns the corresponding property of a specified symbol. There are 2 variants of the function.

1. Immediately returns the property value.

long SymbolInfoInteger(
string name, // symbol
int prop_id // identifier of a property

);

2. Returns true or false depending on whether a function is successfully performed. In case of success, the value of the property is placed into a recipient variable, passed by reference by the last parameter.

bool SymbolInfoInteger(
string name, // symbol
int prop_id, // identifier of a property
long& long_var // here we assume the property value
);

Parameters

name

[in] Symbol name.

prop_id

[in] Identifier of a symbol property. The value can be one of the values of the ENUM_SYMBOL_INFO_INTEGER enumeration.

long_var

[out] Variable of the long type receiving the value of the requested property.

Returned Value

The value of int type.

Note

The symbol property must be of long, datetime, int or bool type. If the spread for the specified symbol is floating, then the expression

SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);

returns zero.

Example:

void OnTick()
{
//---
double Ask,Bid;
int Spread;
bool fixed_spread=true;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);
if(Spread==0) // Floating spread
{
fixed_spread=false;
Spread=(Ask-Bid)/Point();
}

string comm,format;
if(fixed_spread)
{
format=StringFormat("Fixed spread = %%d points, Point = %%.%df",_Digits);
comm=StringFormat(format,Spread,Point());
}
else
{
format=StringFormat("Floating spread = %%d points, Point = %%.%df",_Digits);
comm=StringFormat(format,Spread,Point());
}
Comment(comm);
}


SymbolInfoString

MQL5 Reference / Market Info / SymbolInfoString

SymbolInfoString

Returns the corresponding property of a specified symbol. There are 2 variants of the function.

1. Immediately returns the property value.

string SymbolInfoString(
string name, // Symbol
int prop_id // Identifier properties
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool SymbolInfoString(
string name, // Symbol
int prop_id, // Identifier properties
string& string_var // Here we assume the property value
);

Parameters

name

[in] Symbol name.

prop_id

[in] Identifier of a symbol property. The value can be one of the values of the ENUM_SYMBOL_INFO_STRING enumeration.

string_var

[out] Variable of the string type receiving the value of the requested property.

Returned Value

The value of string type.


SymbolInfoTick

MQL5 Reference / Market Info / SymbolInfoTick

SymbolInfoTick

Returns the current prices for the specified character in a variable MqlTick.

bool SymbolInfoTick(
string symbol, // Symbol
MqlTick& tick // Reference to the structure
);

Options

symbol

[in] The name of the character.

book[]

[out] Reference to the structure typeMqlTick, Which will put the current price and time of last update prices.

Return value

Returns true if successful, otherwise false.


MarketBookAdd

MQL5 Reference / Market Info / MarketBookAdd

MarketBookAdd

Provides opening of Depth of Market for a selected symbol, and subscribes for receiving notifications of the DOM changes.

bool MarketBookAdd(
string symbol // symbol
);

Parameters

symbol

[in] The name of a symbol, whose Depth of Market is to be used in the Expert Advisor or script.

Returned Value

The true value if opened successfully, otherwise false.

Note

Normally, this function must be called from the OnInit() function or in the class constructor. To handle incoming alerts, in the Expert Advisor program must contain the function void OnBookEvent(string& symbol).

See also

Structure of Depth of Market, Structures and Classes


MarketBookRelease

MQL5 Reference / Market Info / MarketBookRelease

MarketBookRelease

Provides closing of Depth of Market for a selected symbol, and cancels the subscription for receiving notifications of the DOM changes.

bool MarketBookRelease(
string symbol // symbol
);

Parameters

symbol

[in] Symbol name.

Returned Value

The true value if closed successfully, otherwise false.

Note

Normally, this function must be called from the OnDeinit() function, if the corresponding MarketBookAdd() function has been called in the OnInit() function. Or it must be called from the class destructor, if the corresponding MarketBookAdd() function has been called from the class constructor.

See also

Structure of Depth of Market, Structures and Classes


MarketBookGet

MQL5 Reference / Market Info / MarketBookGet

MarketBookGet

Returns a structure array MqlBookInfo containing records of the Depth of Market of a specified symbol.

bool MarketBookGet(
string symbol, // symbol
MqlBookInfo& book[] // reference to an array
);

Parameters

symbol

[in] Symbol name.

book[]

[in] Reference to an array of Depth of Market records. The array can be pre-allocated for a sufficient number of records. If a dynamic array hasn't been pre-allocated in the operating memory, the client terminal will distribute the array itself.

Returned Value

Returns true in case of success, otherwise false.

Note

The Depth of Market must be pre-opened by the MarketBookAdd() function.

Example:

MqlBookInfo priceArray[];
bool getBook=MarketBookGet(NULL,priceArray);
if(getBook)
{
int size=ArraySize(priceArray);
Print("MarketBookInfo on",Symbol());
for(int i=0;i<size;i++)
{
Print(i+":",priceArray[i].price
+" Volume="+priceArray[i].volume,
" type =",priceArray[i].type);
}
}
else
{
Print("Could not get contents of the symbol DOM",Symbol());
}

See also

Structure of Depth of Market, Structures and Classes


An access to the timeseries and indicators data

MQL5 Reference / Timeseries and Indicators Access

Access to Timeseries and Indicator Data

These are functions for working with timeseries and indicators. A timeseries differs from the usual data array by its reverse ordering - elements of timeseries are indexed from the end of an array to its begin (from the most recent data to the oldest ones). To copy the time-series values and indicator data, it's recommended to use dynamic arrays only, because copying functions are designed to allocate the necessary size of arrays that receive values.

It is historically accepted that an access to the price data in an array is performed from the end of the data. Physically, the new data are always written at the array end, but the index of the array is always equal to zero. The 0 index in the timeseries array denotes data of the current bar, i.e. the bar that corresponds to the unfinished time interval in this timeframe.

A timeframe is the time period, during which a single price bar is formed. There are 21 predefined standard timeframes.

Function | Action
SeriesInfoInteger | Returns information about the state of historical data.
Bars | Returns the number of bars the history for a specified symbol and period.
BarsCalculated | Returns the number of calculated data in an indicator buffer or -1 in the case of error (data hasn't been calculated yet).
CopyBuffer | Gets data of a specified buffer from a specified indicator into an array.
CopyRates | Gets history data of the Rates structure for a specified symbol and period into an array.
CopyTime | Gets history data on bar opening time for a specified symbol and period into an array.
CopyOpen | Gets history data on bar opening price for a specified symbol and period into an array.
CopyHigh | Gets history data on maximal bar price for a specified symbol and period into an array.
CopyLow | Gets history data on minimal bar price for a specified symbol and period into an array.
CopyClose | Gets history data on bar closing price for a specified symbol and period into an array.
CopyTickVolume | Gets history data on tick volumes for a specified symbol and period into an array.
CopyRealVolume | Gets history data on trade volumes for a specified symbol and period into an array.
CopySpread | Gets history data on spreads for a specified symbol and period into an array.

Despite the fact that by using the ArraySetAsSeries() function it is possible to set up in arrays access to elements like that in timeseries, it should be remembered that the array elements are physically stored in one and the same order - only indexing direction changes. To demonstrate this fact let's perform an example:

datetime TimeAsSeries[];
//--- set access to the array like to a timeseries
ArraySetAsSeries(TimeAsSeries,true);
ResetLastError();
int copied=CopyTime(NULL,0,0,10,TimeAsSeries);
if(copied<=0)
{
Print("The copy operation of the open time values for last 10 bars has failed");
return;
}
Print("TimeCurrent =",TimeCurrent());
Print("ArraySize(Time) =",ArraySize(TimeAsSeries));
int size=ArraySize(TimeAsSeries);
for(int i=0;i<size;i++)
{
Print("TimeAsSeries["+i+"] =",TimeAsSeries[i]);
}

datetime ArrayNotSeries[];
ArraySetAsSeries(ArrayNotSeries,false);
ResetLastError();
copied=CopyTime(NULL,0,0,10,ArrayNotSeries);
if(copied<=0)
{
Print("The copy operation of the open time values for last 10 bars has failed");
return;
}
size=ArraySize(ArrayNotSeries);
for(int i=size-1;i>=0;i--)
{
Print("ArrayNotSeries["+i+"] =",ArrayNotSeries[i]);
}

As a result we will get the output like this:

TimeCurrent = 2009.06.11 14:16:23
ArraySize(Time) = 10
TimeAsSeries[0] = 2009.06.11 14:00:00
TimeAsSeries[1] = 2009.06.11 13:00:00
TimeAsSeries[2] = 2009.06.11 12:00:00
TimeAsSeries[3] = 2009.06.11 11:00:00
TimeAsSeries[4] = 2009.06.11 10:00:00
TimeAsSeries[5] = 2009.06.11 09:00:00
TimeAsSeries[6] = 2009.06.11 08:00:00
TimeAsSeries[7] = 2009.06.11 07:00:00
TimeAsSeries[8] = 2009.06.11 06:00:00
TimeAsSeries[9] = 2009.06.11 05:00:00

ArrayNotSeries[9] = 2009.06.11 14:00:00
ArrayNotSeries[8] = 2009.06.11 13:00:00
ArrayNotSeries[7] = 2009.06.11 12:00:00
ArrayNotSeries[6] = 2009.06.11 11:00:00
ArrayNotSeries[5] = 2009.06.11 10:00:00
ArrayNotSeries[4] = 2009.06.11 09:00:00
ArrayNotSeries[3] = 2009.06.11 08:00:00
ArrayNotSeries[2] = 2009.06.11 07:00:00
ArrayNotSeries[1] = 2009.06.11 06:00:00
ArrayNotSeries[0] = 2009.06.11 05:00:00

As we see from the output, as the index of TimeAsSeries array increases, the time value of the index decreases, i.e. we move from the present to the past. For the common array ArrayNotSeries the result is different - as index grows, we move from past to present.

See Also

ArrayIsDynamic, ArrayGetAsSeries, ArraySetAsSeries, ArrayIsSeries


SeriesInfoInteger

MQL5 Reference / Timeseries and Indicators Access / SeriesInfoInteger

SeriesInfoInteger

Returns information about the state of historical data. There are 2 variants of function calls.

1. Directly returns the property value.

long SeriesInfoInteger(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
ENUM_SERIES_INFO_INTEGER prop_id, // property identifier
);

2. Returns true or false depending on the success of the function run. If successful, the property value is placed in the receiving variable passed by reference by the last parameter.

bool SeriesInfoInteger(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
ENUM_SERIES_INFO_INTEGER prop_id, // property ID
long& long_var // variable for getting info
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

prop_id

[in] Identifier of the requested property, value of the ENUM_SERIES_INFO_INTEGER enumeration.

long_var

[out] Variable to which the value of the requested property is placed.

Returned Value

In the first case, it returns value of the long type.

For the second case, it returns true, if the specified property is available and it's value has been placed into long_var variable, otherwise it returns false. For more details about an error, call GetLastError().

Example:

void OnStart()
{
//---
Print("Total number of bars for the symbol-period at this moment =",
SeriesInfoInteger(Symbol(),0,BARS_COUNT));

Print("The first date for the symbol-period at this moment =",
(datetime)SeriesInfoInteger(Symbol(),0,BARS_SERIES_FIRSTDATE));

Print("The first date in the history for the symbol-period on the server =",
(datetime)SeriesInfoInteger(Symbol(),0,BARS_FIRSTDATE));

Print("Symbol data are synchronized =",
(bool)SeriesInfoInteger(Symbol(),0,BARS_SYNCRONIZED));
}


Bars

MQL5 Reference / Timeseries and Indicators Access / Bars

Bars

Returns the number of bars count in the history for a specified symbol and period. There are 2 variants of functions calls.

Request all of the history bars

int Bars(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
);

Request the history bars for the selected time interval

int Bars(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time // end date and time
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

start_time

[in] Bar time corresponding to the first element.

stop_time

[in] Bar time corresponding to the last element.

Returned Value

If the start_time and stop_time parameters are defined, the function returns the number of bars in the specified time interval, otherwise it returns the total number of bars.

See also

Event Processing Functions


BarsCalculated

MQL5 Reference / Timeseries and Indicators Access / BarsCalculated

BarsCalculated

Returns the number of calculated data for the specified indicator.

int BarsCalculated(
int indicator_handle, // indicator handle
);

Parameters

indicator_handle

[in] The indicator handle, returned by the corresponding indicator function.

Returned Value

Returns the amount of calculated data in the indicator buffer or -1 in the case of error (data not calculated yet)

Note

The function is useful when it's necessary to get the indicator data immediately after its creation (indicator handle is available).

Example:

void OnStart()
{
double Ups[];
//--- set timeseries ordering for the the arrays
ArraySetAsSeries(Ups,true);
//--- create handle for the Fractal Indicator
int FractalsHandle=iFractals(NULL,0);
//--- reset the error code
ResetLastError();
//--- try to copy the indicator values
int i,copied=CopyBuffer(FractalsHandle,0,0,1000,Ups);
if(copied<=0)
{
Sleep(50);
for(i=0;i<100;i++)
{
if(BarsCalculated(FractalsHandle)>0)
break;
Sleep(50);
}
copied=CopyBuffer(FractalsHandle,0,0,1000,Ups);
if(copied<=0)
{
Print("Failed to copy upper fractals. Error =",GetLastError(),
"i=",i," copied=",copied);
return;
}
else
Print("Upper fractals copied",
"i=",i," copied=",copied);
}
else Print("Upper fractals copied. ArraySize =",ArraySize(Ups));
}


CopyBuffer

MQL5 Reference / Timeseries and Indicators Access / CopyBuffer

CopyBuffer

Gets data of a specified buffer of a certain indicator in the necessary quantity. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopyBuffer(
int indicator_handle, // indicator handle
int buffer_num, // indicator buffer number
int start_pos, // start position
int count, // amount to copy
double buffer[] // target array to copy
);

Call by the start date and the number of required elements

int CopyBuffer(
int indicator_handle, // indicator handle
int buffer_num, // indicator buffer number
datetime start_time, // start date and time
int count, // amount to copy
double buffer[] // target array to copy
);

Call by the start and end dates of a required time interval

int CopyBuffer(
int indicator_handle, // indicator handle
int buffer_num, // indicator buffer number
datetime start_time, // start date and time
datetime stop_time, // end date and time
double buffer[] // target array to copy
);

Parameters

indicator_handle

[in] The indicator handle, returned by the corresponding indicator function.

buffer_num

[in] The indicator buffer number.

start_pos

[in] The position of the first element to copy.

count

[in] Data count to copy.

start_time

[in] Bar time, corresponding to the first element.

stop_time

[in] Bar time, corresponding to the last element.

buffer[]

[out] Array of double type.

Returned Value

Returns the copied data count or -1 in case of an error.

Note

Counting of elements of copied data (indicator buffer with the index buffer_num) from the starting position is performed from the present to the past, i.e., starting position of 0 means the current bar (indicator value for the current bar).

As a target array buffer [] it is better to use the dynamic array, because CopyBuffer() tries to allocate the size of target array automatically. If indicator buffer (assigned previously for storing the values of the indicator function by SetIndexBufer())) is used as buffer[], all the values of the copied buffer indicator must be copied, and partial copying is not permitted. An example can be found in the custom indicator Awesome_Oscillator.mq5 of the standard terminal.

If you need to make a partial copy of the indicator values to the custom indicator buffer, then for these purposes it is necessary to use an intermediate array, to which the required number is copied.

Further, using this intermediate array, it is necessary to perform element-by-element copying of the required number of values to the right places of a target indicator buffer.

Example:

//+------------------------------------------------------------------+
//| TestCopyBuffer3.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot MA
#property indicator_label1 "MA"
#property indicator_type1 DRAW_LINE
#property indicator_color1 Red
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input bool AsSeries=true;
input int period=15;
input ENUM_MA_METHOD smootMode=MODE_EMA;
input ENUM_APPLIED_PRICE price=PRICE_CLOSE;
input int shift=0;
//--- indicator buffers
double MABuffer[];
int ma_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
Print("AsSeries parameter=",AsSeries);
Print("Indicator buffer after SetIndexBuffer() is a timeseries =",
ArrayGetAsSeries(MABuffer));
//--- set short indicator name
IndicatorSetString(INDICATOR_SHORTNAME,"MA("+period+")"+AsSeries);
//--- set AsSeries(dependes from input parameter)
ArraySetAsSeries(MABuffer,AsSeries);
Print("The indicator buffer after ArraySetAsSeries(MABuffer,true); is timeseries =",
ArrayGetAsSeries(MABuffer));
//---
ma_handle=iMA(Symbol(),0,period,shift,smootMode,price);
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
int copied=CopyBuffer(ma_handle,0,0,rates_total,MABuffer);
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+

See also

Properties of Custom Indicators, SetIndexBuffer


CopyRates

MQL5 Reference / Timeseries and Indicators Access / CopyRates

CopyRates

Gets history data of MqlRates structure of a specified symbol-period in specified quantity into the rates_array array. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopyRates(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
MqlRates rates_array[] // target array to copy
);

Call by the start date and the number of required elements

int CopyRates(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
MqlRates rates_array[] // target array to copy
);

Call by the start and end dates of a required time interval

int CopyRates(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time, // end date and time
MqlRates rates_array[] // target array to copy
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

start_time

[in] Bar time for the first element to copy.

start_pos

[in] The start position for the first element to copy.

count

[in] Data count to copy.

stop_time

[in] Bar time, corresponding to the last element to copy.

rates_array[]

[out] Array of MqlRates type.

Returned Value

Returns the number of copied elements or -1 in case of an error.

Note

The elements ordering of the copied data is from present to the past, i.e., starting position of 0 means the current bar.

Example:

void OnStart()
{
//---
MqlRates rates[];
ArraySetAsSeries(rates,true);
int copied=CopyRates(Symbol(),0,0,100,rates);
if(copied>0)
{
Print("Bars copied:"+copied);
string format="open=%G, high=%G, low=%G, close=%G, volume=%d";
string out;
int size=fmin(copied,10);
for(int i=0;i<size;i++)
{
out=i+":"+TimeToString(rates[i].time);
out=out+" "+StringFormat(format,
rates[i].open,
rates[i].high,
rates[i].low,
rates[i].close,
rates[i].tick_volume);
Print(out);
}
}
else Print("Failed to get history data for the symbol",Symbol());
}

See also

Structures and Classes, TimeToString, StringFormat


CopyTime

MQL5 Reference / Timeseries and Indicators Access / CopyTime

CopyTime

The function gets to time_array history data of bar opening time for the specified symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.

It is recommended to use dynamical array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely.

No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopyTime(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
datetime time_array[] // target array to copy open times
);

Call by the start date and the number of required elements

int CopyTime(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
datetime time_array[] // target array to copy open times
);

Call by the start and end dates of a required time interval

int CopyTime(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time, // stop date and time
datetime time_array[] // target array to copy open times
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

start_pos

[in] The start position for the first element to copy.

count

[in] Data count to copy.

start_time

[in] The start time for the first element to copy.

stop_time

[in] Bar time corresponding to the last element to copy.

time_array[]

[out] Array of datetime type.

Returned Value

Returns the copied data count or -1 in case of an error.

Note

The elements ordering of the copied data is from present to past, i.e., starting position of 0 means the current bar.


CopyOpen

MQL5 Reference / Timeseries and Indicators Access / CopyOpen

CopyOpen

The function gets into open_array the history data of bar open prices for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.

It is recommended to use dynamical array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely.

No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopyOpen(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
double open_array[] // target array to copy open prices
);

Call by the start date and the number of required elements

int CopyOpen(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
double open_array[] // target array for bar open prices
);

Call by the start and end dates of a required time interval

int CopyOpen(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time, // stop date and time
double open_array[] // target array for bar open values
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

start_pos

[in] The start position for the first element to copy.

count

[in] Data count to copy.

start_time

[in] The start time for the first element to copy.

stop_time

[in] The start time for the last element to copy.

open_array[]

[out] Array of double type.

Returned Value

Returns the number of element in the array or -1 in case of an error.

Note

The elements ordering of the copied data is from present to past, i.e., starting position of 0 means the current bar.


CopyHigh

MQL5 Reference / Timeseries and Indicators Access / CopyHigh

CopyHigh

The function gets into high_array the history data of highest bar prices for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.

It is recommended to use dynamical array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely.

No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopyHigh(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
double high_array[] // target array to copy
);

Call by the start date and the number of required elements

int CopyHigh(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
double high_array[] // target array to copy
);

Call by the start and end dates of a required time interval

int CopyHigh(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time, // stop date and time
double high_array[] // target array to copy
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

start_pos

[in] The start position for the first element to copy.

count

[in] Data count to copy.

start_time

[in] The start time for the first element to copy.

stop_time

[in] Bar time, corresponding to the last element to copy.

high_array[]

[out] Array of double type.

Returned Value

Returns the copied data count or -1 in case of an error.

Note

The elements ordering of the copied data is from present to past, i.e., starting position of 0 means the current bar.

Example:

#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"

#property description "An example for output of the High [i] and Low [i]"
#property description "for a random chosen bars"

double High[],Low[];
//+------------------------------------------------------------------+
//| Get Low for specified bar index |
//+------------------------------------------------------------------+
double iLow(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double low=0;
ArraySetAsSeries(Low,true);
int copied=CopyLow(symbol,timeframe,0,Bars(symbol,timeframe),Low);
if(copied>0 && index<copied) low=Low[index];
return(low);
}
//+------------------------------------------------------------------+
//| Get the High for specified bar index |
//+------------------------------------------------------------------+
double iHigh(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double high=0;
ArraySetAsSeries(High,true);
int copied=CopyHigh(symbol,timeframe,0,Bars(symbol,timeframe),High);
if(copied>0 && index<copied) high=High[index];
return(high);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- At each tick we output the High and Low values for the bar with index,
//--- equal of the tick second
datetime t=TimeCurrent();
int sec=t%60;
printf("High[%d] =%G Low[%d] =%G",
sec,iHigh(Symbol(),0,sec),
sec,iLow(Symbol(),0,sec));
}


CopyLow

MQL5 Reference / Timeseries and Indicators Access / CopyLow

CopyLow

The function gets into low_array the history data of minimal bar prices for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.

It is recommended to use dynamical array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely.

No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopyLow(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
double low_array[] // target array to copy
);

Call by the start date and the number of required elements

int CopyLow(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
double low_array[] // target array to copy
);

Call by the start and end dates of a required time interval

int CopyLow(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time, // stop date and time
double low_array[] // target array to copy
);

Parameters

symbol_name

[in] Symbol.

timeframe

[in] Period.

start_pos

[in] The start position for the first element to copy.

count

[in] Data count to copy.

start_time

[in] Bar time, corresponding to the first element to copy.

stop_time

[in] Bar time, corresponding to the last element to copy.

low_array[]

[out] Array of double type.

Returned Value

Returns the copied data count or -1 in case of an error.

Note

The elements ordering of the copied data is from present to past, i.e., starting position of 0 means the current bar.

See also

CopyHigh


CopyClose

MQL5 Reference / Timeseries and Indicators Access / CopyClose

CopyClose

The function gets into close_array the history data of bar close prices for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.

It is recommended to use dynamical array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely.

No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopyClose(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
double close_array[] // target array to copy
);

Call by the start date and the number of required elements

int CopyClose(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
double close_array[] // target array to copy
);

Call by the start and end dates of a required time interval

int CopyClose(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time, // stop date and time
double close_array[] // target array to copy
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

start_pos

[in] The start position for the first element to copy.

count

[in] Data count to copy.

start_time

[in] The start time for the first element to copy.

stop_time

[in] Bar time, corresponding to the last element to copy.

close_array[]

[out] Array of double type.

Returned Value

Returns the copied data count or -1 in case of an error.

Note

The elements ordering of the copied data is from present to past, i.e., starting position of 0 means the current bar.


CopyTickVolume

MQL5 Reference / Timeseries and Indicators Access / CopyTickVolume

CopyTickVolume

The function gets into volume_array the history data of tick volumes for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.

It is recommended to use dynamical array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely.

No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopyTickVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
long volume_array[] // target array for tick volumes
);

Call by the start date and the number of required elements

int CopyTickVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
long volume_array[] // target array for tick volumes
);

Call by the start and end dates of a required time interval

int CopyTickVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time, // stop date and time
long volume_array[] // target array for tick volumes
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

start_pos

[in] The start position for the first element to copy.

count

[in] Data count to copy.

start_time

[in] The start time for the first element to copy.

stop_time

[in] Bar time, corresponding to the last element to copy..

volume_array[]

[out] Array of long type.

Returned Value

Returns the copied data count or -1 in case of an error.

Note

The elements ordering of the copied data is from present to past, i.e., starting position of 0 means the current bar.

Example:

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot TickVolume
#property indicator_label1 "TickVolume"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 C'143,188,139'
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int bars=3000;
//--- indicator buffers
double TickVolumeBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,TickVolumeBuffer,INDICATOR_DATA);
IndicatorSetInteger(INDICATOR_DIGITS,0);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
if(prev_calculated==0)
{
long timeseries[];
ArraySetAsSeries(timeseries,true);
int prices=CopyTickVolume(Symbol(),0,0,bars,timeseries);
for(int i=0;i<rates_total-prices;i++) TickVolumeBuffer[i]=0.0;
for(int i=0;i<prices;i++) TickVolumeBuffer[rates_total-1-i]=timeseries[prices-1-i];
Print("We have received the following number of TickVolume values:"+prices);
}
else
{
long timeseries[];
int prices=CopyTickVolume(Symbol(),0,0,1,timeseries);
TickVolumeBuffer[rates_total-1]=timeseries[0];
}
//--- return value of prev_calculated for next call
return(rates_total);
}


CopyRealVolume

MQL5 Reference / Timeseries and Indicators Access / CopyRealVolume

CopyRealVolume

The function gets into volume_array the history data of trade volumes for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.

It is recommended to use dynamical array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely.

No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopyRealVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
long volume_array[] // target array for volumes values
);

Call by the start date and the number of required elements

int CopyRealVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
long volume_array[] // target array for volumes values
);

Call by the start and end dates of a required time interval

int CopyRealVolume(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time, // stop date and time
long volume_array[] // target array for volumes values
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

start_pos

[in] The start position for the first element to copy.

count

[in] Data count to copy.

start_time

[in] The start time for the first element to copy.

stop_time

[in] Bar time, corresponding to the last element to copy.

volume_array[]

[out] Array of long type.

Returned Value

Returns the copied data count or -1 in the case of error.

Note

The elements ordering of the copied data is from present to the past, i.e., starting position of 0 means the current bar.


CopySpread

MQL5 Reference / Timeseries and Indicators Access / CopySpread

CopySpread

The function gets into spread_array the history data of spread values for the selected symbol-period pair in the specified quantity. It should be noted that elements ordering is from present to past, i.e., starting position of 0 means the current bar.

It is recommended to use dynamical array as a target array, because if the requested data count is less (or more) than the length of the target array, function tries to reallocate the memory so that the requested data fit entirely.

No matter what is the property of the target array - as_series=true or as_series=false. Data will be copied so that the oldest element will be located at the start of the physical memory allocated for the array. There are 3 variants of function calls.

Call by the first position and the number of required elements

int CopySpread(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
int spread_array[] // target array for spread values
);

Call by the start date and the number of required elements

int CopySpread(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
int count, // data count to copy
int spread_array[] // target array for spread values
);

Call by the start and end dates of a required time interval

int CopySpread(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
datetime start_time, // start date and time
datetime stop_time, // stop date and time
int spread_array[] // target array for spread values
);

Parameters

symbol_name

[in] Symbol name.

timeframe

[in] Period.

start_pos

[in] The start position for the first element to copy.

count

[in] Data count to copy.

start_time

[in] The start time for the first element to copy.

stop_time

[in] Bar time, corresponding to the last element to copy.

spread_array[]

[out] Array of int type.

Returned Value

Returns the copied data count or -1 in case of an error.

Note

The elements ordering of the copied data is from present to past, i.e., starting position of 0 means the current bar.

Example:

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Spread
#property indicator_label1 "Spread"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 Red
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int bars=3000;
//--- indicator buffers
double SpreadBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,SpreadBuffer,INDICATOR_DATA);
IndicatorSetInteger(INDICATOR_DIGITS,0);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
if(prev_calculated==0)
{
int spread_int[];
ArraySetAsSeries(spread_int,true);
int spreads=CopySpread(Symbol(),0,0,bars,spread_int);
Print("We have received the following number of Spread values:"+spreads);
for (int i=0;i<spreads;i++)
{
SpreadBuffer[rates_total-1-i]=spread_int[i];
if(i<=30) Print("spread["+i+"] =",spread_int[i]);
}
}
else
{
double Ask,Bid;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Comment("Ask =",Ask," Bid =",Bid);
SpreadBuffer[rates_total-1]=(Ask-Bid)/Point();
}
//--- return value of prev_calculated for next call
return(rates_total);
}


Chart Operations

MQL5 Reference / Chart Operations

Chart Operations

These are functions for working with charts. All chart operations are allowed in Expert Advisors and scripts only.

Function | Action
ChartApplyTemplate | Applies a specific template from a specified file to the chart
ChartOpen | Opens a new chart with the specified symbol and period
ChartClose | Closes the specified chart
ChartFirst | Returns the ID of the first chart of the client terminal
ChartNext | Returns the chart ID of the chart next to the specified one
ChartSymbol | Returns the symbol name of the specified chart
ChartPeriod | Returns the period value of the specified chart
ChartRedraw | Calls a forced redrawing of a specified chart
ChartSetDouble | Sets the double value for a corresponding property of the specified chart
ChartSetInteger | Sets the integer value (datetime, int, color, bool or char) for a corresponding property of the specified chart
ChartSetString | Sets the string valuefor a corresponding property of the specified chart
ChartGetDouble | Returns the double value property of the specified chart
ChartGetInteger | Returns the integer value property of the specified chart
ChartGetString | Returns the string value property of the specified chart
ChartNavigate | Performs shift of the specified chart by the specified number of bars relative to the specified position in the chart
ChartID | Returns the ID of the current chart.
ChartWindowOnDropped | Returns the number (index) of the chart subwindow, the Expert Advisor or script has been dropped to
ChartPriceOnDropped | Returns the price coordinate of the chart point, the Expert Advisor or script has been dropped to
ChartTimeOnDropped | Returns the time coordinate of the chart point, the Expert Advisor or script has been dropped to
ChartXOnDropped | Returns the X coordinate of the chart point, the Expert Advisor or script has been dropped to
ChartYOnDropped | Returns the Y coordinate of the chart point, the Expert Advisor or script has been dropped to
ChartSetSymbolPeriod | Changes the symbol value and a period of the specified chart.
ChartScreenShot | Provides a screenshot of the chart of its current state in a gif format


ChartApplyTemplate

MQL5 Reference / Chart Operations / ChartApplyTemplate

ChartApplyTemplate

Applies a specific template from a specified file to the chart.

bool ChartApplyTemplate(
long chart_id, // Chart ID
const string filename // Template file name
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

filename

[in] The name of the file containing the template. The file is searched in "MQL5\Files" folder.

Returned Value

If a template is applied successfully, the function returns true, otherwise false. To get an information about the error, call the GetLastError() function.

Note

The Expert Advisor will be unloaded and won't be able to continue operating in case of successful loading of a new template to the chart it is attached to.


ChartOpen

MQL5 Reference / Chart Operations / ChartOpen

ChartOpen

Opens a new chart with the specified symbol and period.

long ChartOpen(
string symbol, // Symbol name
ENUM_TIMEFRAMES period // Period
);

Parameters

symbol

[in] Chart symbol. NULL means the symbol of the current chart (the Expert Advisor is attached to).

period

[in] Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES values. 0 means the current chart period.

Returned Value

If successful, it returns the opened chart ID. Otherwise returns 0.


ChartFirst

MQL5 Reference / Chart Operations / ChartFirst

ChartFirst

Returns the ID of the first chart of the client terminal.

long ChartFirst();

Returned Value

Chart ID.


ChartNext

MQL5 Reference / Chart Operations / ChartNext

ChartNext

Returns the chart ID of the chart next to the specified one.

long ChartNext(
long chart_id // Chart ID
);

Parameters

chart_id

[in] Chart ID. 0 does not mean the current chart. 0 means "return the first chart ID".

Returned Value

Chart ID. If this is the end of the chart list, it returns -1.

Example:

//--- variables for chart ID
long currChart,prevChart=ChartFirst();
int i=0,limit=100;
Print("ChartFirst =",ChartSymbol(prevChart)," ID =",prevChart);
while(i<limit)// We have certainly not more than 100 open charts
{
currChart=ChartNext(prevChart); // Get the new chart ID by using the previous chart ID
if(currChart<0) break; // Have reached the end of the chart list
Print(i,ChartSymbol(currChart)," ID =",currChart);
prevChart=currChart;// let's save the current chart ID for the ChartNext()
i++;// Do not forget to increase the counter
}


ChartClose

MQL5 Reference / Chart Operations / ChartClose

ChartClose

Closes the specified chart.

bool ChartClose(
long chart_id=0 // Chart ID
);

Parameters

chart_id=0

[in] Chart ID. 0 means the current chart.

Returned Value

If successful, returns true, otherwise false.


ChartSymbol

MQL5 Reference / Chart Operations / ChartSymbol

ChartSymbol

Returns the symbol name for the specified chart.

string ChartSymbol(
long chart_id=0 // Chart ID
);

Parameters

chart_id=0

[in] Chart ID. 0 means the current chart.

Returned Value

If chart does not exist, the result will be an empty string.

See also

ChartSetSymbolPeriod


ChartPeriod

MQL5 Reference / Chart Operations / ChartPeriod

ChartPeriod

Returns the timeframe period of specified chart.

ENUM_TIMEFRAMES ChartPeriod(
long chart_id=0 // Chart ID
);

Parameters

chart_id=0

[in] Chart ID. 0 means the current chart.

Returned Value

The function returns one of the ENUM_TIMEFRAMES values. If chart does not exist, it returns 0.


ChartRedraw

MQL5 Reference / Chart Operations / ChartRedraw

ChartRedraw

This function calls a forced redrawing of a specified chart.

void ChartRedraw(
long chart_id=0 // Chart ID
);

Parameters

chart_id=0

[in] Chart ID. 0 means the current chart.

Note

Usually it is used after changing the object properties.

See also

Objects functions


ChartSetDouble

MQL5 Reference / Chart Operations / ChartSetDouble

ChartSetDouble

Sets a value for a corresponding property of the specified chart. Chart property should be of a double type.

bool ChartSetDouble(
long chart_id, // Chart ID
int prop_id, // Property ID
double value // Value
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

prop_id

[in] Chart property ID. Can be one of the ENUM_CHART_PROPERTY_DOUBLE values (except the read-only properties).

value

[in] Property value.

Returned Value

Returns true if successful, otherwise returns false.


ChartSetInteger

MQL5 Reference / Chart Operations / ChartSetInteger

ChartSetInteger

Sets a value for a corresponding property of the specified chart. Chart property must be datetime, int, color, bool or char.

bool ChartSetInteger(
long chart_id, // Chart ID
int prop_id, // Property ID
long value // Value
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

prop_id

[in] Chart property ID. It can be one of the ENUM_CHART_PROPERTY_INTEGER value (except the read-only properties).

value

[in] Property value.

Returned Value

Returns true if successful, otherwise returns false.


ChartSetString

MQL5 Reference / Chart Operations / ChartSetString

ChartSetString

Sets a value for a corresponding property of the specified chart. Chart property must be of the string type.

bool ChartSetString(
long chart_id, // Chart ID
int prop_id, // Property ID
string str_value // Value
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

prop_id

[in] Chart property ID. It's value can be one of the ENUM_CHART_PROPERTY_STRING values (except the read-only properties).

str_value

[in] Property value string. String length cannot exceed 127 characters (extra characters will be truncated).

Returned Value

Returns true if successful, otherwise false.

Note

ChartSetString can be used for a comment output on the chart instead of the Comment function.

Example:

void OnTick()
{
//---
double Ask,Bid;
int Spread;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);
string comment=StringFormat("Printing prices:\nAsk = %G\nBid = %G\nSpread = %d",
Ask,Bid,Spread);
ChartSetString(0,CHART_COMMENT,comment);
}

See also

Comment, ChartGetString


ChartGetDouble

MQL5 Reference / Chart Operations / ChartGetDouble

ChartGetDouble

Returns the value of a corresponding property of the specified chart. Chart property must be of double type. There are 2 variants of th efunction calls.

1. Returns the property value directly.

double ChartGetDouble(
long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window=0 // subwindow number, if necessary
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a target variable double_var passed by reference.

bool ChartGetDouble(
long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window, // Subwindow number
double& double_var // Target variable for the chart property
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

prop_id

[in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_DOUBLE values.

sub_window

[in] Number of the chart subwindow. For the first case, the default value is 0 (main chart window). The most of the properties do not require a subwindow number.

double_var

[out] Target variable of double type for the requested property.

Returned Value

The value of double type.

For the second call case it returns true if the specified property is available and its value has been placed into double_var variable, otherwise returns false. To get an additional information about the error, it is necessary to call the function GetLastError().

Example:

void OnStart()
{
double priceMin=ChartGetDouble(0,CHART_PRICE_MIN,0);
double priceMax=ChartGetDouble(0,CHART_PRICE_MAX,0);
Print("CHART_PRICE_MIN =",priceMin);
Print("CHART_PRICE_MAX =",priceMax);
}


ChartGetInteger

MQL5 Reference / Chart Operations / ChartGetInteger

ChartGetInteger

Returns the value of a corresponding property of the specified chart. Chart property must be of datetime, int or bool type. There are 2 variants of the function calls.

1. Returns the property value directly.

long ChartGetInteger(
long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window=0 // subwindow number, if necessary
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a target variable long_var passed by reference.

bool ChartGetInteger(
long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window, // subwindow number
long& long_var // Target variable for the property
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

prop_id

[in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_INTEGER values.

sub_window

[in] Number of the chart subwindow. For the first case, the default value is 0 (main chart window). The most of the properties do not require a subwindow number.

long_var

[out] Target variable of long type for the requested property.

Returned Value

The value of long type.

For the second call case it returns true if specified property is available and its value has been stored into long_var variable, otherwise returns false. To get additional information about the error, it is necessary to call the function GetLastError().

Example:

void OnStart()
{
int height=ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
int width=ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0);
Print("CHART_HEIGHT_IN_PIXELS =",height,"pixels");
Print("CHART_WIDTH_IN_PIXELS =",width,"pixels");
}


ChartGetString

MQL5 Reference / Chart Operations / ChartGetString

ChartGetString

Returns the value of a corresponding property of the specified chart. Chart property must be of string type. There are 2 variants of the function call.

1. Returns the property value directly.

string ChartGetString(
long chart_id, // Chart ID
int prop_id // Property ID
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a target variable string_var passed by reference.

bool ChartGetString(
long chart_id, // Chart ID
int prop_id, // Property ID
string& string_var // Target variable for the property
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

prop_id

[in] Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_STRING values.

string_var

[out] Target variable of string type for the requested property.

Returned Value

The value of string type.

For the second call case it returns true if the specified property is available and its value has been stored into string_var variable, otherwise returns false. To get additional information about the error, it is necessary to call the function GetLastError().

Note

ChartGetString can be used for reading comments plotted on the chart using the Comment or ChartSetString functions.

Example:

void OnStart()
{
ChartSetString(0,CHART_COMMENT,"Test comment.\nSecond line.\nThird!");
ChartRedraw();
Sleep(1000);
string comm=ChartGetString(0,CHART_COMMENT);
Print(comm);
}

See also

Comment, ChartSetString


ChartNavigate

MQL5 Reference / Chart Operations / ChartNavigate

ChartNavigate

Performs shift of the specified chart by the specified number of bars relative to the specified position in the chart.

bool ChartNavigate(
long chart_id, // Chart ID
int position, // Position
int shift=0 // Shift value
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

position

[in] Chart position to perform a shift. Can be one of the ENUM_CHART_POSITION values.

shift=0

[in] Number of bars to shift the chart. The positive value means the right shift (to the end if the chart), the negative value means the left shift (to the chart begin). The zero shift can be used to navigate to chart beginning or end.

Returned Value

Returns true if successful, otherwise returns false.


ChartID

MQL5 Reference / Chart Operations / ChartID

ChartID

Returns the ID of the current chart.

long ChartID();

Returned Value

Value of long type.


ChartWindowOnDropped

MQL5 Reference / Chart Operations / ChartWindowOnDropped

ChartWindowOnDropped

Returns the number (index) of the chart subwindow, the Expert Advisor or script has been dropped to. 0 means the main chart window.

int ChartWindowOnDropped();

Returned Value

Value of int type.

Example:

int myWindow=ChartWindowOnDropped();
int windowsTotal=ChartGetInteger(0,CHART_WINDOWS_TOTAL);
Print("Script is running on the window #"+myWindow+
". Total windows on the chart "+ChartSymbol()+":",windowsTotal);

See also

ChartPriceOnDropped, ChartTimeOnDropped, ChartXOnDropped, ChartYOnDropped


ChartPriceOnDropped

MQL5 Reference / Chart Operations / ChartPriceOnDropped

ChartPriceOnDropped

Returns the price coordinate corresponding to the chart point, an Expert Advisor or script has been dropped to.

double ChartPriceOnDropped();

Returned Value

Value of double type.

Example:

double p=ChartPriceOnDropped();
Print("ChartPriceOnDropped()=",p);

See also

ChartXOnDropped, ChartYOnDropped


ChartTimeOnDropped

MQL5 Reference / Chart Operations / ChartTimeOnDropped

ChartTimeOnDropped

Returns the time coordinate corresponding to the chart point, an Expert Advisor or script has been dropped to.

datetime ChartTimeOnDropped();

Returned Value

Value of datetime type.

Example:

datetime t=ChartTimeOnDropped();
Print("Script was dropped on the "+t);

See also

ChartXOnDropped, ChartYOnDropped


ChartXOnDropped

MQL5 Reference / Chart Operations / ChartXOnDropped

ChartXOnDropped

Returns the X coordinate of the chart point, an Expert Advisor or script has been dropped to.

int ChartXOnDropped();

Returned Value

The X coordinate value.

Note

X axis direction from left to right.

Example:

int X=ChartXOnDropped();
int Y=ChartYOnDropped();
Print("(X,Y)=("+X+","+Y+")");

See also

ChartWindowOnDropped, ChartPriceOnDropped, ChartTimeOnDropped


ChartYOnDropped

MQL5 Reference / Chart Operations / ChartYOnDropped

ChartYOnDropped

Returns the Y coordinateof the chart point, an Expert Advisor or script has been dropped to.

int ChartYOnDropped();

Returned Value

The Y coordinate value.

Note

Y axis direction from top to bottom.

See also

ChartWindowOnDropped, ChartPriceOnDropped, ChartTimeOnDropped


ChartSetSymbolPeriod

MQL5 Reference / Chart Operations / ChartSetSymbolPeriod

ChartSetSymbolPeriod

Changes the symbol and period of the specified chart. The function is asynchronous, i.e. it sends the command and does not wait for its execution completion.

bool ChartSetSymbolPeriod(
long chart_id, // Chart ID
string symbol, // Symbol name
ENUM_TIMEFRAMES period // Period
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

symbol

[in] Chart symbol. NULL value means the current chart symbol (Expert Advisor is attached to)

period

[in] Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES values. 0 means the current chart period.

Returned Value

Returns true if successful, otherwise false.

Note

The symbol/period change leads to the re-initialization of the Expert Advisor, attached to a chart.

See also

ChartSymbol, ChartPeriod


ChartScreenShot

MQL5 Reference / Chart Operations / ChartScreenShot

ChartScreenShot

The function provides a screenshot of the chart in its current state in a gif format.

bool ChartScreenShot(
long chart_id, // Chart ID
string filename, // Symbol name
int width, // Width
int height, // Height
ENUM_ALIGN_MODE align_mode=ALIGN_RIGHT // Alignment type
);

Parameters

chart_id

[in] Chart ID. 0 means the current chart.

filename

[in] Screenshot file name. Cannot exceed 63 characters. Screenshot files are placed in the directory \ Files.

width

[in] Screenshot width in pixels.

height

[in] Screenshot height in pixels.

align_mode=ALIGN_RIGHT

[in] Output mode of a narrow screenshot. ALIGN_RIGHT means align to the right margin (the output from the end). ALIGN_LEFT means Left justify.

Returned Value

Returns true if successful, otherwise false.

Note

If you need to take a screenshot from a chart from a certain position, first it's necessary to position the graph using the ChartNavigate() function. If the horizontal size of the screenshot is smaller than the chart window, either the right part of the chart window, or its left part is output, depending on the align_mode settings.


Trade functions

MQL5 Reference / Trade functions

Trade functions

This is the group of functions intended for managing trading activities.

Trading functions can be used in Expert Advisors and scripts. Trading functions can be called only if in the properties of the Expert Advisor or script the "Allow live trading" checkbox is enabled.

Function | Action
OrderSend | Sends trade requests to a server
PositionsTotal | Returns the number of open positions
PositionGetSymbol | Returns the symbol corresponding to the open position
PositionSelect | Chooses an open position for further working with it
PositionGetDouble | Returns the requested property of an open position (double)
PositionGetInteger | Returns the requested property of an open position (datetime or int)
PositionGetString | Returns the requested property of an open position (string)
OrdersTotal | Returns the number of orders
OrderGetTicket | Return the ticket of a corresponding order
OrderSelect | Selects a order for further working with it
OrderGetDouble | Returns the requested property of the order (double)
OrderGetInteger | Returns the requested property of the order (datetime or int)
OrderGetString | Returns the requested property of the order (string)
HistorySelect | Retrieves the history of transactions and orders for the specified period of the server time
HistoryOrderSelect | Selects an order in the history for further working with it
HistoryOrdersTotal | Returns the number of orders in the history
HistoryOrderGetTicket | Return order ticket of a corresponding order in the history
HistoryOrderGetDouble | Returns the requested property of an order in the history of (double)
HistoryOrderGetInteger | Returns the requested property of an order in the history (datetime or int)
HistoryOrderGetString | Returns the requested property of an order in the history of (string)
HistoryDealsTotal | Returns the number of deals in the history
HistoryDealGetTicket | Returns a ticket of a corresponding deal in the history
HistoryDealGetDouble | Returns the requested property of a deal in the history (double)
HistoryDealGetInteger | Returns the requested property of a deal in the history (datetime or int)
HistoryDealGetString | Returns the requested property of a deal in the history (string)


OrderSend

MQL5 Reference / Trade functions / OrderSend

OrderSend

OrderSend () is intended for implementing trading activities within MQL5.

bool OrderSend(
MqlTradeRequest& request // query structure
MqlTradeResult& result // structure of the answer
);

Parameters

request

[in] Pointer to a structure of MqlTradeRequest type describing the trade activity of the client.

result

[in,out] Pointer to a structure of MqlTradeResult type describing the result of trade operation in case of a successful completion (if true is returned).

Returned Value

In case of a successful basic check of structures (index checking) returns true --this is not a sign of successful execution of a trade operation. For a more detailed description of the function execution result, analyze the fields of result structure.

Note

It should be noted when placing a market order that the successful completion of the OrderSend() method operation does not always mean a successful deal completion. Check in the returned result structure result the retcode value containing trade server return code, and values of deal or order field depending on the type of operation.


PositionsTotal

MQL5 Reference / Trade functions / PositionsTotal

PositionsTotal

Returns the number of open positions.

int PositionsTotal();

Returned Value

Value of int type.


PositionGetSymbol

MQL5 Reference / Trade functions / PositionGetSymbol

PositionGetSymbol

Returns the symbol corresponding to the open position and automatically selects the position for further working with it using functions PositionGetDouble, PositionGetInteger, PositionGetString.

string PositionGetSymbol(
int index // Number in the list of positions
);

Parameters

index

[in] Number of the position in the list of open positions.

Returned Value

Value of the string type.


PositionSelect

MQL5 Reference / Trade functions / PositionSelect

PositionSelect

Chooses an open position for further working with it. Returns true if the function is successfully completed. Returns false in case of failure. To obtain information about the error, call GetLastError().

bool PositionSelect(
string symbol // Symbol name
uint timeout=0 // Timeout in milliseconds
);

Parameters

symbol

[in] Name of the financial security.

timeout=0

[in] Timeout value in milliseconds. Means the maximum time allowed to find the position for the specified symbol. If during the timeout a position hasn't been selected, the function returns false.

Returned Value

Value of the bool type.

Note

If the function fails due to a timeout 4757 error will be generated.


PositionGetDouble

MQL5 Reference / Trade functions / PositionGetDouble

PositionGetDouble

The function returns the requested property of an open position, pre-selected using PositionGetSymbol or PositionSelect. The position property must be of the double type. There are 2 variants of the function.

1. Immediately returns the property value.

double PositionGetDouble(
ENUM_POSITION_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of the function execution. If successful, the value of the property is placed in a receiving variables passed by reference by the last parameter.

bool PositionGetDouble(
ENUM_POSITION_PROPERTY property_id, // Property identifier
double& double_var // Here we accept the property value
);

Parameters

property_id

[in] Identifier of a position property. The value can be one of the values of the ENUM_POSITION_PROPERTY_DOUBLE enumeration.

double_var

[out] Variable of the double type, accepting the value of the requested property.

Returned Value

Value of the double type.


PositionGetInteger

MQL5 Reference / Trade functions / PositionGetInteger

PositionGetInteger

The function returns the requested property of an open position, pre-selected using PositionGetSymbol or PositionSelect. The position property should be of datetime, int type. There are 2 variants of the function.

1. Immediately returns the property value.

long PositionGetInteger(
ENUM_POSITION_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of the function execution. If successful, the value of the property is placed in a receiving variables passed by reference by the last parameter.

bool PositionGetInteger(
ENUM_POSITION_PROPERTY property_id, // Property identifier
long& long_var // Here we accept the property value
);

Parameters

property_id

[in] Identifier of a position property. The value can be one of the values of the ENUM_POSITION_PROPERTY_INTEGER enumeration.

long_var

[out] Variable of the long type accepting the value of the requested property.

Returned Value

Value of the long type.


PositionGetString

MQL5 Reference / Trade functions / PositionGetString

PositionGetString

The function returns the requested property of the open position, pre-selected with the function PositionGetSymbol or PositionSelect. The property's position must be of type string. There are 2 variants of the function.

1. Immediately returns the property value.

string PositionGetString(
ENUM_POSITION_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of the function execution. If successful, the value of the property is placed in a receiving variables passed by reference by the last parameter.

bool PositionGetString(
ENUM_POSITION_PROPERTY property_id, // Property identifier
string& string_var // Here we assume the property value
);

Parameters

property_id

[in] Identifier property position. The value can be one of the values of the enumeration ENUM_POSITION_PROPERTY_STRING.

string_var

[out] Variable of type string, the host value of the requested properties.

Returned Value

Value type string.


OrdersTotal

MQL5 Reference / Trade functions / OrdersTotal

OrdersTotal

Returns the number of orders.

int OrdersTotal();

Returned Value

Value type int.


OrderGetTicket

MQL5 Reference / Trade functions / OrderGetTicket

OrderGetTicket

Returns ticket or order and automatically selects the order for further work with them using functions.

ulong OrderGetTicket(
int index // Number in the list of orders
);

Parameters

index

[in] Number of the order in the list of orders.

Returned Value

Value type ulong.


OrderSelect

MQL5 Reference / Trade functions / OrderSelect

OrderSelect

Select a order for further work with.Returns true if successful, the function.Returns false if it fails function.To obtain information about the error, you need to call GetLastError().

bool OrderSelect(
ulong ticket // Order ticket
uint timeout=0 // Timeout in milliseconds
);

Parameters

ticket

[in] Order ticket.

timeout=0

[in] Timeout value in milliseconds. Means the maximum time allowed to find the position of the specified order. If during the timeout choice order does not succeed, then the function returns false.

Returned Value

Value type bool.

Note

If the function fails due to a timeout error will be generated 4757.


OrderGetDouble

MQL5 Reference / Trade functions / OrderGetDouble

OrderGetDouble

Returns the requested property warrants, pre-selected with the function OrderGetTicket or OrderSelect. The property warrants must be of type double. There are 2 variants of the function.

1. Immediately returns the property value. properties.

double OrderGetDouble(
ENUM_ORDER_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool OrderGetDouble(
ENUM_ORDER_PROPERTY property_id, // Property identifier
double& double_var // Here we assume the property value
);

Parameters

property_id

[in] Identifier property of order. The value can be one of the values of the enumeration ENUM_ORDER_PROPERTY_DOUBLE.

double_var

[out] Variable of type double, the host value of the requested properties.

Returned Value

Value type double.


OrderGetInteger

MQL5 Reference / Trade functions / OrderGetInteger

OrderGetInteger

Returns the requested property warrants, pre-selected with the function OrderGetTicket or OrderSelect. Order property must be of type datetime, int. There are 2 variants of the function.

1. Immediately returns the property value.

long OrderGetInteger(
ENUM_ORDER_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool OrderGetInteger(
ENUM_ORDER_PROPERTY property_id, // Property identifier
long& long_var // Here we assume the property value
);

Parameters

property_id

[in] Identifier property of order. The value can be one of the values of the enumeration ENUM_ORDER_PROPERTY_INTEGER.

long_var

[out] Variable of type long, the host value of the requested properties.

Returned Value

Value type long.


OrderGetString

MQL5 Reference / Trade functions / OrderGetString

OrderGetString

Returns the requested property warrants, pre-selected with the function OrderGetTicket or OrderSelect. The property warrants must be of type string. There are 2 variants of the function.

1. Immediately returns the property value.

string OrderGetString(
ENUM_ORDER_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool OrderGetString(
ENUM_ORDER_PROPERTY property_id, // Property identifier
string& string_var // Here we assume the property value
);

Parameters

property_id

[in] Identifier property of order. The value can be one of the values of the enumeration ENUM_ORDER_PROPERTY_STRING.

string_var

[out] Variable of type string, the host value of the requested properties.

Returned Value

Value type string.


HistorySelect

MQL5 Reference / Trade functions / HistorySelect

HistorySelect

Retrieves the history of transactions and orders for the specified period of time server.

bool HistorySelect(
datetime from_date, // From date
datetime to_date // To date
);

Parameters

from_date

[in] Start date of request.

to_date

[in] End date request.

Returned Value

Returns true if successful, otherwise false.


HistoryOrderSelect

MQL5 Reference / Trade functions / HistoryOrderSelect

HistoryOrderSelect

Selects in the history of the order for future references to it through the appropriate function. Return true if successful function. Returns false if it fails the function. To obtain information about the error, you need to call GetLastError().

bool HistoryOrderSelect(
ulong ticket // Order ticket
uint timeout=0 // Timeout in milliseconds
);

Parameters

ticket

[in] Order ticket.

Returned Value

Returns true if successful, otherwise false.

timeout=0

[in] Timeout value in milliseconds. Means the maximum time allowed to find the position of the specified order. If during the timeout choice order does not succeed, then the function returns false.

Note

If the function fails due to a timeout error will be generated 4757.


HistoryOrdersTotal

MQL5 Reference / Trade functions / HistoryOrdersTotal

HistoryOrdersTotal

Returns the number of orders in history.

int HistoryOrdersTotal();

Returned Value

Value type int.


HistoryOrderGetTicket

MQL5 Reference / Trade functions / HistoryOrderGetTicket

HistoryOrderGetTicket

Return ticket warrant in history.

ulong HistoryOrderGetTicket(
int index // Number in the list of orders
);

Parameters

index

[in] Number of the order in the list of orders.

Returned Value

Value type ulong.


HistoryOrderGetDouble

MQL5 Reference / Trade functions / HistoryOrderGetDouble

HistoryOrderGetDouble

Returns the requested property of the warrant. The property warrants must be of type double. There are 2 variants of the function.

1. Immediately returns the property value.

double HistoryOrderGetDouble(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool HistoryOrderGetDouble(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY property_id, // Property identifier
double& double_var // Here we assume the property value
);

Parameters

ticket_number

[in] Order ticket.

property_id

[in] Identifier property of order. The value can be one of the values of the enumeration ENUM_ORDER_PROPERTY_DOUBLE.

double_var

[out] Variable of type double, the host value of the requested properties.

Returned Value

Value type double.


HistoryOrderGetInteger

MQL5 Reference / Trade functions / HistoryOrderGetInteger

HistoryOrderGetInteger

Returns the requested property of the warrant. Property warrants must be of type datetime, int. There are 2 variants of the function.

1. Immediately returns the property value.

long HistoryOrderGetInteger(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool HistoryOrderGetInteger(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY property_id, // Property identifier
long& long_var // Here we assume the property value
);

Parameters

ticket_number

[in] Order ticket.

property_id

[in] Identifier property of order. The value can be one of the values of the enumeration ENUM_ORDER_PROPERTY_INTEGER.

long_var

[out] Variable of type long, the host value of the requested properties.

Returned Value

Value type long.


HistoryOrderGetString

MQL5 Reference / Trade functions / HistoryOrderGetString

HistoryOrderGetString

Returns the requested property of the warrant. The property warrants must be of type string. There are 2 variants of the function.

1. Immediately returns the property value.

string HistoryOrderGetString(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool HistoryOrderGetString(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY property_id, // Property identifier
string& string_var // Here we assume the property value
);

Parameters

ticket_number

[in] Order ticket.

property_id

[in] Identifier property of order. The value can be one of the values of the enumeration ENUM_ORDER_PROPERTY_STRING.

string_var

[out] Variable of type string, the host value of the requested properties.

Returned Value

Value type string.


HistoryDealSelect

MQL5 Reference / Trade functions / HistoryDealSelect

HistoryDealSelect

Selects in the history of the transaction for future reference it through the appropriate functions. Returns true if successful function. Returns false if it fails the function. To obtain information about the error, you need to call GetLastError().

bool HistoryDealSelect(
ulong ticket // Order ticket
uint timeout=0 // Timeout in milliseconds
);

Parameters

ticket

[in] Deal ticket.

Returned Value

Returns true if successful, otherwise false.

timeout=0

[in] Timeout value in milliseconds. Means the maximum time allowed to find the position of the specified deal. If during the timeout choice deal does not succeed, then the function returns false.

Note

If the function fails due to a timeout error will be generated 4757.


HistoryDealsTotal

MQL5 Reference / Trade functions / HistoryDealsTotal

HistoryDealsTotal

Returns the number of transactions in history.

int HistoryDealsTotal();

Returned Value

Value type int.


HistoryDealGetTicket

MQL5 Reference / Trade functions / HistoryDealGetTicket

HistoryDealGetTicket

Returns a ticket of a transaction in history.

ulong HistoryDealGetTicket(
int index // Deal ticket
);

Parameters

index

[in] Number of transactions in the list of transactions

Returned Value

Value type ulong.


HistoryDealGetDouble

MQL5 Reference / Trade functions / HistoryDealGetDouble

HistoryDealGetDouble

Returns the requested property transaction. Property transactions must be of type double. There are 2 variants of the function.

1. Immediately returns the property value.

double HistoryDealGetDouble(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool HistoryDealGetDouble(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY property_id, // Property identifier
double& double_var // Here we assume the property value
);

Parameters

ticket_number

[in] Trade ticket.

property_id

[in] Identifier property of trade. The value can be one of the values of the enumeration ENUM_DEAL_PROPERTY_DOUBLE.

double_var

[out] Variable of type double, the host value of the requested properties.

Returned Value

Value type double.


HistoryDealGetInteger

MQL5 Reference / Trade functions / HistoryDealGetInteger

HistoryDealGetInteger

Returns the requested property transaction. Property transactions must be of type datetime, int. There are 2 variants of the function.

1. Immediately returns the property value.

long HistoryDealGetInteger(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool HistoryDealGetInteger(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY property_id, // Property identifier
long& long_var // Here we assume the property value
);

Parameters

ticket_number

[in] Trade ticket.

property_id

[in] Identifier property of trade. The value can be one of the values of the enumeration ENUM_DEAL_PROPERTY_INTEGER.

long_var

[out] Variable of type long, the host value of the requested properties.

Returned Value

Value type long.


HistoryDealGetString

MQL5 Reference / Trade functions / HistoryDealGetString

HistoryDealGetString

Returns the requested property transaction. Property transactions must be of type string. There are 2 variants of the function.

1. Immediately returns the property value.

string HistoryDealGetString(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY property_id // Property identifier
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool HistoryDealGetString(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY property_id, // Property identifier
string& string_var // Here we assume the property value
);

Parameters

ticket_number

[in] Trade ticket.

property_id

[in] Identifier property of trade. The value can be one of the values of the enumeration ENUM_DEAL_PROPERTY_STRING.

string_var

[out] Variable of type string, the host value of the requested properties.

Returned Value

Value type string.


Global variables of the client terminal

MQL5 Reference / Global variables of the client terminal

Global variables of the client terminal

There is a set of functions developed to work with global variables.

Do not confuse the global variables of the client terminal with a variable declared atglobalmql5-program.

Global variables exist in the client terminal during 4 weeks since the last use, then automatically deleted. The use of global variable is not only setting a new value, but also read the value of the global variable.

Global variables of the client terminal are available simultaneously from all mql5-programs that are running on the client terminal.

Function | Action
GlobalVariableCheck | Checks the existence of a global variable with the specified name
GlobalVariableDel | Deletes the global variable
GlobalVariableGet | Returns the value of the global variable
GlobalVariableName | Returns the name of the global variable by it's ordinal number in the list of global variables
GlobalVariableSet | Sets the new value for the global variable
GlobalVariablesFlush | Forced save the global variables values to disk
GlobalVariableTemp | Sets the new value for the global variable, that exists only in the current session of the terminal
GlobalVariableSetOnCondition | Sets the new value of the existing global variable using by condition
GlobalVariablesDeleteAll | Deletes the global variables with the specified prefix in the name
GlobalVariablesTotal | Returns the total number of global variables


GlobalVariableCheck

MQL5 Reference / Global variables of the client terminal / GlobalVariableCheck

GlobalVariableCheck

Checks the existence of a global variable with the specified name and returns the time of its last modification.

datetime GlobalVariableCheck(
string name // Global variable name
);

Parameters

name

[in] Global variable name.

Returned Value

If successful, the function returns the last modification time, otherwise 0. To obtain an information about the error it is necessary to call the function GetLastError().

Note

Global variables exists in the client terminal during 4 weeks since the last use, then automatically deleted.


GlobalVariableDel

MQL5 Reference / Global variables of the client terminal / GlobalVariableDel

GlobalVariableDel

Deletes the global variable of the client terminal.

bool GlobalVariableDel(
string name // Global variable name
);

Parameters

name

[in] Global variable name.

Returned Value

If successful, the function returns true, otherwise it returns false. To obtain an information about the error it is necessary to call the function GetLastError().

Note

Global variables exists in the client terminal during 4 weeks since the last use, then automatically deleted.


GlobalVariableGet

MQL5 Reference / Global variables of the client terminal / GlobalVariableGet

GlobalVariableGet

Returns the value of the existing global variable of the client terminal. There are 2 variants of the function.

1. Immediately returns the value of the global variable.

double GlobalVariableGet(
string name // Global variable name
);

2. Returns true or false depending on the success of the function run. If successful, the global variable of the client terminal is placed in a variable passed by reference in the second parameter.

bool GlobalVariableGet(
string name // Global variable name
double& double_var // This variable will contain the value of the global variable
);

Parameters

name

[in] Global variable name.

double_var

[out] Target variable of type double, which will have the value of the global variable of the client terminal.

Returned Value

The value of the existing global variable or 0 if there was an error. To obtain an information about the error, you need to call GetLastError().

Note

Global variables exists in the client terminal during 4 weeks since the last use, then automatically deleted.


GlobalVariableName

MQL5 Reference / Global variables of the client terminal / GlobalVariableName

GlobalVariableName

Returns the name of the global variable by it's ordinal number.

string GlobalVariableName(
int index // Global variable number in the global variables list
);

Parameters

index

[in] Sequence number in the list of global variables. It should be greater or equal 0 and less than GlobalVariablesTotal() .

Returned Value

Global variable name by it's ordinal number in the list of the global variables. To obtain an information about the error, it is necessary to call GetLastError().

Note

Global variables exists in the client terminal during 4 weeks since the last use, then automatically deleted.


GlobalVariableSet

MQL5 Reference / Global variables of the client terminal / GlobalVariableSet

GlobalVariableSet

Sets the new value for the global variable. If variable does not exist, the system creates a new global variable.

datetime GlobalVariableSet(
string name, // Global variable name
double value // Value to set
);

Parameters

name

[in] Global variable name.

value

[in] The new numerical value.

Returned Value

If successful, the function returns the last modification time, otherwise 0. To obtain an information about the error it is necessary to call the function GetLastError().

Note

Global variables exists in the client terminal during 4 weeks since the last use, then automatically deleted.


GlobalVariablesFlush

MQL5 Reference / Global variables of the client terminal / GlobalVariablesFlush

GlobalVariablesFlush

Forced save the global variables values to disk.

void GlobalVariablesFlush(
string name, // Global variable name
);

Parameters

name

[in] Global variable name.

Returned Value

No return value.

Note

The terminal itself writes all of the global variables at the end of work, but computer data could be lost in the case of the sudden failure. This function allows you to control the process of maintaining global variables for contingency situations.


GlobalVariableTemp

MQL5 Reference / Global variables of the client terminal / GlobalVariableTemp

GlobalVariableTemp

Attempts to create a temporary global variable. If the variable doesn't exist, the system creates a new temporary global variable.

bool GlobalVariableTemp(
string name, // Global variable name
);

Parameters

name

[in] The name of a temporary global variable.

Returned Value

If successful, the function returns true, otherwise false. To obtain an information about the error it is necessary to call the function GetLastError().

Note

The temporary global variables exists only while the client terminal run, after the closure of the terminal, they are automatically destroyed. Note that function GlobalVariablesFlush() does not saving on disk the temporary global variables.

After creation of the temporary global variable, an access and it's modification are the same as for global variable of the client terminal.


GlobalVariableSetOnCondition

MQL5 Reference / Global variables of the client terminal / GlobalVariableSetOnCondition

GlobalVariableSetOnCondition

Sets the new value of the existing global variable, if the current value equals to the value of the third parameter check_value. If the variable does not exist, the function will generate an error ERR_GLOBALVARIABLE_NOT_FOUND (4501) and returns false.

bool GlobalVariableSetOnCondition(
string name, // Global variable name
double value, // New value for variable if condition is true
double check_value // Check value condition
);

Parameters

name

[in] The name of global variable.

value

[in] New value.

check_value

[in] The value to check the current value of global variable.

Returned Value

If successful, the function returns true, otherwise false. To obtain an information about the error it is necessary to call the function GetLastError(). If current value of the global variable is different from check_value, the function returns false.

Note

Function provides an atomic access to a global variable, so it can be used to organize the semaphore in the interaction of several concurrent experts within one client terminal.


GlobalVariablesDeleteAll

MQL5 Reference / Global variables of the client terminal / GlobalVariablesDeleteAll

GlobalVariablesDeleteAll

Deletes the global variables of the client terminal.

int GlobalVariablesDeleteAll(
string prefix_name=NULL // All global variables whose names begin with the prefix
datetime limit_data=0 // All global variables, which were changed earlier before this date
);

Parameters

prefix_name=NULL

[in] name prefix for removal global variables. If you specify a prefix NULL or empty string, then a criterion for removal consistent with all global variables, the relevant criterion for removal date.

limit_data=0

[in] The date for the selection of global variables by time of last modification. The function removes global variables, which were changed earlier before this date. If the parameter is zero, then delete all the global variables corresponding to the first criterion (a prefix).

Returned Value

The number of deleted variables.

Note

If both options are equal to zero (prefix_name = NULL and limit_data = 0), then function deletes all global variables of the terminal. If both parameters specified, then it deletes global variables corresponding simultaneously to each of these parameters.

Global variables exists in the client terminal 4 weeks since the last use, then automatically deleted.


GlobalVariablesTotal

MQL5 Reference / Global variables of the client terminal / GlobalVariablesTotal

GlobalVariablesTotal

Returns the total number of global variables of the client terminal.

int GlobalVariablesTotal();

Returned Value

Number of global variables.

Note

Global variables exists in the client terminal 4 weeks since the last use, then automatically deleted. The use of the global variable is not only setting a new value, but also read the value of the global variable.


File operations

MQL5 Reference / File operations

File operations

With functions for working with files.

There are two directories (with subdirectories), which can be located working files:

· terminal_path/MQL5/FILES (select to view in the terminal menu item "File" - "Open the data directory");
· all shared folder on your computer terminals - usually located in the directory C: \ Documents and Settings \ All Users \ Application Data \ MetaQuotes \ Terminal \ Common.

Program can be obtained through the names of the directories using the TerminalInfoString() using enumeration ENUM_TERMINAL_INFO_STRING:

//--- Folder that stores the data terminal
string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH);
//--- Shared folder for all client terminals
string common_data_path=TerminalInfoString(TERMINAL_COMMONDATA_PATH);

Work with files from other directories will be stopped.

Function | Action
FileFindFirst | Start the Bust of files in a directory in accordance with the specified filter
FileFindNext | Continues the search begun function FileFindFirst ()
FileFindClose | Closes handle search
FileOpen | Opens a file with the specified name and the flag
FileDelete | Deletes the specified file
FileFlush | Flush any data remaining in the file I / O buffer
FileIsEnding | Defines the end of the file in the process of reading
FileIsLineEnding | Defines the end of the line in a text file in the process of reading
FileClose | Closes a previously opened file
FileIsExist | Checks existence of file
FileCopy | Copies the original file from a local or shared folder to another file
FileMove | Moves or renames a file
FileReadArray | Reads from the file type BIN arrays of any type except string
FileReadBool | Reads from the file type CSV string from the current situation to a separator (or until the end of a line of text) and converts the read string to a value of type bool
FileReadDatetime | Reads from the file type CSV string of one of the formats: "YYYY.MM.DD HH: MI: SS", "YYYY.MM.DD" or "HH: MI: SS" - and converts it into a datetime value
FileReadDouble | Reads from the current position file pointer value of type double
FileReadFloat | Reads from the current position file pointer value of type float
FileReadInteger | Reads from the current position file pointer value of type int, short, or char
FileReadLong | Reads from the current position file pointer value of type long
FileReadNumber | Reads from the file type CSV string from the current situation to a separator (or until the end of a line of text) and converts the read string to double value
FileReadString | Reads from a file line with the current position file pointer
FileReadStruct | Reads from a binary file contents in the structure passed as a parameter, with the current position file pointer
FileSeek | Moves the position of file pointer a specified number of bytes relative to the specified position
FileSize | Returns the size of the open file
FileTell | Returns the current position of file pointer of the open file
FileWrite | Writes data to a file type of CSV or TXT
FileWriteArray | Writes the file type BIN arrays of any type except string
FileWriteDouble | Writes a binary value of type double from the current position file pointer
FileWriteFloat | Writes a binary value of type float with the current position file pointer
FileWriteInteger | Writes a binary value of type int with the current position file pointer
FileWriteLong | Writes a binary value of type long with the current position file pointer
FileWriteString | Writes the file type BIN or TXT value of type string with the current position file pointer
FileWriteStruct | Writes to a binary file content, structure, passed as a parameter, with the current position file pointer
FolderCreate | Creates a directory in the folder Files (depending on the value common_flag)
FolderDelete | Removes the specified directory. If the folder is not empty, then it can not be removed
FolderClean | Deletes all files in the specified folder

If the file is opened for writing using the FileOpen(), Then all the way specified in sub-folders will be created in their absence.


FileFindFirst

MQL5 Reference / File operations / FileFindFirst

FileFindFirst

Start the Bust of files in a directory in accordance with the specified filter.

int FileFindFirst(
string file_filter, // String - search filter
string& returned_filename, // Name of the file found
int common_flag // Defines the search
);

Parameters

file_filter

[in] Filter search. In the filter may be specified subdirectory (or a sequence of nested subdirectories) on the directory \ Files, in which you want to bust files.

returned_filename

[out] The returned parameter, which in case of success placed the name of the first file found.

common_flag

[in] Flag, determining the location of the file. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder.

Returned Value

Returns Handle object of search, which should be used for further sorting files function FileFindNext() or INVALID_HANDLE when there is no file corresponding to the filter (in the particular case - the directory is empty). After searching Handle must be closed using function FileFindClose().

Example:

void OnStart()
{
string filename;
//---
int found=FileFindFirst("*.*",filename);
if(found!=INVALID_HANDLE)
Print("FileFindFirst returned",filename);
else
{
Print("Files not found!!! Continue search in Common");
found=FileFindFirst("*.*",filename,FILE_COMMON);
if(found!=INVALID_HANDLE)
Print("FileFindFirst in Common returned",filename);
}
}

See also


FileFindNext

MQL5 Reference / File operations / FileFindNext

FileFindNext

Continues the search begun function FileFindFirst().

bool FileFindNext(
int search_handle, // Search handle
string& returned_filename // Name of the file found
);

Parameters

search_handle

[in] Search handle, retrieval function FileFindFirst().

returned_filename

[out] The name of the next file or directory found.

Returned Value

If successful returns true, otherwise false.

Example:

void OnStart()
{
string filename;
int i=0;
//---
int search=FileFindFirst("*.*",filename);
if(search!=INVALID_HANDLE)
{
Print("FileFindFirst returned",filename);
while(FileFindNext(search,filename))
{
i++;
Print(i,":",filename);
}
FileFindClose(filename);
}
else
Print("Files not found!!!");
}

See also

FileFindFirst, FileFindClose


FileFindClose

MQL5 Reference / File operations / FileFindClose

FileFindClose

Close search hadle.

void FileFindClose(
int search_handle // Search handle
);

Parameters

search_handle

[in] Search handle, retrieval function FileFindFirst().

Returned Value

No return value.

Note

Function must be called to free system resources.


FileIsExist

MQL5 Reference / File operations / FileIsExist

FileIsExist

Checks the existence of a file.

bool FileIsExist(
string file_name, // File name
int common_flag=0 // Search area
);

Parameters

file_name

[in] The name of the file being checked

common_flag=0

[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder.

Returned Value

Returns true, if the specified file exists.

Note

If common_flag = FILE_COMMON, then the function looks for the file in a shared folder for all client terminals, otherwise the function looks for a file to a local folder (MQL5 \ Files or MQL5 \ Tester \ Files in the case of testing).


FileOpen

MQL5 Reference / File operations / FileOpen

FileOpen

The function opens the file with the specified name and the flag.

int FileOpen(
string file_name, // File name
int open_flags, // Combination of flags
short delimiter='\t' // Separator
);

Parameters

file_name

[in] The name of the file can contain subfolders. If the file is opened for writing, then these subfolders will be created in their absence.

open_flags

[in] combination of flags determining the mode of the file. The flags are defined as follows:
FILE_READ file is opened for reading
FILE_WRITE file open for writing
FILE_BIN binary read-write mode (no conversion from a string and a string)
FILE_CSV file type csv (all recorded items are converted to the strings of the type, unicode or ansi, and are separated by a delimiter)
FILE_TXT a simple text file (the same as csv, but the separator is not taken into account)
FILE_ANSI string like ANSI (single-byte characters)
FILE_UNICODE line type UNICODE (double-byte characters)
FILE_SHARE_READ shared reading from several programs
FILE_COMMON location of the file in a shared folder for all client terminals

delimiter='\t'

[in] 2value to be used as a separator in txt or csv-file.If the csv-file delimiter is not specified, it defaults to a tab.If the txt-file delimiter is not specified, then no separator is not used.If the separator is clearly set to 0, then no separator is not used.

Returned Value

If successful, the function returns a handle to open the file, which is then used to access the data file. In case of failure returns INVALID_HANDLE.

Note

This opens the file in the folder of the client terminal in a subfolder MQL5\files (or MQL5\tester\files in the case of testing).If among the flags specified FILE_COMMON, then the file is opened in a shared folder for all client terminals MetaTrader5.


FileClose

MQL5 Reference / File operations / FileClose

FileClose

Close the file previously opened by FileOpen() .

void FileClose(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen ().

Returned Value

No return value.


FileCopy

MQL5 Reference / File operations / FileCopy

FileCopy

Copies the original file from a local or shared folder to another file.

bool FileCopy(
string src_filename, // Name of the source file
int common_flag, // Locale
string dst_filename, // Name of the destination file
int mode_flags // Access mode
);

Parameters

src_filename

[in] File name to copy.

common_flag

[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder.

dst_filename

[in] Result file name .

mode_flags

[in] Access flags. The parameter can contain only 2 flags: FILE_REWRITE and / or FILE_COMMON - other flags are ignored.If the file already exists and was not there at the flag FILE_REWRITE, then the file will not be rewritten, and the function returns false.

Returned Value

In case of failure the function returns false.

Note

If the new file there, then the copy will be made depending on the availability of the flag in FILE_REWRITE parameter mode_flags.


FileDelete

MQL5 Reference / File operations / FileDelete

FileDelete

Delete Deletes the specified file to a local folder of the client terminal.

bool FileDelete(
string file_name // File name to delete
int common_flag=0 // Location of the deleted file
);

Parameters

file_name

[in] File name.

common_flag=0

[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder.

Returned Value

In case of failure the function returns false.

Note

Deletes the specified file to a local folder of the client terminal (MQL5\files or MQL5\tester\files in the case of testing). If specified common_flag = FILE_COMMON, then the function removes the file from the shared folder for all client terminals.


FileMove

MQL5 Reference / File operations / FileMove

FileMove

Moves a file from a local or shared folder to another folder.

int FileMove(
string src_filename, // File name for the move operation
int common_flag, // Location
string dst_filename, // Name of the destination file
int mode_flags // Access mode
);

Parameters

src_filename

[in] name of file name for the move / rename.

common_flag

[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then the file is located in a shared folder for all client terminals. Otherwise, the file is located in a local folder.

dst_filename

[in] File name after operation

mode_flags

[in] Access flags. The parameter can contain only 2 flags: FILE_REWRITE and / or FILE_COMMON - other flags are ignored.If the file already exists and was not there at the flag FILE_REWRITE, then the file will not be rewritten, and the function returns false.

Returned Value

In case of failure the function returns false.

Note

If a new file there, then the copy will be made depending on the availability of the flag FILE_REWRITE in parameter mode-flags.


FileFlush

MQL5 Reference / File operations / FileFlush

FileFlush

Flush any data remaining in the file I/O buffer.

void FileFlush(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

No return value.

Note

Function FileFlush () must be called between the operations of reading from a file and write to a file.


FileIsEnding

MQL5 Reference / File operations / FileIsEnding

FileIsEnding

Defines the end of the file in the process of reading.

bool FileIsEnding(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

The function returns true if in the process of reading or move the file pointer past the end of the file.


FileIsLineEnding

MQL5 Reference / File operations / FileIsLineEnding

FileIsLineEnding

Defines the end of the line in a text file in the process of reading.

bool FileIsLineEnding(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

Returns true if in the process of reading txt or csv-file reached the end of the line (the characters CR-LF).


FileReadArray

MQL5 Reference / File operations / FileReadArray

FileReadArray

Reads from a file of type BIN arrays of any type except string (may be an array of structures, not containing strings and dynamic arrays).

uint FileReadArray(
int file_handle // File handle
void array[], // Array to record
int start_item=0, // With what position the array to write
int items_count=-1 // How many to read
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

array[]

[out] An array where the data will be loaded.

start_item=0

[in] Start position to write to the array.

items_count=-1

[in] Number of elements to read.

Returned Value

Number of read.

Note

String array can be read only from the file type TXT. If necessary, the function tries to increase the size of the array.

See also

Variables


FileReadBool

MQL5 Reference / File operations / FileReadBool

FileReadBool

Reads from the file type CSV string from the current situation to a separator (or until the end of a line of text) and converts the read string to a value of type bool.

bool FileReadBool(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

Line read may be set to "true", "false" or the symbolic representation of integers "0" or "1".A nonzero value is converted to a logical true.The function returns the converted value.

See also

Type bool


FileReadDatetime

MQL5 Reference / File operations / FileReadDatetime

FileReadDatetime

Reads from the file type CSV string of one of the formats: "YYYY.MM.DD HH: MI: SS", "YYYY.MM.DD" or "HH: MI: SS" - and converts it into a value of type datetime.

datetime FileReadDatetime(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

The value of type datetime.

See also

Type datetime, StringToTime, TimeToString


FileReadDouble

MQL5 Reference / File operations / FileReadDouble

FileReadDouble

Reads a double-precision floating point (double) from the current position of the binary file.

double FileReadDouble(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

The value of type double.

Note

To obtain information about the error, you need to call GetLastError().

See also

Real types (double, float), StringToDouble, DoubleToString


FileReadFloat

MQL5 Reference / File operations / FileReadFloat

FileReadFloat

Reads the number of single-precision floating point (float) from the current position of the binary file.

float FileReadFloat(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

The value of type float.

Note

To obtain information about the error, you need to call GetLastError().

See also

Real types (double, float), FileReadDouble


FileReadInteger

MQL5 Reference / File operations / FileReadInteger

FileReadInteger

Reads from the current position file pointer value of type int, short, or char, depending on the length specified in bytes.

int FileReadInteger(
int file_handle // File handle
int size=INT_VALUE // Size of an integer in bytes
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

size=INT_VALUE

[in] Number of bytes (up to 4 inclusive), who need to write.Provision appropriate constants: CHAR_VALUE = 1, SHORT_VALUE = 2 and INT_VALUE = 4, so the function can read the whole value of type char, short or int.

Returned Value

The value of type int.Since the return value of type int, then it can safely be converted to any integer, signed or unsigned, the value.File pointer is positioned on the number of bytes read by a type.

See also

IntegerToString, StringToInteger, Integer types


FileReadLong

MQL5 Reference / File operations / FileReadLong

FileReadLong

Reads an integer type long (8 bytes) from the current position of the binary file.

long FileReadLong(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

The value of type long.

See also

Integer types, FileReadInteger


FileReadNumber

MQL5 Reference / File operations / FileReadNumber

FileReadNumber

Reads from the file type CSV string from the current situation to a separator (or until the end of a line of text) and converts the read string to a value of type double.

double FileReadNumber(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

The value of type double.


FileReadString

MQL5 Reference / File operations / FileReadString

FileReadString

Reads from a file line with the current status of the file pointer.

string FileReadString(
int file_handle // File handle
int size=-1 // Length of string
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

size=-1

[in] Number of characters to read.

Returned Value

Line read (string).

Note

When reading from a bin-file must specify the length of the readable string.When reading from a txt-file line length are not required to be read a string from the current position to sign newline "\ r \ n".When reading from a csv-file line length as you do not need to be read by a string from the current situation to the next delimiter or sign up to the end of the text string.

If the file is opened with flag FILE_ANSI, then the line read is converted to Unicode.

See also

Type string, Data Conversion


FileReadStruct

MQL5 Reference / File operations / FileReadStruct

FileReadStruct

Read the bin-file contents in the structure passed as a parameter, with the current status of the file pointer.

uint FileReadStruct(
int file_handle // File handle
any_simple_struct str_object, // Structure, which are read
int size=-1 // Structure size in bytes
);

Parameters

file_handle

[in] File descriptor open bin-file.

str_object

[out] The object of this structure. The structure should not contain line, dynamic arrays and virtual functions.

size=-1

[in] Number of bytes that you want to read. If size is not specified or indicated greater than the size of the structure of the number of bytes, it uses the exact size of this structure.

Returned Value

If successful the function returns the number of bytes read. File pointer is positioned on the same number of bytes.

See also

Structures and classes


FileSeek

MQL5 Reference / File operations / FileSeek

FileSeek

Moves the position of file pointer a specified number of bytes relative to the specified position.

bool FileSeek(
int file_handle // File handle
int offset, // In bytes
ENUM_FILE_POSITION origin // Position for reference
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

offset

[in] The offset in bytes (may take a negative value).

origin

[in] The starting point for the displacement.

Returned Value

In the case of a successful movement returns true, otherwise false.


FileSize

MQL5 Reference / File operations / FileSize

FileSize

Returns the file size in bytes.

int FileSize(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

The value of type int.

Note

To obtain information on error need to call GetLastError().


FileTell

MQL5 Reference / File operations / FileTell

FileTell

Returns the current position of file pointer of the opened file.

int FileTell(
int file_handle // File handle
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

Returned Value

Current position of file descriptor in bytes from the beginning of the file.

Note

To obtain information on error need to call GetLastError().


FileWrite

MQL5 Reference / File operations / FileWrite

FileWrite

Writing data to a file type of CSV or TXT, the separator between the data is inserted automatically if it is not equal to 0. After recording a file is added to the row terminator "\r\n".

uint FileWrite(
int file_handle // File handle
... // List of recorded parameters
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

...

[in] the list of parameters separated by commas, to write to the file. The number displayed in the parameter file should not exceed 63.

Returned Value

Number of characters written.

Note

In the derivation of numeric data is converted into text format (cm.function Print ()).Data type double output with an accuracy of 16 digits after the decimal point, and the data can be displayed either in traditional or in scientific format - depending on how the record will be the most compact.The data type float are shown with 5 digits after the decimal point.To derive the real numbers with different precision or clearly specified format must use the DoubleToString().

Numbers of type bool are displayed as strings "true" or "false". Numbers are displayed in a datetime format "YYYY.MM.DD HH: MI: SS".

See also

Comment, Print, StringFormat


FileWriteArray

MQL5 Reference / File operations / FileWriteArray

FileWriteArray

Writes a file of type BIN arrays of any type except string (may be an array of structures, not containing strings and dynamic arrays).

int FileWriteArray(
int file_handle // File handle
void array[], // Array
int start_item=0, // Start index in the array
int items_count=-1 // Number of elements
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

array[]

[out] Array for recording.

start_item=0

[in] Initial index in the array (number of the first recording element).

items_count=-1

[in] Number of items to record(that means -1 is unknown).

Returned Value

Number of recorded items.

Note

String array can be recorded in a file type TXT. In this case, the line was automatically ended the end of line characters "\r\n". Depending on the type of file ANSI or UNICODE, strings are converted to ansi-encoding or not.

See also

Variables


FileWriteDouble

MQL5 Reference / File operations / FileWriteDouble

FileWriteDouble

Writes to the file parameter of type double from the current position of the file pointer.

uint FileWriteDouble(
int file_handle // File handle
double dvalue // Value to write
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

dvalue

[in] The value of type double.

Returned Value

If successful the function returns the number of bytes written (in this case sizeof(double) = 8). File pointer is positioned on the same number of bytes.

See also

Real types (double, float)


FileWriteFloat

MQL5 Reference / File operations / FileWriteFloat

FileWriteFloat

Write to the bin-file value of a float with the current status of the file pointer.

uint FileWriteFloat(
int file_handle // File handle
float fvalue // Value to be written
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

fvalue

[in] The value of type float.

Returned Value

If successful the function returns the number of bytes written (in this case sizeof(float) = 4). File pointer is positioned on the same number of bytes.

See also

Real types (double, float), FileWriteDouble


FileWriteInteger

MQL5 Reference / File operations / FileWriteInteger

FileWriteInteger

Write to the bin-file parameter of type int with the current status of the file pointer.

uint FileWriteInteger(
int file_handle // File handle
int ivalue, // Value to be written
int size=INT_VALUE // Size in bytes
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

ivalue

[in] Integer value.

size=INT_VALUE

[in] Number of bytes (up to 4 inclusive), who need to write.Provision appropriate constants: CHAR_VALUE = 1, SHORT_VALUE = 2 and INT_VALUE = 4, so the function can write the integer value of type char, uchar, short, ushort, int, or uint.

Returned Value

If successful the function returns the number of bytes written. File pointer is positioned on the same number of bytes. bytes.

See also

IntegerToString, StringToInteger, Integer types


FileWriteLong

MQL5 Reference / File operations / FileWriteLong

FileWriteLong

Write to the bin-file parameter of type long with the current status of the file pointer.

uint FileWriteLong(
int file_handle // File handle
long lvalue // Value to be written
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

lvalue

[in] Value of type long.

Returned Value

If successful the function returns the number of bytes written (in this case sizeof(long) = 8). File pointer is positioned on the same number of bytes.

See also

Integer types, FileWriteInteger


FileWriteString

MQL5 Reference / File operations / FileWriteString

FileWriteString

Writes the file type BIN or TXT value of type string with the current position file pointer.When writing to a file type TXT if there is a symbol in the string '\n' (LF) without previous character '\r' (CR), then before the symbol '\n' appended missing character '\r'.

uint FileWriteString(
int file_handle // File handle
string svalue, // Write string
int size=-1 // Number of characters
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

svalue

[in] String.

size=-1

[in] The number of characters that you want to write.This option is needed to record the line in a file of type BIN.If size is not specified, then recorded the entire string without the trailing 0.If you specify a size smaller than the length of the string, then writes the string without the trailing 0.If you specify a size greater than the length of the string, the string is appended the appropriate number of zeros.For files of type TXT, this parameter is ignored and the string is written entirely.

Returned Value

If successful the function returns the number of bytes written. File pointer is positioned on the same number of bytes.

Note

It should be borne in mind that when writing to a file opened with flag FILE_UNICODE (or without a flag FILE_ANSI), then the number of bytes written will be 2 times the number of characters written lines. When recording in a file opened with the flag FILE_ANSI, the number of bytes written to coincide with the number of characters written lines.

See also

Type string, StringFormat


FileWriteStruct

MQL5 Reference / File operations / FileWriteStruct

FileWriteStruct

Writes the bin-file content, structure, passed as a parameter, with the current status of the file pointer.

uint FileWriteStruct(
int file_handle // File handle
any_simple_struct str_object&, // Reference to object
int size // Write size in bytes
);

Parameters

file_handle

[in] File descriptor returned by FileOpen().

str_object&

[in] Reference to the object of this structure. The structure should not contain line, dynamic arrays and virtual functions.

size

[in] Number of bytes that you want to record. If size is not specified or indicated greater than the size of the structure of the number of bytes written to the entire structure completely.

Returned Value

If successful the function returns the number of bytes written. File pointer is positioned on the same number of bytes.

See also

Structures and classes


FolderCreate

MQL5 Reference / File operations / FolderCreate

FolderCreate

Creates a directory in the folder Files (depending on the value common_flag)

bool FolderCreate(
string folder_name, // String with the name of new folder
int common_flag=0 // Scope
);

Parameters

folder_name

[in] The name of the directory you want to create. Contains the full path to the folder.

common_flag=0

[in] Flag determining the location of the directory. If common_flag = FILE_COMMON, then the directory is in the shared folder for all client terminals. Otherwise, the directory is in a local folder(MQL5 \ files or MQL5 \ tester \ files in the case of testing).

Returned Value

Returns true if successful, otherwise false.


FolderDelete

MQL5 Reference / File operations / FolderDelete

FolderDelete

Removes the specified directory. If the folder is not empty, then it can not be removed.

bool FolderDelete(
string folder_name, // String with the name of the deleted folder
int common_flag=0 // Scope
);

Parameters

folder_name

[in] The name of the directory you want to delete. Contains the full path to the folder.

common_flag=0

[in] Flag determining the location of the directory. If common_flag = FILE_COMMON, then the directory is in the shared folder for all client terminals. Otherwise, the directory is in a local folder(MQL5\files or MQL5\tester\files in the case of testing).

Returned Value

Returns true if successful, otherwise false.

Note

If the directory contains at least one file and/or a directory, then delete this directory is not possible, it must first clean.Total clearance of all files, folders and all nested subfolders made using the function FolderClean().


FolderClean

MQL5 Reference / File operations / FolderClean

FolderClean

Deletes all files in that folder.

bool FolderClean(
string folder_name, // String with the name of the deleted folder
int common_flag=0 // Scope
);

Parameters

folder_name

[in] The name of the directory where you want to delete all files. Contains the full path to the folder.

common_flag=0

[in] Flag determining the location of the directory. If common_flag = FILE_COMMON, then the directory is in the shared folder for all client terminals. Otherwise, the directory is in a local folder(MQL5\files or MQL5\tester\files in the case of testing).

Returned Value

Returns true if successful, otherwise false.

Note

Caution to use this feature, since all the files and all subdirectories are deleted forever.


Custom Indicators

MQL5 Reference / Custom Indicators

Custom Indicators

Group functions used in the design of custom indicators. These functions can not be used when writing advisors and scripts.

Function | Action
SetIndexBuffer | Associates the specified indicator buffer with one-dimensional dynamic array type double
IndicatorSetDouble | Specifies the property value of the indicator of the type double
IndicatorSetInteger | Specifies the property value of the indicator of the type int
IndicatorSetString | Specifies the property value of the indicator of the type string
PlotIndexSetDouble | Sets the value of the property line of the indicator of the type double
PlotIndexSetInteger | Sets the value of the property line of the indicator of the type int
PlotIndexSetString | Sets the value of the property line of the indicator of the type int
PlotIndexGetInteger | Returns the value of the property line of the indicator, which has integer type

All the necessary calculations custom indicator must be placed in a predetermined function OnCalculate(). If you use a short form of the function call OnCalculate () type

int OnCalculate (const int rates_total, const int prev_calculated, const int begin, const double& price[])

the variable rates_total contains the value of the total number of elements of the array price [], passed as an input parameter for calculating the indicator values.

Parameter prev_calculated- The result of a function OnCalculate () on the previous call and can arrange economical algorithm for calculating the indicator values. For example, if the current value rates_total = 1000,prev_calculated = 999, then perhaps it is sufficient to make calculations only for one value of each indicator buffer.

If the information about the size of the array of input price would have been available, then it led to the need to make calculations for the 1000 values of each indicator buffer. When you first call the function OnCalculate() value prev_calculated = 0. If the array price [] in any way changed, then in this case prev_calculated also equal to 0.

For example, consider a simple indicator: Parameter begin reports the number of initial values of the array price, which does not contain data for the calculation.For example, if the input array have been used indicator values Accelerator Oscillator (for which the first 37 values are not calculated), then begin = 37.For example, consider a simple indicator:.

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Label1
#property indicator_label1 "Label1"
#property indicator_type1 DRAW_LINE
#property indicator_color1 Red
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- indicator buffers
double Label1Buffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[])

{
//---
Print("begin =",begin," prev_calculated =",prev_calculated," rates_total =",rates_total);
//--- return value of prev_calculated for next call
return(rates_total);
}

Drag him out the window "Navigator" on the indicator window Accelerator Oscillator and we note that the settlements will be made on the previous values of the indicator:

As a result, the first call to OnCalculate () valueprev_calculated will be equal to zero, and in subsequent calls it will be equal to the value rates_total (up until not increase the number of bars on the price chart).

The value begin to be exactly equal to the number of primary bars, for which the values of the indicator Accelerator is not calculated in accordance with the logic of this indicator.If we look at the source code of the custom indicator Accelerator.mq5, we see in the function.OnInit() these lines:

//--- sets first bar from what index will be drawn
PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,37);

This function PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, empty_first_values), we report the number of minor first values in the zero indicator arrays custom indicator that we do not need to take to the calculations (empty_first_values).Thus, we have the mechanisms to:

1. indicate the number of initial values of the indicator, which should not be used for calculations in another user's display;
2. information on the number of first values to be ignored when you call another custom indicator, without going into the logic of his calculations.


SetIndexBuffer

MQL5 Reference / Custom Indicators / SetIndexBuffer

SetIndexBuffer

Associates the specified indicator buffer with one-dimensional dynamic array type double announced at global level.

bool SetIndexBuffer(
int index, // Index buffer
double buffer[], // Array
ENUM_INDEXBUFFER_TYPE data_type // That will store
);

Parameters

index

[in] Number of the indicator buffer. The numbering starts with 0. Number must be less than the value declared in the#property indicator_buffers.

buffer[]

[in] An array declared in the program custom indicator.

data_type

[in] Type of data stored in the indicator array. Default INDICATOR_DATA(values calculated indicator). May also take the value INDICATOR_COLOR_INDEX, Then this buffer is used to store color indexes for the previous indicator buffer. You can specify up to 64 colors in line #property indicator_colorN. Value INDICATOR_CALCULATIONS means that the buffer is involved in the intermediate calculations of the indicator and is not intended for rendering.

Returned Value

If successful, returns true, otherwise false.

Note

After binding a dynamic array buffer[] will be indexed as in conventional arrays, even if the bound of the array will be pre-installed as an index of timeseries. If you want to change the order of access to elements of the indicator array must use the function ArraySetAsSeries().

Example:

//+------------------------------------------------------------------+
//| TestCopyBuffer1.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot MA
#property indicator_label1 "MA"
#property indicator_type1 DRAW_LINE
#property indicator_color1 Red
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input bool AsSeries=true;
input int period=15;
input ENUM_MA_METHOD smootMode=MODE_EMA;
input ENUM_APPLIED_PRICE price=PRICE_CLOSE;
input int shift=0;
//--- indicator buffers
double MABuffer[];
int ma_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
if(AsSeries) ArraySetAsSeries(MABuffer,true);
Print("Indicator buffer is timeseries =",ArrayGetAsSeries(MABuffer));
SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
Print("Indicator buffer after SetIndexBuffer() is timeseries =",
ArrayGetAsSeries(MABuffer));

//--- Change the order of access to elements of the indicator buffer
ArraySetAsSeries(MABuffer,AsSeries);

IndicatorSetString(INDICATOR_SHORTNAME,"MA("+period+")"+AsSeries);
//---
ma_handle=iMA(Symbol(),0,period,shift,smootMode,price);
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- Copy the values of the moving average in the buffer MABuffer
int copied=CopyBuffer(ma_handle,0,0,rates_total,MABuffer);

Print("MABuffer[0] =",MABuffer[0]);// Depending on the value AsSeries
// Will receive a very old value
// Or for the current unfinished bar

//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+

See also

Properties custom indicators, Access to timeseries and indicators


IndicatorSetDouble

MQL5 Reference / Custom Indicators / IndicatorSetDouble

IndicatorSetDouble

Sets the value of the properties of the indicator.Property of the indicator should be of type double.There are 2 variants of the function.Sets the value of the properties of the indicator.Property of the indicator should be a double.There are 2 variants of the function.

Call indicating identifier properties.

bool IndicatorSetDouble(
int prop_id, // Identifier
double prop_value // Set the value
);

Calling indicating the identifier and modifier properties.

bool IndicatorSetDouble(
int prop_id, // Identifier
int prop_modifier, // Modifier
double prop_value // Set the value
)

Parameters

prop_id

[in] The value can be one of the values of the enumeration ENUM_CUSTOMIND_PROPERTY_DOUBLE.

prop_modifier

[in] Modifier specified property. Only the properties of the levels require a modifier.

prop_value

[in] The value of the property.

Returned Value

If successful, returns true, otherwise false.


IndicatorSetInteger

MQL5 Reference / Custom Indicators / IndicatorSetInteger

IndicatorSetInteger

Sets the value of the properties of the indicator. Property of the indicator should be an int or color. There are 2 variants of the function.

Call indicating identifier properties.

bool IndicatorSetInteger(
int prop_id, // Identifier
int prop_value // Set the value
);

Calling indicating the identifier and modifier properties.

bool IndicatorSetInteger(
int prop_id, // Identifier
int prop_modifier, // Modifier
int prop_value // Set the value
)

Parameters

prop_id

[in] The value can be one of the values of the enumeration ENUM_CUSTOMIND_PROPERTY_INTEGER.

prop_modifier

[in] Modifier specified property. Only the properties of the levels require a modifier.

prop_value

[in] The value of the property.

Returned Value

If successful, returns true, otherwise false.


IndicatorSetString

MQL5 Reference / Custom Indicators / IndicatorSetString

IndicatorSetString

Sets the value of the properties of the indicator. Property of the indicator should be of type string. There are 2 variants of the function.

Call indicating identifier properties.

bool IndicatorSetString(
int prop_id, // Identifier
string prop_value // Set the value
);

Calling indicating the identifier and modifier properties.

bool IndicatorSetString(
int prop_id, // Identifier
int prop_modifier, // Modifier
string prop_value // Set the value
)

Parameters

prop_id

[in] The value can be one of the values of the enumeration ENUM_CUSTOMIND_PROPERTY_STRING.

prop_modifier

[in] Modifier specified property. Only the properties of the levels require a modifier.

prop_value

[in] The value of the property.

Returned Value

If successful, returns true, otherwise false.


PlotIndexSetDouble

MQL5 Reference / Custom Indicators / PlotIndexSetDouble

PlotIndexSetDouble

Sets the value of the properties of the corresponding line of the indicator. Property of the indicator should be a double.

bool PlotIndexSetDouble(
int plot_index, // Plot index
int prop_id, // Property identifier
double prop_value // Set the value
);

Parameters

plot_index

[in] Index of graphical plot

prop_id

[in] The value can be one of the values of the enumeration ENUM_PLOT_PROPERTY_DOUBLE.

prop_value

[in] The value of the property.

Returned Value

If successful, returns true, otherwise false.


PlotIndexSetInteger

MQL5 Reference / Custom Indicators / PlotIndexSetInteger

PlotIndexSetInteger

Sets the value of the properties of the corresponding line of the indicator. Property of the indicator should be the type int, char, bool, or color. There are 2 variants of the function.

Call indicating identifier properties.

bool PlotIndexSetInteger(
int plot_index, // Plot index
int prop_id, // Property identifier
int prop_value // Set the value
);

Calling indicating the identifier and modifier properties.

bool PlotIndexSetInteger(
int plot_index, // Plot index
int prop_id, // Property identifier
int prop_modifier, // Property modifier
int prop_value // Set the value
)

Parameters

plot_index

[in] Index of graphical plot

prop_id

[in] The value can be one of the values of the enumeration ENUM_PLOT_PROPERTY_INTEGER.

prop_modifier

[in] Modifier specified property. Only the properties of the levels require a modifier.

prop_value

[in] The value of the property.

Returned Value

If successful, returns true, otherwise false.

Example:indicator, which draws a three-color line. The color scheme changes every 5 ticks.

#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 1
//---- plot ColorLine
#property indicator_label1 "ColorLine"
#property indicator_type1 DRAW_COLOR_LINE
#property indicator_color1 Red,Green,Blue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 3
//--- indicator buffers
double ColorLineBuffer[];
double ColorBuffer[];
int MA_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,ColorLineBuffer,INDICATOR_DATA);
SetIndexBuffer(1,ColorBuffer,INDICATOR_COLOR_INDEX);
//--- get MA handle
MA_handle=iMA(Symbol(),0,10,0,MODE_EMA,PRICE_CLOSE);
//---
}
//+------------------------------------------------------------------+
//| get color index |
//+------------------------------------------------------------------+
int getIndexOfColor(int i)
{
int j=i%300;
if(j<100) return(0);// first index
if(j<200) return(1);// second index
return(2); // third index
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
static int ticks=0,modified=0;
int limit;
//--- first calculation or number of bars was changed
if(prev_calculated==0)
{
//--- copy values of MA into indicator buffer ColorLineBuffer
int copied=CopyBuffer(MA_handle,0,0,rates_total,ColorLineBuffer);
if(copied<=0) return(0);// copying failed - throw away
//--- now set line color for every bar
for(int i=0;i<rates_total;i++)
ColorBuffer[i]=getIndexOfColor(i);
}
else
{
//--- copy values of MA into indicator buffer ColorLineBuffer
int copied=CopyBuffer(MA_handle,0,0,rates_total,ColorLineBuffer);
if(copied<=0) return(0);

ticks++;// ticks counting
if(ticks>=5)//it's time to change color scheme
{
ticks=0; // reset counter
modified++; // counter of color changes
if(modified>=3)modified=0;// reset counter
ResetLastError();
switch(modified)
{
case 0:// first color scheme
PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,Red);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,Blue);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,Green);
Print("Color scheme"+modified);
break;
case 1:// second color scheme
PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,Yellow);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,Pink);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,LightSlateGray);
Print("Color scheme"+modified);
break;
default:// third color scheme
PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,LightGoldenrod);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,Orchid);
PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,LimeGreen);
Print("Color scheme"+modified);
}
}
else
{
//--- set start position
limit=prev_calculated-1;
//--- now we set line color for every bar
for(int i=limit;i<rates_total;i++)
ColorBuffer[i]=getIndexOfColor(i);
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+


PlotIndexSetString

MQL5 Reference / Custom Indicators / PlotIndexSetString

PlotIndexSetString

Sets the value of the properties of the corresponding line of the indicator. Property of the indicator should be of type string.

bool PlotIndexSetString(
int plot_index, // Plot index
int prop_id, // Property identifier
string prop_value // Set the value
);

Parameters

plot_index

[in] Index of graphical plot

prop_id

[in] The value can be one of the values of the enumeration ENUM_PLOT_PROPERTY_STRING.

prop_value

[in] The value of the property.

Returned Value

If successful, returns true, otherwise false.


PlotIndexGetInteger

MQL5 Reference / Custom Indicators / PlotIndexGetInteger

PlotIndexGetInteger

Returns the value of the properties of the corresponding line of the indicator. The property must be type int, color, bool or char. There are 2 variants of the function.

Call indicating identifier properties.

int PlotIndexGetInteger(
int plot_index, // Plot index
int prop_id, // Property identifier
);

Calling indicating the identifier and modifier properties.

int PlotIndexGetInteger(
int plot_index, // Plot index
int prop_id, // Property identifier
int prop_modifier // Property modifier
)

Parameters

plot_index

[in] Index of graphical plot

prop_id

[in] The value can be one of the values of the enumeration ENUM_PLOT_PROPERTY_INTEGER.

prop_modifier

[in] Modifier specified property. Only the properties of the levels require a modifier.

Note

Function is designed to extract the settings of drawing the appropriate line of the indicator. The function works in tandem with the function PlotIndexSetInteger Copies the properties of drawing one line to another.

Example: indicator, coloring the candles in the color, depending on the day of the week. Colors for each day are set programmatically.

#property indicator_separate_window
#property indicator_buffers 5
#property indicator_plots 1
//---- plot ColorCandles
#property indicator_label1 "ColorCandles"
#property indicator_type1 DRAW_COLOR_CANDLES
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- indicator buffers
double OpenBuffer[];
double HighBuffer[];
double LowBuffer[];
double CloseBuffer[];
double ColorCandlesColors[];
color ColorOfDay[6]={CLR_NONE,MediumSlateBlue,
DarkGoldenrod,ForestGreen,BlueViolet,Red};
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,OpenBuffer,INDICATOR_DATA);
SetIndexBuffer(1,HighBuffer,INDICATOR_DATA);
SetIndexBuffer(2,LowBuffer,INDICATOR_DATA);
SetIndexBuffer(3,CloseBuffer,INDICATOR_DATA);
SetIndexBuffer(4,ColorCandlesColors,INDICATOR_COLOR_INDEX);
//--- set number of colors in color buffer
PlotIndexSetInteger(0,PLOT_COLOR_INDEXES,6);
//--- set colors for color buffer
for(int i=1;i<6;i++)
PlotIndexSetInteger(0,PLOT_LINE_COLOR,i,ColorOfDay[i]);
//--- set accuracy
IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
printf("We have %u colors of days",PlotIndexGetInteger(0,PLOT_COLOR_INDEXES));
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
int i;
MqlDateTime t;
//----
if(prev_calculated==0) i=0;
else i=prev_calculated-1;
//----
while(i<rates_total)
{
OpenBuffer[i]=open[i];
HighBuffer[i]=high[i];
LowBuffer[i]=low[i];
CloseBuffer[i]=close[i];
//--- set color for every candle
TimeToStruct(time[i],t);
ColorCandlesColors[i]=t.day_of_week;
//---
i++;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+


Graphic objects

MQL5 Reference / Graphic objects

Graphic objects

With features designed to work with graphic objects relating to any of the specified chart. These functions can not be used in indicators.

Function | Action
ObjectCreate | Creates an object of a given type on a specified chart
ObjectName | Returns the name of the object of the type specified in the chart (specified pane of the chart)
ObjectDelete | Removes the object with the specified name with the specified chart (with the specified subwindow graphics)
ObjectsDeleteAll | Removes all objects of this type with the specified chart (with the specified subwindow graphics)
ObjectFind | Looks named object with the specified ID
ObjectGetTimeByValue | Returns the value of time for the specified limit price of the object
ObjectGetValueByTime | Returns the price value of an object for the specified time
ObjectMove | Changes the coordinates of this anchor point of the object
ObjectsTotal | Returns the number of objects of the type specified in the chart (specified pane of the chart)
ObjectGetDouble | Returns the double value of the properties of the object
ObjectGetInteger | Returns the integer value of the properties of the object
ObjectGetString | Returns a string corresponding object properties
ObjectSetDouble | Sets the value of the properties of the object
ObjectSetInteger | Sets the value of the properties of the object
ObjectSetString | Sets the value of the properties of the object

Every graphic should have a name unique within a chart, Including its subwindows. After creating the object or modifying object object properties recommended to call the function ChartRedraw() Which gives the terminal command to enforce drawing graphics (and all visible objects on it).


ObjectCreate

MQL5 Reference / Graphic objects / ObjectCreate

ObjectCreate

Creates an object with the specified name, type, and the initial coordinates in the specified pane of the chart. When you specify up to 30 coordinates.

bool ObjectCreate(
long chart_id, // ID chart
string name, // Name of the object
int type, // Object type
int nwin, // Index of window
datetime time1, // Time of the first anchor point
double price1, // Price of the first anchor point
...
datetime timeN=0, // Time N-th anchor point
double priceN=0, // Price of N-th anchor point
...
datetime time30=0, // The 30-second anchor point
double price30=0 // Price of 30-point binding
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object. The name must be unique within a single graph, including its subwindows.

type

[in] Type of object. The value can be one of the values of the enumeration ENUM_OBJECT.

nwin

[in] Number subwindows chart. 0 means the main chart window. Specified subwindow must exist, otherwise the function returns false.

time1

[in] The time coordinate of the first anchor.

price1

[in] Price coordinate first anchor point.

timeN=0

[in] Time coordinate N-th point of binding.

priceN=0

[in] Price coordinate N-th point of binding.

time30=0

[in] Time coordinate thirtieth anchor point.

price30=0

[in] Price coordinate thirtieth anchor point.

Returned Value

Returns true or false depending on whether the object is created or not. To learn more about error need to call GetLastError(). If the object was previously created, then tries to change his position.

Note

The numbering of the panes chart (if the chart is subwindows with LEDs) starts with 1. The main window of the chart is and always has index 0.

A large number of anchor points (to 30) provides for future use.At the same time limit only 30 possible anchor points for the graphics due to the fact that when you call the number of parameters must not exceed 64.


ObjectName

MQL5 Reference / Graphic objects / ObjectName

ObjectName

Returns the name of the object in the specified chart specified pane of the chart, this type of.

string ObjectName(
long chart_id, // ID chart
int pos, // Number in the list of objects
int nwin=-1, // Index of window
int type=-1 // Object type
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

pos

[in] Ordinal number of the object under the specified filter on the number and type of panes.

nwin=-1

[in] Number subwindows chart. 0 means the main window graphics, -1 means all subwindows chart, including the main window.

type=-1

[in] Type of object. The value can be one of the values of the enumeration ENUM_OBJECT. -1 means all types.

Returned Value

Name of the object in case of success.


ObjectDelete

MQL5 Reference / Graphic objects / ObjectDelete

ObjectDelete

Removes the object with the specified name with the specified chart.

bool ObjectDelete(
long chart_id, // ID chart
string name // Name of the object
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of object to be deleted.

Returned Value

Returns true if the removal was successful, otherwise false. To learn more about error need to call GetLastError().


ObjectsDeleteAll

MQL5 Reference / Graphic objects / ObjectsDeleteAll

ObjectsDeleteAll

Removes all objects in the specified timetable specified pane of the chart type.

int ObjectsDeleteAll(
long chart_id, // ID chart
int nwin=-1, // Index of window
int type=-1 // Object type
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

nwin=-1

[in] Number subwindows chart. 0 means the main window graphics, -1 means all subwindows chart, including the main window.

type=-1

[in] Type of object. The value can be one of the values of the enumeration ENUM_OBJECT. -1 means all types.

Returned Value

Returns the number of remote objects. To learn more about error need to call GetLastError().


ObjectFind

MQL5 Reference / Graphic objects / ObjectFind

ObjectFind

Finds the object with the specified name on the chart with the specified ID.

int ObjectFind(
long chart_id, // ID chart
string name // Name of the object
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] The name of the desired object.

Returned Value

If successful the function returns the number of subwindows (0 means the main window of the chart), in which the object is found.If the object is not found, then the function returns a negative number.To learn more about error need to call GetLastError().


ObjectGetTimeByValue

MQL5 Reference / Graphic objects / ObjectGetTimeByValue

ObjectGetTimeByValue

Returns the value of time for the specified limit price of the specified object.

datetime ObjectGetTimeByValue(
long chart_id, // ID chart
string name, // Name of the object
double value, // Price
int line_id // Line
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object.

value

[in] The value prices.

line_id

[in] ID of the line

Returned Value

The value of time for the specified values of the price of the specified object.

Note

Since the object in one coordinate prices can have several meanings (ellipse, triangle, channels, etc.), then in this case, an identifier line.


ObjectGetValueByTime

MQL5 Reference / Graphic objects / ObjectGetValueByTime

ObjectGetValueByTime

Returns the value of the price for a specified time the specified object.

double ObjectGetValueByTime(
long chart_id, // ID chart
string name, // Name of the object
datetime time, // Time
int line_id // Line
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object.

time

[in] The value of time.

line_id

[in] ID of the line.

Returned Value

Value price for a specified time the specified object.

Note

Since the object in one coordinate time can have several meanings (ellipse, triangle, channels, and TA), in this case, an identifier line.


ObjectMove

MQL5 Reference / Graphic objects / ObjectMove

ObjectMove

Changes the coordinates of this anchor point of the object.

bool ObjectMove(
long chart_id, // ID chart
string name, // Name of the object
int point_index, // Number of bindings
datetime time, // Time
double price // Price
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object.

point_index

[in] Number anchor point. The number of anchor points depends on the type of object.

time

[in] The time coordinate of this point of binding.

price

[in] Price coordinate specified anchor point.

Returned Value

If successful, returns true, on failure returns false. To learn more about error need to call GetLastError().


ObjectsTotal

MQL5 Reference / Graphic objects / ObjectsTotal

ObjectsTotal

Returns the number of objects in the specified chart specified pane of the chart, the specified type.

int ObjectsTotal(
long chart_id, // ID chart
int nwin=-1, // Index of window
int type=-1 // Object type
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

nwin=-1

[in] Number subwindows chart. 0 means the main window graphics, -1 means all subwindows chart, including the main window.

type=-1

[in] Type of object. The value can be one of the values of the enumeration ENUM_OBJECT. -1 means all types.

Returned Value

The number of objects.


ObjectSetDouble

MQL5 Reference / Graphic objects / ObjectSetDouble

ObjectSetDouble

Sets the value of the properties of the object. Property of the object must be of type double. There are 2 variants of the function.

Setting property value, without modifier

bool ObjectSetDouble(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property
double prop_value // Value
);

Setting a property value indicating the modifier

bool ObjectSetDouble(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property
int prop_modifier, // Modifier
double prop_value // Value
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object.

prop_id

[in] ID of the object properties. The value can be one of the values of the enumeration ENUM_OBJECT_PROPERTY_DOUBLE.

prop_modifier

[in] Modifier specified property. Most properties do not require a modifier.

prop_value

[in] The value of the property.

Returned Value

Returns true if successful installation values for the property, otherwise false. To learn more about error need to call GetLastError().

Example of a Fib-object and add a new level in him

//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- axillary arrays
double high[],low[],price1,price2;
datetime time[],time1,time2;
//--- Copy the opening price - latest 100 bars enough
int copied=CopyHigh(Symbol(),0,0,100,high);
if(copied<=0)
{
Print("Unable to copy the values of the price series High");
return;
}
//--- Copy the closing price - latest 100 bars enough
copied=CopyLow(Symbol(),0,0,100,low);
if(copied<=0)
{
Print("Unable to copy the values of the price series Low");
return;
}
//--- Copy the opening for the last 100 bars
copied=CopyTime(Symbol(),0,0,100,time);
if(copied<=0)
{
Print("Unable to copy the values of the price series of Time");
return;
}
//--- Organize access to the copied data as taymseriyam - backwards
ArraySetAsSeries(high,true);
ArraySetAsSeries(low,true);
ArraySetAsSeries(time,true);

//--- Coordinates of the first anchor point Fibo object
price1=high[70];
time1=time[70];
//--- Coordinates of the second anchor point Fibo object
price2=low[50];
time2=time[50];

//--- Time to create himself Fib-object
bool created=ObjectCreate(0,"Fibo",OBJ_FIBO,0,time1,price1,time2,price2);
if(created) // If the object is created successfully
{
//--- Set the color Fibo levels
ObjectSetInteger(0,"Fibo",OBJPROP_LEVELCOLOR,Blue);
//--- The way, but how much we Fibo levels?
int levels=ObjectGetInteger(0,"Fibo",OBJPROP_LEVELS);
Print("Fibo levels before =",levels);
//---derive the Journal => number of levels: the values level_desription
for(int i=0;i<levels;i++)
{
Print(i,":",ObjectGetDouble(0,"Fibo",OBJPROP_LEVELVALUE,i),
" ",ObjectGetString(0,"Fibo",OBJPROP_LEVELTEXT,i));
}
//--- Try to increase the number of levels per unit
bool modified=ObjectSetInteger(0,"Fibo",OBJPROP_LEVELS,levels+1);
if(!modified) // Could not change the number of levels
{
Print("Could not change the number of levels of Fib, error",GetLastError());
}
//--- Just let
Print("Fibo levels after =",ObjectGetInteger(0,"Fibo",OBJPROP_LEVELS));
//--- Define a value for the newly established level
bool added=ObjectSetDouble(0,"Fibo",OBJPROP_LEVELVALUE,levels,133);
if(added) // Could set a value for the level
{
Print("It was possible to establish another layer of Fibo");
//--- Also do not forget to set the level description
ObjectSetString(0,"Fibo",OBJPROP_LEVELTEXT,levels,"my level");
ChartRedraw(0);
//--- Get the actual value of the number of levels in the Fib-object
levels=ObjectGetInteger(0,"Fibo",OBJPROP_LEVELS);
Print("Fibo levels after adding =",levels);
//--- Again derive all levels - just to make sure
for(int i=0;i<levels;i++)
{
Print(i,":",ObjectGetDouble(0,"Fibo",OBJPROP_LEVELVALUE,i),
" ",ObjectGetString(0,"Fibo",OBJPROP_LEVELTEXT,i));
}
}
else // Fail when you try to increase the number of levels in the Fib-object
{
Print("Unable to establish one more Fibo level. Error",GetLastError());
}
}
}

See also

Object Types, Object Properties


ObjectSetInteger

MQL5 Reference / Graphic objects / ObjectSetInteger

ObjectSetInteger

Sets the value of the properties of the object. Property of the object must be of type datetime, int, color, bool or char. There are 2 variants of the function.

Setting property value, without modifier

bool ObjectSetInteger(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property
long prop_value // Value
);

Setting a property value indicating the modifier

bool ObjectSetInteger(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property
int prop_modifier, // Modifier
long prop_value // Value
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object.

prop_id

[in] ID of the object properties. The value can be one of the values of the enumeration ENUM_OBJECT_PROPERTY_INTEGER.

prop_modifier

[in] Modifier specified property. Most properties do not require a modifier.

prop_value

[in] The value of the property.

Returned Value

Returns true if successful installation values for the property, otherwise false. To learn more about error need to call GetLastError().

See also

Object Types, Object Properties


ObjectSetString

MQL5 Reference / Graphic objects / ObjectSetString

ObjectSetString

Sets the value of the properties of the object. Property of the object must be of type string. There are 2 variants of the function.

Setting property value, without modifier

bool ObjectSetString(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property
string prop_value // Value
);

Setting a property value indicating the modifier

bool ObjectSetString(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property
int prop_modifier, // Modifier
string prop_value // Value
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object.

prop_id

[in] ID of the object properties. The value can be one of the values of the enumeration ENUM_OBJECT_PROPERTY_STRING.

prop_modifier

[in] Modifier specified property. Most properties do not require a modifier.

prop_value

[in] The value of the property.

Returned Value

Returns true if successful installation values for the property, otherwise false. To learn more about error need to call GetLastError().


ObjectGetDouble

MQL5 Reference / Graphic objects / ObjectGetDouble

ObjectGetDouble

Returns the value of the properties of the object. Property of the object must be of type double. There are 2 variants of the function.

1. Immediately returns the property value.

double ObjectGetDouble(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property identifier
int prop_modifier=0 // Property modifier, if required
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool ObjectGetDouble(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property identifier
int prop_modifier, // Property modifier
double& double_var // Here we assume the property value
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object.

prop_id

[in] ID of the object properties. The value can be one of the values of the enumeration ENUM_OBJECT_PROPERTY_DOUBLE.

prop_modifier

[in] Modifier specified property. For the first version of the default value of the modifier is 0. Most properties do not require a modifier.

double_var

[out] Variable of type double, the host value of the requested properties.

Returned Value

Double value for the first version of the call.

For the second version of the call returns true, if this property is maintained and the value was placed in the variable double_var, otherwise returns false. To learn more about error need to call GetLastError().


ObjectGetInteger

MQL5 Reference / Graphic objects / ObjectGetInteger

ObjectGetInteger

Returns the value of the properties of the object. Property of the object must be of type datetime, int, color, bool or char. There are 2 variants of the function.

1. Immediately returns the property value.

long ObjectGetInteger(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property identifier
int prop_modifier=0 // Property modifier, if required
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool ObjectGetInteger(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property identifier
int prop_modifier, // Property modifier
long& long_var // Here we assume the property value
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object.

prop_id

[in] ID of the object properties. The value can be one of the values of the enumeration ENUM_OBJECT_PROPERTY_INTEGER.

prop_modifier

[in] Modifier specified property. For the first version of the default value of the modifier is 0. Most properties do not require a modifier.

long_var

[out] Variable of type long, the host value of the requested properties.

Returned Value

Long value for the first version of the call.

For the second version of the call returns true, if this property is maintained and the value was placed in the variable long_var, otherwise returns false. To learn more about error need to call GetLastError().


ObjectGetString

MQL5 Reference / Graphic objects / ObjectGetString

ObjectGetString

Returns the value of the properties of the object. Property of the object must be of type string. There are 2 variants of the function.

1. Immediately returns the property value.

string ObjectGetString(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property identifier
int prop_modifier=0 // Property modifier, if required
);

2. Returns true or false, depending on the success of a function. If successful, the value of the property is placed in a foster variables passed by reference the last parameter.

bool ObjectGetString(
long chart_id, // ID chart
string name, // Name of the object
int prop_id, // Property identifier
int prop_modifier, // Property modifier
string& string_var // Here we assume the property value
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

name

[in] Name of the object.

prop_id

[in] ID of the object properties. The value can be one of the values of the enumeration ENUM_OBJECT_PROPERTY_STRING.

prop_modifier

[in] Modifier specified property. For the first version of the default value of the modifier is 0. Most properties do not require a modifier.

string_var

[out] Variable of type string, the host value of the requested properties.

Returned Value

String value for the first version of the call.

For the second version of the call returns true, if this property is maintained and the value was placed in the variable string_var, otherwise returns false. To learn more about error need to call GetLastError().


Technical Indicators

MQL5 Reference / Technical indicators

Technical indicator functions

All functions like iMA, iAC, iMACD, iIchimoku etc. creates a copy of the technical indicator in the global cache of the client terminal. If a copy of the indicator with these options is already exist, in such case a new copy is not created, and the reference counter on this copy increases.

These functions return a handle to the appropriate copy of the indicator. Further, using this handle, you may receive the data, calculated by indicator. The buffer data (technical indicators contain calculated data in its internal buffers, which, depending on the indicator, can vary from 1 to 5) can be copied to mql5-program by using the function CopyBuffer().

Custom Indicators can contain up to 512 indicator buffers, the buffer data also can be obtained by using the function CopyBuffer() with the handle returned by function iCustom() .

Note.Repeated call to the indicator with the same parameters within one mql5-program does not lead to a multiple increase of the reference counter, the counter will be increased only once at 1. However, we recommend to get the indicators handles in function OnInit() or in the class constructor (the better way to perform such in the OnInit(), since there is no function to free handles), and further use these handles in other functions. Reference counter decreases in deinitialization of mql5-program.

All indicator functions have at least 2 parameters - symbol and period. The NULL value of the symbol means the current tool, the value of 0 means the current timeframe.

Function | Returns the indicator handle:
iAC | Accelerator Oscillator
iAD | Accumulation/Distribution
iADX | Average Directional Index
iADXWilder | Average Directional Index by Welles Wilder
iAlligator | Alligator
iAMA | Adaptive Moving Average
iAO | Awesome Oscillator
iATR | Average True Range
iBearsPower | Bears Power
iBands | Bollinger Bands
iBullsPower | Bulls Power
iCCI | Commodity Channel Index
iChaikin | Chaikin Oscillator
iCustom | Custom user indicator
iDEMA | Double Exponential Moving Average
iDeMarker | DeMarker
iEnvelopes | Envelopes
iForce | Force Index
iFractals | Fractals
iFRAMA | Fractal Adaptive Moving Average
iGator | Gator Oscillator
iIchimoku | Ichimoku Kinko Hyo
iBWMFI | Market Facilitation Index by Bill Williams
iMomentum | Momentum
iMFI | Money Flow Index
iMA | Moving Average
iOsMA | Moving Average of Oscillator (MACD histogram)
iMACD | Moving Averages Convergence-Divergence
iOBV | On Balance Volume
iSAR | Parabolic Stop And Reverse System
iRSI | Relative Strength Index
iRVI | Relative Vigor Index
iStdDev | Standard Deviation
iStochastic | Stochastic Oscillator
iTEMA | Triple Exponential Moving Average
iTriX | Triple Exponential Moving Averages Oscillator
iWPR | Williams' Percent Range
iVIDyA | Variable Index DYnamic Average
iVolumes | Volumes


iAC

MQL5 Reference / Technical indicators / iAC

iAC

Creates an Accelerator Oscillator indicator in a global cache of the client terminal and return it's handle. It has an only one buffer.

int iAC(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period // Period
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.


iAD

MQL5 Reference / Technical indicators / iAD

iAD

Returns the handle of the Accumulation/Distribution indicator. It has an only one buffer.

int iAD(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
ENUM_APPLIED_VOLUME applied_volume // Volume type for calculation
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

applied_volume

[in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values.


iADX

MQL5 Reference / Technical indicators / iADX

iADX

Returns the handle of the Average Directional Movement Index indicator.

int iADX(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int adx_period // Averaging Period
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

adx_period

[in] The value of the period for average (bars count).

Note

The buffer numbers are the following: 0 - MAIN_LINE, 1 - PLUSDI_LINE, 2 - MINUSDI_LINE.


iADXWilder

MQL5 Reference / Technical indicators / iADXWilder

iADXWilder

Returns the handle of the Average Directional Movement Index by Welles Wilder.

int iADXWilder(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int adx_period // Averaging Period
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

adx_period

[in] The value of the period for average (bars count).

Note

The buffer numbers are the following: 0 - MAIN_LINE, 1 - PLUSDI_LINE, 2 - MINUSDI_LINE.


iAlligator

MQL5 Reference / Technical indicators / iAlligator

iAlligator

Returns the handle of the Alligator indicator.

int iAlligator(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int jaw_period, // Period for the calculation of the jaws
int jaw_shift, // Jaws horizontal shift
int teeth_period, // Period for the calculation of the teeth
int teeth_shift, // Teeth horizontal shift
int lips_period, // Period for the calculation of the lips
int lips_shift, // Lips horizontal shift
ENUM_MA_METHOD ma_method, // Type of smoothing
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

jaw_period

[in] Average period for the blue line (Alligator's Jaw)

jaw_shift

[in] The shift offset the blue line on the price chart. This shift of the line is purely visual and the indicator values are stored without bias in indicator buffer. If you are using the buffer values by function CopyBuffer(), it is necessary to bear in mind this fact.

teeth_period

[in] Average period for the red line (Alligator Teeth).

teeth_shift

[in] The shift offset the red line on the price chart. This shift of the line is purely visual and the indicator values are stored without bias in indicator buffer. If you are using the buffer values by function CopyBuffer(), it is necessary to bear in mind this fact.

lips_period

[in] Average period for the green line (Alligator lips).

lips_shift

[in] The shift offset the red line on the chart of prices. This shift of the line is purely visual and the indicator values are stored without bias in indicator buffer. If you are using the buffer values by function CopyBuffer(), it is necessary to bear in mind this fact.

ma_method

[in] The method of averaging. Can be any of the ENUM_MA_METHOD values.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.

Note

The buffer numbers are the following: 0 - GATORJAW_LINE, 1 - GATORTEETH_LINE, 2 - GATORLIPS_LINE.


iAMA

MQL5 Reference / Technical indicators / iAMA

iAMA

Returns the handle of the Adaptive Moving Average indicator. It has an only one buffer.

int iAMA(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ama_period, // Average period for AMA
int fast_ma_period, // Fast MA period
int slow_ma_period, // Slow MA period
int ama_shift, // Horizontal shift of the indicator
ENUM_APPLIED_PRICE applied_price // Type of the price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ama_period

[in] The period for the efficiency coefficient calculation.

fast_ma_period

[in] Fast period for the smoothing coefficient calculation for a rapid market.

slow_ma_period

[in] Slow period for the smoothing coefficient calculation in the absence of trend.

ama_shift

[in] Shift indicator on the price chart.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iAO

MQL5 Reference / Technical indicators / iAO

iAO

Returns the handle of the Awesome oscillator indicator. It has an only one buffer.

int iAO(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period // Period
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.


iATR

MQL5 Reference / Technical indicators / iATR

iATR

Returns the handle of the Average True Range indicator. It has an only one buffer.

int iATR(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] The value of the period for average (bars count).


iBearsPower

MQL5 Reference / Technical indicators / iBearsPower

iBearsPower

Returns the handle of the Bears Power indicator. It has an only one buffer.

int iBearsPower(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] The value of the period for average (bars count).

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iBands

MQL5 Reference / Technical indicators / iBands

iBands

Returns the handle of the Bollinger Bands indicator.

int iBands(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int period, // Period for average line calculation
double deviation, // Number of standard deviations
int bands_shift, // Horizontal shift of the indicator
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] The value of the period for average (bars count).

deviation

[in] The number of standard deviations from the main line.

bands_shift

[in] The shift the indicator on the price chart. This shift of the line is purely visual and the indicator values are stored without bias in indicator buffer. If you are using the buffer values by function CopyBuffer(), it is necessary to bear in mind this fact.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.

Note

The buffer numbers are the following: 0 - BASE_LINE, 1 - UPPER_BAND, 2 - LOWER_BAND


iBullsPower

MQL5 Reference / Technical indicators / iBullsPower

iBullsPower

Returns the handle of the Bulls Power indicator. It has an only one buffer.

int iBullsPower(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] The value of the period for average (bars count).

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iCCI

MQL5 Reference / Technical indicators / iCCI

iCCI

Returns the handle of the Commodity Channel Index indicator. It has an only one buffer.

int iCCI(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] The value of the period for average (bars count).

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iChaikin

MQL5 Reference / Technical indicators / iChaikin

iChaikin

Returns the handle of the Chaikin Oscillator indicator. It has an only one buffer.

int iChaikin(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int fast_ma_period, // Fast period
int slow_ma_period, // Slow period
ENUM_MA_METHOD ma_method, // Smoothing type
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

fast_ma_period

[in] Fast averaging period for calculations.

slow_ma_period

[in] Slow averaging period for calculations.

ma_method

[in] Smoothing type. Can be one of the averaging constants of ENUM_MA_METHOD.

applied_volume

[in] The volume used. Can be one of the constants of ENUM_APPLIED_VOLUME.


iCustom

MQL5 Reference / Technical indicators / iCustom

iCustom

Returns the handle of the Custom Indicator.

int iCustom(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
string name // Folder/user_indicator_filename
... // List of indicator input parameters
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

name

[in] The name of the custom indicator, with path relative to the root directory of indicators (MQL5/Indicators/).

For example, if the indicator is located in path MQL5/Indicators/Examples, it's name must be the following: "Examples\\indicator_name" (it is necessary to use a double slash instead of the single slash as a separator).

...

[in] input-parameters of custom indicator, separated by commas. Type and order of parameters must match. If there is no parameters specified, then default values will be used.

Note

Custom indicator should be compiled (with extension EX5) and located in the directory MQL5/Indicators of the client terminal or.

If indicator called from OnCalculate, then after custom indicator run it is possible to specify the data for calculation. If the option "Apply to" is not selected explicitly, the default calculation is based on the values of "Close" prices.

When you call a custom indicator from mql5-program, the Applied_Price parameter or a handle of another indicator should be last parameter, after all of the user-specified input indicator variables.

Example:

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Label1
#property indicator_label1 "Label1"
#property indicator_type1 DRAW_LINE
#property indicator_color1 Red
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int MA_Period=21;
input int MA_Shift=0;
input ENUM_MA_METHOD MA_Method=MODE_SMA;
//--- indicator buffers
double Label1Buffer[];
//--- Handle of the Custom Moving Average.mq5 user indicator
int MA_handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
ResetLastError();
MA_handle=iCustom(NULL,0,"Custom Moving Average",
MA_Period,
MA_Shift,
MA_Method,
PRICE_CLOSE // using the close prices
);
Print("MA_handle =",MA_handle," error =",GetLastError());
//---
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- Copy the values of the indicator CHO our indicator buffer
int copy=CopyBuffer(MA_handle,0,0,rates_total,Label1Buffer);
Print("copy =",copy," rates_total =",rates_total);
//--- If our attempt has failed - Report this
if(copy<=0)
Print("An attempt to get the values if Custom Moving Average has failed");
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+


iDEMA

MQL5 Reference / Technical indicators / iDEMA

iDEMA

Returns the handle of the Double Exponential Moving Average indicator. It has an only one buffer.

int iDEMA(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Horizontal shift
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for calculations.

ma_shift

[in] Shift offset of the indicator on the price chart.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iDeMarker

MQL5 Reference / Technical indicators / iDeMarker

iDeMarker

Returns the handle of the DeMarker indicator. It has an only one buffer.

int iDeMarker(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for calculations.


iEnvelopes

MQL5 Reference / Technical indicators / iEnvelopes

iEnvelopes

Returns the handle of the Envelopes indicator.

int iEnvelopes(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Period for the average line calculation
ENUM_MA_METHOD ma_method, // Type of smoothing
int ma_shift, // Horizontal shift of the indicator
ENUM_APPLIED_PRICE applied_price, // Type of price or handle
double deviation // Deviation boundary from the midline (in percents)
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for the main line.

ma_method

[in] Smoothing type. Can be one of the values of ENUM_MA_METHOD.

ma_shift

[in] The shift offset of the indicator on price chart. This shift of the line is purely visual and the indicator values are stored without bias in indicator buffer. If you are using the buffer values by function CopyBuffer(), it is necessary to bear in mind this fact.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.

deviation

[in] The deviation from the main line (in percents).

Note

The buffer numbers: 0 - UPPER_LINE, 1 - LOWER_LINE.


iForce

MQL5 Reference / Technical indicators / iForce

iForce

Returns the handle of the Force Index indicator. It has an only one buffer.

int iForce(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
ENUM_MA_METHOD ma_method, // Smoothing type
ENUM_APPLIED_VOLUME applied_volume // Volume type for calculation
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for the calculations.

ma_method

[in] Smoothing type. Can be one of the values of ENUM_MA_METHOD.

applied_volume

[in] The volume used. Can be one of the values of ENUM_APPLIED_VOLUME.


iFractals

MQL5 Reference / Technical indicators / iFractals

iFractals

Returns the handle of the Fractals indicator.

int iFractals(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period // Period
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

Note

The buffer numbers are the following: 0 - UPPER_LINE, 1 - LOWER_LINE.


iFrAMA

MQL5 Reference / Technical indicators / iFrAMA

iFrAMA

Returns the handle of the Fractal Adaptive Moving Average indicator. It has an only one buffer.

int iFrAMA(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Horizontal shift on the chart
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for the calculations.

ma_shift

[in] Horizontal shift of the indicator on the price chart.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iGator

MQL5 Reference / Technical indicators / iGator

iGator

Returns the handle of the Gator indicator. The Oscillator shows the difference between the blue and red lines of Alligator (upper histogram) and difference between red and green lines (lower histogram).

int iGator(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int jaw_period, // Period for the calculation of the jaws
int jaw_shift, // Jaws horizontal shift
int teeth_period, // Period for the calculation of the teeth
int teeth_shift, // Teeth horizontal shift
int lips_period, // Period for the calculation of the lips
int lips_shift, // Lips horizontal shift
ENUM_MA_METHOD ma_method, // Type of smoothing
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

jaw_period

[in] Averaging period for the blue line (Alligator's Jaw).

jaw_shift

[in] The shift offset the blue line on the price chart. It hasn't a direct relationship with visual shift of the indicator histogram.

teeth_period

[in] Averaging period for the red line (Alligator Teeth).

teeth_shift

[in] The shift offset the red line on the price chart. It hasn't a direct relationship with visual shift of the indicator histogram.

lips_period

[in] Averaging period for the green line (Alligator lips).

lips_shift

[in] The shift offset the green line on the price charts. It hasn't a direct relationship with visual shift of the indicator histogram.

ma_method

[in] Smoothing type. Can be one of the values of ENUM_MA_METHOD.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.

Note

The buffer numbers: 0 - UPPER_LINE, 1 - LOWER_LINE.


iIchimoku

MQL5 Reference / Technical indicators / iIchimoku

iIchimoku

Returns the handle of the Ichimoku Kinko Hyo indicator.

int iIchimoku(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int tenkan_sen, // Period of Tenkan-sen
int kijun_sen, // Period of Kijun-sen
int senkou_span_b // Period of Senkou Span B
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

tenkan_sen

[in] Averaging period (bars count) for the Tenkan Sen.

kijun_sen

[in] Averaging period (bars count) for the Kijun Sen.

senkou_span_b

[in] Averaging period (bars count) for the Senkou Span B.

Note

The buffer numbers: 0 - TENKANSEN_LINE, 1 - KIJUNSEN_LINE, 2 - SENKOUSPANA_LINE, 3 - SENKOUSPANB_LINE, 4 - CHINKOUSPAN_LINE.


iBWMFI

MQL5 Reference / Technical indicators / iBWMFI

iBWMFI

Returns the handle of the Market Facilitation Index indicator. It has an only one buffer.

int iBWMFI(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
ENUM_APPLIED_VOLUME applied_volume // Volume Type for calculation
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

applied_volume

[in] The volume used. Can be one of the constants of ENUM_APPLIED_VOLUME.


iMomentum

MQL5 Reference / Technical indicators / iMomentum

iMomentum

Returns the handle of the Momentum indicator. It has an only one buffer.

int iMomentum(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int period, // Averaging period
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

period

[in] Averaging period (bars count) for the calculation of the price difference.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iMFI

MQL5 Reference / Technical indicators / iMFI

iMFI

Returns the handle of the Money Flow Index indicator.

int iMFI(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
ENUM_APPLIED_VOLUME applied_volume // Volume type for calculation
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for the calculation.

applied_volume

[in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values.


iMA

MQL5 Reference / Technical indicators / iMA

iMA

Returns the handle of the Moving Average indicator. It has an only one buffer.

int iMA(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Horizontal shift
ENUM_MA_METHOD ma_method, // Smoothing type
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for the calculation of moving average.

ma_shift

[in] Horizontal shift offset of the indicator on the price chart.

ma_method

[in] Smoothing type. Can be one of the ENUM_MA_METHOD values.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iOsMA

MQL5 Reference / Technical indicators / iOsMA

iOsMA

Returns the handle of the Moving Average of Oscillator indicator. OsMA Oscillator shows the difference between the values of MACD and its signal line. It has an only one buffer.

int iOsMA(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int fast_ema_period, // Period for Fast Moving Average
int slow_ema_period, // Period for Slow Moving Average
int signal_period, // Averaging period for their difference
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

fast_ema_period

[in] Period for Fast Moving Average calculation.

slow_ema_period

[in] Period for Slow Moving Average calculation.

signal_period

[in] Averaging period for signal line calculation.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.

Note

In some systems this oscillator also known as MACD histogram.


iMACD

MQL5 Reference / Technical indicators / iMACD

iMACD

Returns the handle of the Moving Averages Convergence / Divergence indicator.In systems where OsMA called as MACD Histogram, this indicator are shown as two lines.In the client terminal the Moving Averages Convergence / Divergence looks like a histogram.

int iMACD(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int fast_ema_period, // Period for Fast average calculation
int slow_ema_period, // Period for Slow average calculation
int signal_period, // Period for their difference averaging
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

fast_ema_period

[in] Period for Fast Moving Average calculation.

slow_ema_period

[in] Period for Slow Moving Average calculation.

signal_period

[in] Period for Signal line calculation.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.

Note

The buffer numbers are the following: 0 - MAIN_LINE, 1 - SIGNAL_LINE.


iOBV

MQL5 Reference / Technical indicators / iOBV

iOBV

Returns the handle of the On Balance Volume indicator. It has an only one buffer.

int iOBV(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
ENUM_APPLIED_VOLUME applied_volume // Volume type for calculation
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

applied_volume

[in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values.


iSAR

MQL5 Reference / Technical indicators / iSAR

iSAR

Returns the handle of the Parabolic Stop and Reverse system indicator. It has an only one buffer.

int iSAR(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
double step, // Step increment
double maximum // The maximal stop level
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

step

[in] The stop level increment, usually 0.02.

maximum

[in] The maximal stop level, usually 0.2.


iRSI

MQL5 Reference / Technical indicators / iRSI

iRSI

Returns the handle of the Relative Strength Index indicator. It has an only one buffer.

int iRSI(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period for the RSI calculation.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iRVI

MQL5 Reference / Technical indicators / iRVI

iRVI

Returns the handle of the Relative Vigor Index indicator.

int iRVI(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period // Averaging period
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for the RVI calculation

Note

The buffer numbers are the following: 0 - MAIN_LINE, 1 - SIGNAL_LINE.


iStdDev

MQL5 Reference / Technical indicators / iStdDev

iStdDev

Returns the handle of the Standard Deviation indicator. It has an only one buffer.

int iStdDev(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Horizontal shift
ENUM_MA_METHOD ma_method, // Smoothing type
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for calculation

ma_shift

[in] Horizontal shift offset on the price chart.

ma_method

[in] Smoothing type. Can be any of the ENUM_MA_METHOD values.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iStochastic

MQL5 Reference / Technical indicators / iStochastic

iStochastic

Returns the handle of the Stochastic Oscillator indicator.

int iStochastic(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int %Kperiod, // K-period (window period for calculations)
int %Dperiod, // D-period (the period of primary smoothing)
int slowing, // Final smoothing
ENUM_MA_METHOD ma_method, // Type of Smoothing
ENUM_STO_PRICE price_field // Stochastic calculation method
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

%Kperiod

[in] Averaging period (bars count) for the %K line calculation.

%Dperiod

[in] Averaging period (bars count) for the %D line calculation.

slowing

[in] Slowing value.

ma_method

[in] Type of smoothing. Can be any of the ENUM_MA_METHOD values.

price_field

[in] Parameter for the prices selection. Can be one of the ENUM_STO_PRICE values.

Note

The buffer numbers: 0 - MAIN_LINE, 1 - SIGNAL_LINE.


iTEMA

MQL5 Reference / Technical indicators / iTEMA

iTEMA

Returns the handle of the Triple Exponential Moving Average indicator. It has an only one buffer.

int iTEMA(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
int ma_shift, // Horizontal shift of indicator
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for calculation.

ma_shift

[in] Horizontal shift of indicator on the price chart.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iTriX

MQL5 Reference / Technical indicators / iTriX

iTriX

Returns the handle of the Triple Exponential Moving Averages Oscillator indicator. It has an only one buffer.

int iTriX(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int ma_period, // Averaging period
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

ma_period

[in] Averaging period (bars count) for calculation.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iWPR

MQL5 Reference / Technical indicators / iWPR

iWPR

Returns the handle of the Larry Williams' Percent Range indicator. It has an only one buffer.

int iWPR(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int calc_period // Averaging period
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

calc_period

[in] Averaging period (bars count) for calculation.


iVIDyA

MQL5 Reference / Technical indicators / iVIDyA

iVIDyA

Returns the handle of the Variable Index DYnamic Average indicator. It has an only one buffer.

int iVIDyA(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
int cmo_period, // Period for Chande Momentum
int ema_period, // EMA smoothing period
int ma_shift, // Horizontal shift on the price chart
ENUM_APPLIED_PRICE applied_price // Type of price or handle
);

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

cmo_period

[in] Period (bars count) for the Chande Momentum Oscillator calculation.

ema_period

[in] EMA smoothing period (bars count).

ma_shift

[in] Horizontal shift of the indicator on the price chart.

applied_price

[in] The used price. Can be any of the price constants ENUM_APPLIED_PRICE or a handle of another indicator.


iVolumes

MQL5 Reference / Technical indicators / iVolumes

iVolumes

Returns the handle of the Volumes indicator. It has an only one buffer.

int iVolumes(
string symbol, // Name of the symbol
ENUM_TIMEFRAMES period, // Period
ENUM_APPLIED_VOLUME applied_volume // Volume type for calculation
)

Parameters

symbol

[in] The symbolic name of the instrument, which data will be used by the indicator in calculations. The NULL value means the current symbol.

period

[in] The value of the period can be one of the ENUM_TIMEFRAMES values, 0 means the current timeframe.

applied_volume

[in] The volume used. Can be any of the ENUM_APPLIED_VOLUME values.


Working with events

MQL5 Reference / Working with events

Working with events

Options to work with custom events and timer events. In addition to these functions, there are also special features for handling predefined events.

Function | Action
EventSetTimer | Starts the timer event generator with the specified period of time for the current chart
EventKillTimer | Stops on the current chart of events to generate a timer
EventChartCustom | Generate a custom event for the specified chart


EventSetTimer

MQL5 Reference / Working with events / EventSetTimer

EventSetTimer

Specifies the client terminal that chart, which is attached to this expert, to generate events fromTimerspecified period of time.

void EventSetTimer(
int seconds // Seconds
);

Parameters

seconds

[in] Number of seconds that determines the frequency of occurrence of events from the timer.

Returned Value

No return value.

Note

Normally, this function must be called from a function OnInit() or from a class Constructor(). In order to handle events coming from the timer, the expert must have a function OnTimer(). For each program no more than one timer can be run.


EventKillTimer

MQL5 Reference / Working with events / EventKillTimer

EventKillTimer

Specifies the client terminal that is necessary to stop the generation of events from Timer.

void EventKillTimer();

Returned Value

No return value.

Note

Typically, this function must be called from a function OnDeinit() in that case, if the function OnInit() was caused by a function EventSetTimer(). Either must be called from the destructor of class, if class constructor calls the function EventSetTimer().


EventChartCustom

MQL5 Reference / Working with events / EventChartCustom

EventChartCustom

Generate a custom event for the specified chart.

void EventChartCustom(
long chart_id, //
ushort custom_event_id, // Event ID
long lparam, // Parameter of type long
double dparam, // Parameter of type double
string sparam // String parameter events
);

Parameters

chart_id

[in] ID of chart. 0 means the current chart.

custom_event_id

[in] ID of the user events. This identifier is automatically added to the value CHARTEVENT_CUSTOM and converted to integer type.

lparam

[in] parameter event of a long, passed to the function OnChartEvent.

dparam

[in] parameter event type double, passed to the function OnChartEvent.

sparam

[in] parameter event type string, passed to the function OnChartEvent. If the string has a length of more than 63 characters, then the string is truncated.

Returned Value

No return value.

Note

Expert attached to the specified chart, handles the event using the function OnChartEvent(int event_id, long& lparam, double& dparam, string& sparam);

Example:

//+------------------------------------------------------------------+
//| ButtonClickExpert.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"

string buttonID="Button";
string labelID="Info";
int broadcastEventID=5000;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Create a button to send custom events
ObjectCreate(0,buttonID,OBJ_BUTTON,0,100,100);
ObjectSetInteger(0,buttonID,OBJPROP_COLOR,White);
ObjectSetInteger(0,buttonID,OBJPROP_BGCOLOR,Gray);
ObjectSetInteger(0,buttonID,OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,buttonID,OBJPROP_YDISTANCE,100);
ObjectSetInteger(0,buttonID,OBJPROP_XSIZE,200);
ObjectSetInteger(0,buttonID,OBJPROP_YSIZE,50);
ObjectSetString(0,buttonID,OBJPROP_FONT,"Arial");
ObjectSetString(0,buttonID,OBJPROP_TEXT,"Button");
ObjectSetInteger(0,buttonID,OBJPROP_FONTSIZE,10);
ObjectSetInteger(0,buttonID,OBJPROP_SELECTABLE,0);

//--- Create a label for displaying information
ObjectCreate(0,labelID,OBJ_LABEL,0,100,100);
ObjectSetInteger(0,labelID,OBJPROP_COLOR,Red);
ObjectSetInteger(0,labelID,OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,labelID,OBJPROP_YDISTANCE,50);
ObjectSetString(0,labelID,OBJPROP_FONT,"Trebuchet MS");
ObjectSetString(0,labelID,OBJPROP_TEXT,"No information");
ObjectSetInteger(0,labelID,OBJPROP_FONTSIZE,20);
ObjectSetInteger(0,labelID,OBJPROP_SELECTABLE,0);

//---
return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
ObjectDelete(0,buttonID);
ObjectDelete(0,labelID);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---

}
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Check the event by pressing a mouse button
if(id==CHARTEVENT_OBJECT_CLICK)
{
string clickedChartObject=sparam;
//--- If you click on the object with the name buttonID
if(clickedChartObject==buttonID)
{
//--- State of the button - is pressed or not
bool selected=ObjectGetInteger(0,buttonID,OBJPROP_STATE);
//--- Derive a log debug message
Print("Button pressed =",selected);
int customEventID; // Number of user events to send
string message; // Message to be sent to the event
//--- If the button is pressed
if(selected)
{
message="Button pressed";
customEventID=CHARTEVENT_CUSTOM+1;
}
else // Button is not pressed
{
message="Button in not pressed";
customEventID=CHARTEVENT_CUSTOM+999;
}
//--- Send a custom event "their" chart
EventChartCustom(0,customEventID-CHARTEVENT_CUSTOM,0,0,message);
///--- Send a message to all open charts
BroadcastEvent(ChartID(),0,"Broadcast Message");
//--- Debug message
Print("Sent an event with ID =",customEventID);
}
ChartRedraw();// Forced redraw of all chart objects
}

//--- Check the event belongs to the user events
if(id>CHARTEVENT_CUSTOM)
{
if(id==broadcastEventID)
{
Print("Got broadcast message from a chart with id ="+lparam);
}
else
{
//--- We read a text message in the event
string info=sparam;
Print("Handle the user event with the ID =",id);
//--- Display a message in a label
ObjectSetString(0,labelID,OBJPROP_TEXT,sparam);
ChartRedraw();// Forced redraw of all chart objects
}
}
}
//+------------------------------------------------------------------+
//| sends broadcast event to all opened charts |
//+------------------------------------------------------------------+
void BroadcastEvent(long lparam,double dparam,string sparam)
{
int limit=100;// We have certainly not more than 100 open charts
int eventID=broadcastEventID-CHARTEVENT_CUSTOM;
long currChart,prevChart=ChartFirst();
int i=0;
while(i<limit)
{
currChart=ChartNext(prevChart); // We have received a new chart from the previous
if(currChart==0) break; // Reached the end of the charts list
EventChartCustom(currChart,eventID,lparam,dparam,sparam);
prevChart=currChart;// Remember the the current chart ID for ChartNext ()
i++;// Do not forget to increase the counter
}
}
//+------------------------------------------------------------------+

See also

Events client terminal, Event handler function


Standard Library

MQL5 Reference / Standard Library

Standard Library

This group of chapters contains the technical details of the standard library MQL5 and descriptions of all its key components.

Standard library MQL5 written in MQL5 and is designed to facilitate writing programs (indicators, scripts, experts) to end users.Library provides convenient access to most of the internal functions MQL5.

Standard library MQL5 placed in the working directory of the terminal in the folder Include.

Section | Location
Base class | Include\
Data structures | Include\Arrays\
File operations | Include\Files\
Operations with strings | Include\Strings\
Graphic objects | Include\Objects\
Technical indicators | Include\Indicators\


Basic Class CObject

MQL5 Reference / Standard Library / Basic Class CObject

Basic Class CObject

Class CObject is the base class for constructing a standard library MQL5.

Description

Class CObject provides all its descendants to be part of a linked list. Also identifies a number of virtual methods for further implementation in descendant classes.

Declaration

class CObject

Title

#include <Object.mqh>

Class Methods

Function method | Action
Prev | Gets the value of the previous item
Prev | Sets the value of the previous item
Next | Gets the value of the subsequent element
Next | Sets the next element
Save | Writes object to a file
Load | Reads the object from the file
Type | Returns the type of object
Compare | Returns the result of comparison with another object


Prev

MQL5 Reference / Standard Library / Basic Class CObject / Prev

Prev

Gets a pointer to the previous list item.

CObject* Prev()

Returned Value

Pointer to the previous list item. If an item is listed first, then return NULL.

Example:

//--- example for CObject::Prev()
#include <Object.mqh>
//---
void OnStart()
{
CObject *object_first,*object_second;
//---
object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
object_second.Prev(object_first);
//--- use prev object
CObject *object=object_second.Prev();
//--- delete objects
delete object_first;
delete object_second;
}


Prev

MQL5 Reference / Standard Library / Basic Class CObject / Prev

Prev

Sets the pointer to the previous list item.

void Prev(
CObject* object // Pointer to the previous list item
)

Parameters

object

[in] New value pointer to the previous list item.

Example:

//--- example for CObject::Prev(CObject*)
#include <Object.mqh>
//---
void OnStart()
{
CObject *object_first,*object_second;
//---
object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
object_second.Prev(object_first);
//--- use objects
//--- ...
//--- delete objects
delete object_first;
delete object_second;
}


Next

MQL5 Reference / Standard Library / Basic Class CObject / Next

Next

Gets a pointer to the next element of the list.

CObject* Next()

Returned Value

Pointer to the next item in the list. If the last item in the list, returns NULL.

Example:

//--- example for CObject::Next()
#include <Object.mqh>
//---
void OnStart()
{
CObject *object_first,*object_second;
//---
object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
object_second.Prev(object_first);
//--- use next object
CObject *object=object_first.Next();
//--- delete objects
delete object_first;
delete object_second;
}


Next

MQL5 Reference / Standard Library / Basic Class CObject / Next

Next

Sets the pointer to the next element of the list.

void Next(
CObject* object // Pointer to the next list item
)

Parameters

object

[in] New value pointer to the next list item.

Example:

//--- example for CObject::Next(CObject*)
#include <Object.mqh>
//---
void OnStart()
{
CObject *object_first,*object_second;
//---
object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
object_second.Prev(object_first);
//--- use objects
//--- ...
//--- delete objects
delete object_first;
delete object_second;
}


Load

MQL5 Reference / Standard Library / Basic Class CObject / Load

Load

Loads data item in the list from a file.

virtual bool Load(
int file_handle // handle to file
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (), binary

Returned Value

true - if successfully completed, false - if an error.

Note

Method Load (int) in class CObject always returns true and does not perform any action. If you want to load the data derived class from a file, the method Load (int) should be implemented.

Example:

//--- example for CObject::Load(int)
#include <Object.mqh>
//---
void OnStart()
{
int file_handle;
CObject *object=new CObject;
//---
if(object!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!object.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete object;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use object
//--- . . .
delete object;
}


Save

MQL5 Reference / Standard Library / Basic Class CObject / Save

Save

Saves data element list in the file.

virtual bool Save(
int file_handle // Handle to file
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (), binary

Returned Value

true - if successfully completed, false - if an error.

Note

Method Save (int) in class CObject always returns true and does not perform any action. If you want to save the data derived class in the file, the method Save (int) should be implemented.

Example:

//--- example for CObject::Save(int)
#include <Object.mqh>
//---
void OnStart()
{
int file_handle;
CObject *object=new CObject;
//---
if(object!=NULL)
{
printf("Object create error");
return;
}
//--- set objects data
//--- . . .
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!object.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete object;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
delete object;
}


Type

MQL5 Reference / Standard Library / Basic Class CObject / Type

Type

Gets the type identifier.

virtual int Type()

Returned Value

Type identifier (for CObject - 0).

Example:

//--- example for CObject::Type()
#include <Object.mqh>
//---
void OnStart()
{
CObject *object=new CObject;
//---
object=new CObject;
if(object ==NULL)
{
printf("Object create error");
return;
}
//--- get objects type
int type=object.Type();
//--- delete object
delete object;
}


Compare

MQL5 Reference / Standard Library / Basic Class CObject / Compare

Compare

Compares the data item in the list with data on another element of the list.

virtual int Compare(
CObject const * node, // Element
int mode=0 // Version
)

Parameters

node

[in] Pointer to a list item to compare

mode=0

[in] Variant Comparison

Returned Value

0 - in case the list items are equal, -1 - if the list item is less than the item in the list for comparison (node), 1 - if the list item more than item in the list for comparison (node).

Note

Method Compare () in class CObject always returns 0 and does not perform any action.If you want to compare data derived class, the method Compare (...) Should be implemented.The mode parameter should be used when implementing multivariate comparison.

Example:

//--- example for CObject::Compare(...)
#include <Object.mqh>
//---
void OnStart()
{
CObject *object_first,*object_second;
//---
object_first=new CObject;
if(object_first==NULL)
{
printf("Object create error");
return;
}
object_second=new CObject;
if(object_second==NULL)
{
printf("Object create error");
delete object_first;
return;
}
//--- set interconnect
object_first.Next(object_second);
object_second.Prev(object_first);
//--- compare objects
int result=object_first.Compare(object_second);
//--- delete objects
delete object_first;
delete object_second;
}


Data Structures

MQL5 Reference / Standard Library / Data Structures

Data Structures

This section contains the technical details of working with various data structures (arrays, linked lists, etc.) and description of the relevant components of the standard library MQL5.

Using classes of data structures, will save time when creating custom data stores of various formats (including composite data structures).

Standard library MQL5 (in terms of data sets) is placed in the working directory of the terminal in the folder Include \ Arrays

Data Arrays

Use of classes of dynamic arrays of data will save time when creating a custom data stores of various formats (including multidimensional arrays).

Standard library MQL5 (in terms of arrays of data) is placed in the working directory of the terminal in the folder Include \ Arrays.

Class Name | Class Purpose
CArray | Base class of dynamic data array
CArrayChar | Dynamic array of variables of type char or uchar
CArrayShort | Dynamic array of variables of type short or ushort
CArrayInt | Dynamic array of variables of type int or uint
CArrayLong | Dynamic array of variables of type long or ulong
CArrayFloat | Dynamic array of variables of type float
CArrayDouble | Dynamic array of variables of type double
CArrayString | Dynamic array of variables of type string
CArrayObj | Dynamic array of pointers CObject
CList | Provides the ability to work with a list of instances of CObject and his successors


CArray

MQL5 Reference / Standard Library / Data Structures / CArray

CArray

CArray class is the base class a dynamic array of variables.

Description

Class CArray provides the ability to work with a dynamic array of variables in the part of the attributes of management of memory allocation, sorting, and working with files.

Declaration

class CArray : public CObject

Title

#include <Arrays\Array.mqh>

Class Methods

Function-Method | Action
Step | Gets the step increment size of the array
Step | Set the increment size of the array
Total | Gets the number of elements in the array
Available | Gets the number of free elements of the array are available without additional memory allocation
Max | Gets the maximum possible size of the array without perevydeleniya memory
IsSorted | Gets sign sorted array to the specified option
SortMode | Gets the version of the sorting array
Sort | Sorts an array to the specified option
Save | Saves data array in the file
Load | Loads data array from a file


Step

MQL5 Reference / Standard Library / Data Structures / CArray / Step

Step

Gets the step increment size of the array.

int Step()

Returned Value

Increment size of the array.

Example:

//--- example for CArray::Step()
#include <Arrays\Array.mqh>
//---
void OnStart()
{
CArray *array=new CArray;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get resize step
int step=array.Step();
//--- use array
//--- ...
//--- delete array
delete array;
}


Step

MQL5 Reference / Standard Library / Data Structures / CArray / Step

Step

Set the increment size of the array.

bool Step(
int step // step
)

Parameters

step

[in] The new value of step increments in the size of the array.

Returned Value

true if successful, false - if there was an attempt to establish a step less than or equal to zero.

Example:

//--- example for CArray::Step(int)
#include <Arrays\Array.mqh>
//---
void OnStart()
{
CArray *array=new CArray;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- set resize step
bool result=array.Step(1024);
//--- use array
//--- ...
//--- delete array
delete array;
}


Total

MQL5 Reference / Standard Library / Data Structures / CArray / Total

Total

Gets the number of elements in the array.

int Total() const;

Returned Value

Number of elements in the array.

Example:

//--- example for CArray::Total()
#include <Arrays\Array.mqh>
//---
void OnStart()
{
CArray *array=new CArray;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- check total
int total=array.Total();
//--- use array
//--- ...
//--- delete array
delete array;
}


Available

MQL5 Reference / Standard Library / Data Structures / CArray / Available

Available

Gets the number of free elements of the array are available without additional memory allocation.

int Available()

Returned Value

Number of free elements of the array are available without additional memory allocation.

Example:

//--- example for CArray::Available()
#include <Arrays\Array.mqh>
//---
void OnStart()
{
CArray *array=new CArray;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- check available
int available=array.Available();
//--- use array
//--- ...
//--- delete array
delete array;
}


Max

MQL5 Reference / Standard Library / Data Structures / CArray / Max

Max

Gets the maximum possible size of the array without reallocation memory.

int Max()

Returned Value

The maximum possible size of the array without reallocation memory.

Example:

//--- example for CArray::Max()
#include <Arrays\Array.mqh>
//---
void OnStart()
{
CArray *array=new CArray;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- check maximum size
int max=array.Max();
//--- use array
//--- ...
//--- delete array
delete array;
}


IsSorted

MQL5 Reference / Standard Library / Data Structures / CArray / IsSorted

IsSorted

Gets sign sorted array to the specified option.

bool IsSorted(
int mode=0 // Sorting mode
)

Parameters

mode=0

[in] Tested version of the sort.

Returned Value

Flag of the sorted list. If the list is sorted by the specified version - true, otherwise - false.

Note

Symptom sorted array can not be changed directly. Symptom sorted set method Sort () and reset any methods to add / insert except InsertSort (...).

Example:

//--- example for CArray::IsSorted()
#include <Arrays\Array.mqh>
//---
void OnStart()
{
CArray *array=new CArray;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- check sorted
if(array.IsSorted())
{
//--- use methods for sorted array
//--- ...
}
//--- delete array
delete array;
}


SortMode

MQL5 Reference / Standard Library / Data Structures / CArray / SortMode

SortMode

Gets the version of the sorting array.

int SortMode() const;

Returned Value

Sorting mode.

Example:

//--- example for CArray::SortMode()
#include <Arrays\Array.mqh>
//---
void OnStart()
{
CArray *array=new CArray;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- check sort mode
int sort_mode=array.SortMode();
//--- use array
//--- ...
//--- delete array
delete array;
}


Sort

MQL5 Reference / Standard Library / Data Structures / CArray / Sort

Sort

Sorts an array to the specified option.

void Sort(
int mode=0 // Sorting mode
)

Parameters

mode=0

[in] Mode of array sorting.

Returned Value

No.

Note

Sorting an array is always ascending.For arrays of primitive data types (CArrayChar, CArrayShort, etc.), the parameter mode is not used.For the array CArrayObj, multivariate sort should be implemented in the method Sort (int) derived class.

Example:

//--- example for CArray::Sort(int)
#include <Arrays\Array.mqh>
//---
void OnStart()
{
CArray *array=new CArray;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- sorting by mode 0
array.Sort(0);
//--- use array
//--- ...
//--- delete array
delete array;
}


Save

MQL5 Reference / Standard Library / Data Structures / CArray / Save

Save

Saves data array in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArray::Save(int)
#include <Arrays\Array.mqh>
//---
void OnStart()
{
int file_handle;
CArray *array=new CArray;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- delete array
delete array;
}


Load

MQL5 Reference / Standard Library / Data Structures / CArray / Load

Load

Loads data array from a file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArray::Load(...)
#include <Arrays\Array.mqh>
//---
void OnStart()
{
int file_handle;
CArray *array=new CArray;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- delete array
delete array;
}


CArrayChar

MQL5 Reference / Standard Library / Data Structures / CArrayChar

CArrayChar

CArrayChar class is a class of dynamic array of variables of type char or uchar.

Description

Class CArrayChar provides the ability to work with a dynamic array of variables of type char or uchar.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.

Declaration

class CArrayChar : public CArray

Title

#include <Arrays\ArrayChar.mqh>

Class Method

Function-Method | Action
Reserve | Allocates memory to increase the size of the array
Resize | Sets a new (smaller) size of the array
Shutdown | Clears the array with a full memory release
Add | Adds an element to the end of the array
AddArray | Adds to the end of the array elements from another array
AddArray | Adds to the end of the array elements from another array
Insert | Inserts an element in the array to the specified position
InsertArray | Inserts an array of elements from another array with the specified position
InsertArray | Inserts an array of elements from another array with the specified position
AssignArray | Copies the array elements from another array
AssignArray | Copies the array elements from another array
Update | Changes the element at the specified position array
Shift | Moves an item from a given position in the array to the specified offset
Delete | Removes the element from the specified position array
DeleteRange | Deletes a group of elements from the specified position array
At | Gets the element from the specified position array
CompareArray | Compares array with another array
CompareArray | Compares array with another array
InsertSort | Inserts element in a sorted array
Search | Searches for an element equal to the model in sorted array
SearchGreat | Searches for an element of more samples in sorted array
SearchLess | Searches for an element less than the sample in the sorted array
SearchGreatOrEqual | Searches for an element greater than or equal to the model in sorted array
SearchLessOrEqual | Searches for an element less than or equal to the model in sorted array
SearchFirst | Finds the first element equal to the model in sorted array
SearchLast | Finds the last element equal to the model in sorted array
Save | Saves data array in the file
Load | Loads data array from a file
Type | Gets the type identifier of the array


Reserve

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Reserve

Reserve

Allocates memory to increase the size of the array.

bool Reserve(
int size // Number
)

Parameters

size

[in] The number of additional elements of the array.

Returned Value

true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase.

Note

To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayChar::Reserve(int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


Resize

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Resize

Resize

Sets a new (smaller) size of the array.

bool Resize(
int size // Size
)

Parameters

size

[in] New size of the array.

Returned Value

true if successful, false - if there was an attempt to set the size of less than or equal to zero.

Note

Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayChar::Resize(int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}


Shutdown

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Shutdown

Shutdown

Clears the array with a full memory release.

bool Shutdown()

Returned Value

true if successful, false - if an error occurred.

Example:

//--- example for CArrayChar::Shutdown()
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}


Add

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Add

Add

Adds an element to the end of the array.

bool Add(
char element // Element to add
)

Parameters

element

[in] value of the element to add to the array.

Returned Value

true if successful, false - if you can not add an element.

Example:

//--- example for CArrayChar::Add(char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayChar / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const char& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayChar::AddArray(const char &[])
#include <Arrays\ArrayChar.mqh>
//---
char src[];
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayChar / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const CArrayChar* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayChar-source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayChar::AddArray(const CArrayChar*)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayChar *src=new CArrayChar;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Insert

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Insert

Insert

Inserts an element in the array to the specified position.

bool Insert(
char element, // Element to insert
int pos // Position
)

Parameters

element

[in] Value of the element to be inserted into an array

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayChar::Insert(char,int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayChar / InsertArray

InsertArray

Inserts an array of elements from another array with the specified position.

bool InsertArray(
const char& src[], // Source array
int pos // Position
)

Parameters

src[]

[in] Reference to an array of source elements to insert

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayChar::InsertArray(const char &[],int)
#include <Arrays\ArrayChar.mqh>
//---
char src[];
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayChar / InsertArray

InsertArray

Inserts an array of elements from another array with the specified position.

bool InsertArray(
CArrayChar* src, // Pointer to the source
int pos // Position
)

Parameters

src

[in] Pointer to an instance of class CArrayChar-source elements to insert.

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayChar::InsertArray(const CArrayChar*,int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayChar *src=new CArrayChar;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayChar / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const char& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayChar::AssignArray(const char &[])
#include <Arrays\ArrayChar.mqh>
//---
char src[];
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayChar / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const CArrayChar* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayChar-source element to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayChar::AssignArray(const CArrayChar*)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayChar *src =new CArrayChar;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Update

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Update

Update

Changes the element at the specified position array.

bool Update(
int pos, // Position
char element // Value
)

Parameters

pos

[in] Position of the element in the array to change

element

[in] New value element

Returned Value

true if successful, false - if you can not change the element.

Example:

//--- example for CArrayChar::Update(int,char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,'A'))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}


Shift

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Shift

Shift

Moves an item from a given position in the array to the specified offset.

bool Shift(
int pos, // Position
int shift // Value
)

Parameters

pos

[in] Position of the moved element array

shift

[in] The value of displacement (both positive and negative).

Returned Value

true if successful, false - if you can not move the item.

Example:

//--- example for CArrayChar::Shift(int,int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}


Delete

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Delete

Delete

Removes the element from the given position in the array.

bool Delete(
int pos // Position
)

Parameters

pos

[in] Position removes the element in the array.

Returned Value

true if successful, false - if you can not remove the element.

Example:

//--- example for CArrayChar::Delete(int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


DeleteRange

MQL5 Reference / Standard Library / Data Structures / CArrayChar / DeleteRange

DeleteRange

Deletes a group of elements from a given position in the array.

bool DeleteRange(
int from, // Position of the first element
int to // Positions of the last element
)

Parameters

from

[in] Position of the first removes the element in the array.

to

[in] Position of the last deleted element in the array.

Returned Value

true if successful, false - if you can not remove elements.

Example:

//--- example for CArrayChar::DeleteRange(int,int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


At

MQL5 Reference / Standard Library / Data Structures / CArrayChar / At

At

Gets the element from the given position in the array.

char At(
int pos // Position
)

Parameters

pos

[in] Position of the desired element in the array.

Returned Value

The value of the element in case of success, CHAR_MAX-if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE).

Note

Of course, CHAR_MAX may be a valid value of an array element, so having a value, always check the last error code.

Example:

//--- example for CArrayChar::At(int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
char result=array.At(i);
if(result==CHAR_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- error of reading from array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayChar / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const char& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayChar::CompareArray(const char &[])
#include <Arrays\ArrayChar.mqh>
//---
char src[];
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayChar / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const CArrayChar* src // Pointer to the sources
)

Parameters

src

[in] Pointer to an instance of class CArrayChar-source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayChar::CompareArray(const CArrayChar*)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayChar *src=new CArrayChar;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}


InsertSort

MQL5 Reference / Standard Library / Data Structures / CArrayChar / InsertSort

InsertSort

Inserts element in a sorted array.

bool InsertSort(
char element // Element to insert
)

Parameters

element

[in] Value of the element to be inserted into a sorted array

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayChar::InsertSort(char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort('A'))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}


Search

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Search

Search

Searches for an element equal to the sample in the sorted array.

int Search(
char element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayChar::Search(char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search('A')!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreat

MQL5 Reference / Standard Library / Data Structures / CArrayChar / SearchGreat

SearchGreat

Searches for an element of more samples in sorted array.

int SearchGreat(
char element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayChar::SearchGreat(char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat('A')!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLess

MQL5 Reference / Standard Library / Data Structures / CArrayChar / SearchLess

SearchLess

Searches for an element less than the sample in the sorted array.

int SearchLess(
char element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayChar::SearchLess(char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess('A')!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreatOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayChar / SearchGreatOrEqual

SearchGreatOrEqual

Searches for an element greater than or equal to the sample in the sorted array

int SearchGreatOrEqual(
char element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayChar::SearchGreatOrEqual(char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual('A')!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLessOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayChar / SearchLessOrEqual

SearchLessOrEqual

Searches for an element less than or equal to the sample in the sorted array.

int SearchLessOrEqual(
char element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayChar::SearchLessOrEqual(char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual('A')!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchFirst

MQL5 Reference / Standard Library / Data Structures / CArrayChar / SearchFirst

SearchFirst

Finds the first element equal to the sample in the sorted array.

int SearchFirst(
char element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayChar::SearchFirst(char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst('A')!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLast

MQL5 Reference / Standard Library / Data Structures / CArrayChar / SearchLast

SearchLast

Finds the last element equal to the model in sorted array.

int SearchLast(
char element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayChar::SearchLast(char)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast('A')!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


Save

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Save

Save

Saves data array in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayChar::Save(int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
int file_handle;
CArrayChar *array=new CArrayChar;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- delete array
delete array;
}


Load

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Load

Load

Loads data array from a file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayChar::Load(int)
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
int file_handle;
CArrayChar *array=new CArrayChar;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use arrays elements
for(int i=0;i<array.Total();i++)
{
printf("Element [% d] = '% c'",i,array.At(i));
}
//--- delete array
delete array;
}


Type

MQL5 Reference / Standard Library / Data Structures / CArrayChar / Type

Type

Gets the type identifier of the array.

virtual int Type()

Returned Value

ID type of the array (for CArrayChar - 77).

Example:

//--- example for CArrayChar::Type()
#include <Arrays\ArrayChar.mqh>
//---
void OnStart()
{
CArrayChar *array=new CArrayChar;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}


CArrayShort

MQL5 Reference / Standard Library / Data Structures / CArrayShort

CArrayShort

CArrayShort class is a class of dynamic array of variables of type short or ushort.

Description

Class CArrayShort provides the ability to work with a dynamic array of variables of type short or ushort.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.

Declaration

class CArrayShort : public CArray

Title

#include <Arrays\ArrayShort.mqh>

Class Methods

Function-Method | Action
Reserve | Allocates memory to increase the size of the array
Resize | Sets a new (smaller) size of the array
Shutdown | Clears the array with a full memory release
Add | Adds an element to the end of the array
AddArray | Adds to the end of the array elements from another array
AddArray | Adds to the end of the array elements from another array
Insert | Inserts an element in the array to the specified position
InsertArray | Inserts an array of elements from another array with the specified position
InsertArray | Inserts an array of elements from another array with the specified position
AssignArray | Copies the array elements from another array
AssignArray | Copies the array elements from another array
Update | Changes the element at the specified position array
Shift | Moves an item from a given position in the array to the specified offset
Delete | Removes the element from the specified position array
DeleteRange | Deletes a group of elements from the specified position array
At | Gets the element from the specified position array
CompareArray | Compares array with another array
CompareArray | Compares array with another array
InsertSort | Inserts element in a sorted array
Search | Searches for an element equal to the model in sorted array
SearchGreat | Searches for an element of more samples in sorted array
SearchLess | Searches for an element less than the sample in the sorted array
SearchGreatOrEqual | Searches for an element greater than or equal to the model in sorted array
SearchLessOrEqual | Searches for an element less than or equal to the model in sorted array
SearchFirst | Finds the first element equal to the model in sorted array
SearchLast | Finds the last element equal to the model in sorted array
Save | Saves data array in the file
Load | Loads data array from a file
Type | Gets the type identifier of the array


Reserve

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Reserve

Reserve

Allocates memory to increase the size of the array.

bool Reserve(
int size // Number
)

Parameters

size

[in] The number of additional elements of the array.

Returned Value

true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase.

Note

To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayShort::Reserve(int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


Resize

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Resize

Resize

Sets a new (smaller) size of the array.

bool Resize(
int size // Size
)

Parameters

size

[in] New size of the array.

Returned Value

true if successful, false - if there was an attempt to set the size of less than or equal to zero.

Note

Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayShort::Resize(int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}


Shutdown

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Shutdown

Shutdown

Clears the array with a full memory release.

bool Shutdown()

Returned Value

true if successful, false - if an error occurred.

Example:

//--- example for CArrayShort::Shutdown()
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}


Add

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Add

Add

Adds an element to the end of the array.

bool Add(
short element // Element to add
)

Parameters

element

[in] Value of the element to add to the array.

Returned Value

true if successful, false - if you can not add an element.

Example:

//--- example for CArrayShort::Add(short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayShort / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const short& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayShort::AddArray(const short &[])
#include <Arrays\ArrayShort.mqh>
//---
short src[];
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayShort / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const CArrayShort* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayShort-source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayShort::AddArray(const CArrayShort*)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayShort *src=new CArrayShort;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Insert

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Insert

Insert

Inserts an element in the array to the specified position.

bool Insert(
short element, // Element to insert
int pos // Position
)

Parameters

element

[in] Value of the element to be inserted into an array

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayShort::Insert(short,int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayShort / InsertArray

InsertArray

Inserts an array of elements from another array specified position.

bool InsertArray(
const short& src[], // Source array
int pos // Position
)

Parameters

src[]

[in] Reference to an array of source elements to insert

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayShort::InsertArray(const short &[],int)
#include <Arrays\ArrayShort.mqh>
//---
short src[];
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayShort / InsertArray

InsertArray

Inserts an array of elements from another array ukazannogy position.

bool InsertArray(
CArrayShort* src, // Pointer to the source
int pos // Position
)

Parameters

src

[in] Pointer to an instance of class CArrayShort-source elements to insert.

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayShort::InsertArray(const CArrayShort*,int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayShort *src=new CArrayShort;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayShort / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const short& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayShort::AssignArray(const short &[])
#include <Arrays\ArrayShort.mqh>
//---
short src[];
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayShort / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const CArrayShort* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayShort-source element to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayShort::AssignArray(const CArrayShort*)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayShort *src =new CArrayShort;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Update

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Update

Update

Changes the element at the specified position array.

bool Update(
int pos, // Position
short element // Value
)

Parameters

pos

[in] Position of the element in the array to change

element

[in] New value element

Returned Value

true if successful, false - if you can not change the element.

Example:

//--- example for CArrayShort::Update(int,short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,100))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}


Shift

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Shift

Shift

Moves an item from a given position in the array to the specified offset.

bool Shift(
int pos, // Positions
int shift // Shift
)

Parameters

pos

[in] Position of the moved element array

shift

[in] The value of displacement (both positive and negative).

Returned Value

true if successful, false - if you can not move the item.

Example:

//--- example for CArrayShort::Shift(int,int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}


Delete

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Delete

Delete

Removes the element from the given position in the array.

bool Delete(
int pos // Position
)

Parameters

pos

[in] Position removes the element in the array.

Returned Value

true if successful, false - if you can not remove the element.

Example:

//--- example for CArrayShort::Delete(int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


DeleteRange

MQL5 Reference / Standard Library / Data Structures / CArrayShort / DeleteRange

DeleteRange

Deletes a group of elements from a given position in the array.

bool DeleteRange(
int from, // Position of the first element
int to // Position of the lase element
)

Parameters

from

[in] Position of the first removes the element in the array.

to

[in] Position of the last deleted element in the array.

Returned Value

true if successful, false - if you can not remove elements.

Example:

//--- example for CArrayShort::DeleteRange(int,int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


At

MQL5 Reference / Standard Library / Data Structures / CArrayShort / At

At

Gets the element from the given position in the array.

short At(
int pos // Position
)

Parameters

pos

[in] Position of the desired element in the array.

Returned Value

The value of the element in case of success, SHORT_MAX-if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE).

Note

Of course, SHORT_MAX may be a valid value of an array element, so having a value, always check the last error code.

Example:

//--- example for CArrayShort::At(int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
short result=array.At(i);
if(result==SHORT_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- error of reading from array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayShort / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const short& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayShort::CompareArray(const short &[])
#include <Arrays\ArrayShort.mqh>
//---
short src[];
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayShort / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const CArrayShort* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayShort-source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayShort::CompareArray(const CArrayShort*)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayShort *src=new CArrayShort;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}


InsertSort

MQL5 Reference / Standard Library / Data Structures / CArrayShort / InsertSort

InsertSort

Inserts element in a sorted array.

bool InsertSort(
short element // Element to insert
)

Parameters

element

[in] Value of the element to be inserted into a sorted array

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayShort::InsertSort(short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(100))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}


Search

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Search

Search

Searches for an element equal to the sample in the sorted array.

int Search(
short element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayShort::Search(short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(100)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreat

MQL5 Reference / Standard Library / Data Structures / CArrayShort / SearchGreat

SearchGreat

Searches for an element of more samples in sorted array.

int SearchGreat(
short element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayShort::SearchGreat(short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(100)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLess

MQL5 Reference / Standard Library / Data Structures / CArrayShort / SearchLess

SearchLess

Searches for an element less than the sample in the sorted array.

int SearchLess(
short element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayShort::SearchLess(short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(100)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreatOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayShort / SearchGreatOrEqual

SearchGreatOrEqual

Searches for an element greater than or equal to the sample in the sorted array.

int SearchGreatOrEqual(
short element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayShort::SearchGreatOrEqual(short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(100)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLessOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayShort / SearchLessOrEqual

SearchLessOrEqual

Searches for an element less than or equal to the sample in the sorted array.

int SearchLessOrEqual(
short element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayShort::SearchLessOrEqual(short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(100)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchFirst

MQL5 Reference / Standard Library / Data Structures / CArrayShort / SearchFirst

SearchFirst

Finds the first element equal to the sample in the sorted array.

int SearchFirst(
short element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayShort::SearchFirst(short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(100)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLast

MQL5 Reference / Standard Library / Data Structures / CArrayShort / SearchLast

SearchLast

Finds the last element equal to the model in sorted array.

int SearchLast(
short element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayShort::SearchLast(short)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(100)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


Save

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Save

Save

Saves data array in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayShort::Save(int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
int file_handle;
CArrayShort *array=new CArrayShort;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- add 100 arrays elements
for(int i=0;i<100;i++)
{
array.Add(i);
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
delete array;
}


Load

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Load

Load

Loads data array from a file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayShort::Load(int)
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
int file_handle;
CArrayShort *array=new CArrayShort;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use arrays elements
for(int i=0;i<array.Total();i++)
{
printf("Element[%d]=%d",i,array.At(i));
}
delete array;
}


Type

MQL5 Reference / Standard Library / Data Structures / CArrayShort / Type

Type

Gets the type identifier of the array.

virtual int Type()

Returned Value

ID type of the array (for CArrayShort - 82).

Example:

//--- example for CArrayShort::Type()
#include <Arrays\ArrayShort.mqh>
//---
void OnStart()
{
CArrayShort *array=new CArrayShort;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}


CArrayInt

MQL5 Reference / Standard Library / Data Structures / CArrayInt

CArrayInt

CArrayInt class is a class of dynamic array of variables of type int or uint.

Description

Class CArrayInt provides the ability to work with a dynamic array of variables of type int or uint.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.

Declaration

class CArrayInt : public CArray

Title

#include <Arrays\ArrayInt.mqh>

Class Methods

Function-Method | Actions
Reserve | Allocates memory to increase the size of the array
Resize | Sets a new (smaller) size of the array
Shutdown | Clears the array with a full memory release
Add | Adds an element to the end of the array
AddArray | Adds to the end of the array elements from another array
AddArray | Adds to the end of the array elements from another array
Insert | Inserts an element in the array to the specified position
InsertArray | Inserts an array of elements from another array with the specified position
InsertArray | Inserts an array of elements from another array with the specified position
AssignArray | Copies the array elements from another array
AssignArray | Copies the array elements from another array
Update | Changes the element at the specified position array
Shift | Moves an item from a given position in the array to the specified offset
Delete | Removes the element from the specified position array
DeleteRange | Deletes a group of elements from the specified position array
At | Gets the element from the specified position array
CompareArray | Compares array with another array
CompareArray | Compares array with another array
InsertSort | Inserts element in a sorted array
Search | Searches for an element equal to the model in sorted array
SearchGreat | Searches for an element of more samples in sorted array
SearchLess | Searches for an element less than the sample in the sorted array
SearchGreatOrEqual | Searches for an element greater than or equal to the model in sorted array
SearchLessOrEqual | Searches for an element less than or equal to the model in sorted array
SearchFirst | Finds the first element equal to the model in sorted array
SearchLast | Finds the last element equal to the model in sorted array
Save | Saves data array in the file
Load | Loads data array from a file
Type | Gets the type identifier of the array


Reserve

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Reserve

Reserve

Allocates memory to increase the size of the array.

bool Reserve(
int size // Number
)

Parameters

size

[in] The number of additional elements of the array.

Returned Value

true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase.

Note

To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayInt::Reserve(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


Resize

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Resize

Resize

Sets a new (smaller) size of the array.

bool Resize(
int size // Number
)

Parameters

size

[in] New size of the array.

Returned Value

true if successful, false - if there was an attempt to set the size of less than or equal to zero.

Note

Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayInt::Resize(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}


Shutdown

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Shutdown

Shutdown

Clears the array with a full memory release.

bool Shutdown()

Returned Value

true if successful, false - if an error occurred.

Example:

//--- example for CArrayInt::Shutdown()
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}


Add

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Add

Add

Adds an element to the end of the array.

bool Add(
int element // Element to add
)

Parameters

element

[in] value of the element to add to the array.

Returned Value

true if successful, false - if you can not add an element.

Example:

//--- example for CArrayInt::Add(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayInt / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const int& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayInt::AddArray(const int &[])
#include <Arrays\ArrayInt.mqh>
//---
int src[];
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayInt / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const CArrayInt* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayInt-source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayInt::AddArray(const CArrayInt*)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayInt *src=new CArrayInt;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Insert

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Insert

Insert

Inserts an element in the array to the specified position.

bool Insert(
int element, // Element to insert
int pos // Position
)

Parameters

element

[in] Value of the element to be inserted into an array

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayInt::Insert(int,int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayInt / InsertArray

InsertArray

Inserts an array of elements from another array specified position.

bool InsertArray(
const int& src[], // Source array
int pos // Position
)

Parameters

src[]

[in] Reference to an array of source elements to insert

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayInt::InsertArray(const int &[],int)
#include <Arrays\ArrayInt.mqh>
//---
int src[];
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayInt / InsertArray

InsertArray

Inserts an array of elements from another array specified position.

bool InsertArray(
CArrayInt* src, // Pointer to the source
int pos // Position
)

Parameters

src

[in] Pointer to an instance of class CArrayInt-source elements to insert.

pos

[in] Position in the array to insert.

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayInt::InsertArray(const CArrayInt*,int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayInt *src=new CArrayInt;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayInt / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const int& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayInt::AssignArray(const int &[])
#include <Arrays\ArrayInt.mqh>
//---
int src[];
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayInt / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const CArrayInt* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayInt-source element to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayInt::AssignArray(const CArrayInt*)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayInt *src =new CArrayInt;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Update

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Update

Update

Changes the element at the specified position array.

bool Update(
int pos, // Position
int element // Value
)

Parameters

pos

[in] Position of the element in the array to change.

element

[in] New value element

Returned Value

true if successful, false - if you can not change the element.

Example:

//--- example for CArrayInt::Update(int,int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,10000))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}


Shift

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Shift

Shift

Moves an item from a given position in the array to the specified offset.

bool Shift(
int pos, // Position
int shift // Shift
)

Parameters

pos

[in] Position of the moved element array

shift

[in] The value of displacement (both positive and negative).

Returned Value

true if successful, false - if you can not move the item.

Example:

//--- example for CArrayInt::Shift(int,int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}


Delete

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Delete

Delete

Removes the element from the given position in the array.

bool Delete(
int pos // Position
)

Parameters

pos

[in] Position removes the element in the array.

Returned Value

true if successful, false - if you can not remove the element.

Example:

//--- example for CArrayInt::Delete(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


DeleteRange

MQL5 Reference / Standard Library / Data Structures / CArrayInt / DeleteRange

DeleteRange

Deletes a group of elements from a given position in the array.

bool DeleteRange(
int from, // Position of the first element
int to // Position of the last element
)

Parameters

from

[in] Position of the first removes the element in the array.

to

[in] Position of the last deleted element in the array.

Returned Value

true if successful, false - if you can not remove elements.

Example:

//--- example for CArrayInt::DeleteRange(int,int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


At

MQL5 Reference / Standard Library / Data Structures / CArrayInt / At

At

Gets the element from the given position in the array.

int At(
int pos // Position
)

Parameters

pos

[in] Position of the desired element in the array.

Returned Value

The value of the element in case of success, INT_MAX-if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE).

Note

Of course, INT_MAX could be a valid value of an array element, so having a value, always check the last error code.

Example:

//--- example for CArrayInt::At(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
int result=array.At(i);
if(result==INT_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- error of reading from array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayInt / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const int& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayInt::CompareArray(const int &[])
#include <Arrays\ArrayInt.mqh>
//---
int src[];
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayInt / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const CArrayInt* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayInt-source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayInt::CompareArray(const CArrayInt*)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayInt *src=new CArrayInt;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}


InsertSort

MQL5 Reference / Standard Library / Data Structures / CArrayInt / InsertSort

InsertSort

Inserts element in a sorted array.

bool InsertSort(
int element // Element to insert
)

Parameters

element

[in] value of the element to be inserted into a sorted array

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayInt::InsertSort(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(10000))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}


Search

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Search

Search

Searches for an element equal to the sample in the sorted array.

int Search(
int element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayInt::Search(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(10000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreat

MQL5 Reference / Standard Library / Data Structures / CArrayInt / SearchGreat

SearchGreat

Searches for an element of more samples in sorted array.

int SearchGreat(
int element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayInt::SearchGreat(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(10000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLess

MQL5 Reference / Standard Library / Data Structures / CArrayInt / SearchLess

SearchLess

Searches for an element less than the sample in the sorted array.

int SearchLess(
int element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayInt::SearchLess(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(10000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreatOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayInt / SearchGreatOrEqual

SearchGreatOrEqual

Searches for an element greater than or equal to the sample in the sorted array.

int SearchGreatOrEqual(
int element / Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayInt::SearchGreatOrEqual(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(10000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLessOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayInt / SearchLessOrEqual

SearchLessOrEqual

Searches for an element less than or equal to the sample in the sorted array.

int SearchLessOrEqual(
int element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayInt::SearchLessOrEqual(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(10000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchFirst

MQL5 Reference / Standard Library / Data Structures / CArrayInt / SearchFirst

SearchFirst

Finds the first element equal to the sample in the sorted array.

int SearchFirst(
int element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayInt:: SearchFirst(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(10000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLast

MQL5 Reference / Standard Library / Data Structures / CArrayInt / SearchLast

SearchLast

Finds the last element equal to the model in sorted array.

int SearchLast(
int element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayInt::SearchLast(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(10000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


Save

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Save

Save

Saves data array in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayInt::Save(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
int file_handle;
CArrayInt *array=new CArrayInt;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- add 100 arrays elements
for(int i=0;i<100;i++)
{
array.Add(i);
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
delete array;
}


Load

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Load

Load

Loads data array from a file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayInt::Load(int)
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
int file_handle;
CArrayInt *array=new CArrayInt;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use arrays elements
for(int i=0;i<array.Total();i++)
{
printf("Element[%d]=%d",i,array.At(i));
}
delete array;
}


Type

MQL5 Reference / Standard Library / Data Structures / CArrayInt / Type

Type

Gets the type identifier of the array.

virtual int Type()

Returned Value

ID type of the array (for CArrayInt - 82).

Example:

//--- example for CArrayInt::Type()
#include <Arrays\ArrayInt.mqh>
//---
void OnStart()
{
CArrayInt *array=new CArrayInt;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}


CArrayLong

MQL5 Reference / Standard Library / Data Structures / CArrayLong

CArrayLong

CArrayLong class is a class of dynamic array of variables of type long or ulong.

Description

Class CArrayLong provides the ability to work with a dynamic array of variables of type long or ulong.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.

Declaration

class CArrayLong : public CArray

Title

#include <Arrays\ArrayLong.mqh>

Class Method

Function-Method | Action
Reserve | Allocates memory to increase the size of the array
Resize | Sets a new (smaller) size of the array
Shutdown | Clears the array with a full memory release
Add | Adds an element to the end of the array
AddArray | Adds to the end of the array elements from another array
AddArray | Adds to the end of the array elements from another array
Insert | Inserts an element in the array to the specified position
InsertArray | Inserts an array of elements from another array with the specified position
InsertArray | Inserts an array of elements from another array with the specified position
AssignArray | Copies the array elements from another array
AssignArray | Copies the array elements from another array
Update | Changes the element at the specified position array
Shift | Moves an item from a given position in the array to the specified offset
Delete | Removes the element from the specified position array
DeleteRange | Deletes a group of elements from the specified position array
At | Gets the element from the specified position array
CompareArray | Compares array with another array
CompareArray | Compares array with another array
InsertSort | Inserts element in a sorted array
Search | Searches for an element equal to the model in sorted array
SearchGreat | Searches for an element of more samples in sorted array
SearchLess | Searches for an element less than the sample in the sorted array
SearchGreatOrEqual | Searches for an element greater than or equal to the model in sorted array
SearchLessOrEqual | Searches for an element less than or equal to the model in sorted array
SearchFirst | Finds the first element equal to the model in sorted array
SearchLast | Finds the last element equal to the model in sorted array
Save | Saves data array in the file
Load | Loads data array from a file
Type | Gets the type identifier of the array


Reserve

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Reserve

Reserve

Allocates memory to increase the size of the array.

bool Reserve(
int size // Number
)

Parameters

size

[in] The number of additional elements of the array.

Returned Value

true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase.

Note

To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayLong::Reserve(int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


Resize

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Resize

Resize

Sets a new (smaller) size of the array.

bool Resize(
int size // Size
)

Parameters

size

[in] New size of the array.

Returned Value

true if successful, false - if there was an attempt to set the size of less than or equal to zero.

Note

Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayLong::Resize(int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}


Shutdown

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Shutdown

Shutdown

Clears the array with a full memory release.

bool Shutdown()

Returned Value

true if successful, false - if an error occurred.

Example:

//--- example for CArrayLong::Shutdown()
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}


Add

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Add

Add

Adds an element to the end of the array.

bool Add(
long element // Element to add
)

Parameters

element

[in] Value of the element to add to the array.

Returned Value

true if successful, false - if you can not add an element.

Example:

//--- example for CArrayLong::Add(long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayLong / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const long& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayLong::AddArray(const long &[])
#include <Arrays\ArrayLong.mqh>
//---
long src[];
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayLong / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const CArrayLong* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayLong-source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayLong::AddArray(const CArrayLong*)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayLong *src=new CArrayLong;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Insert

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Insert

Insert

Inserts an element in the array to the specified position.

bool Insert(
long element, // Element to insert
int pos // Position
)

Parameters

element

[in] Value of the element to be inserted into an array

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayLong::Insert(long,int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayLong / InsertArray

InsertArray

Inserts an array of elements from another array ukazannogy position.

bool InsertArray(
const long& src[], // Source array
int pos // Position
)

Parameters

src[]

[in] Reference to an array of source elements to insert

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayLong::InsertArray(const long &[],int)
#include <Arrays\ArrayLong.mqh>
//---
long src[];
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayLong / InsertArray

InsertArray

Inserts an array of elements from another array ukazannogy position.

bool InsertArray(
CArrayLong* src, // Pointer to the source
int pos // Position
)

Parameters

src

[in] Pointer to an instance of class CArrayLong-source elements to insert.

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayLong::InsertArray(const CArrayLong*,int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayLong *src=new CArrayLong;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayLong / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const long& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayLong::AssignArray(const long &[])
#include <Arrays\ArrayLong.mqh>
//---
long src[];
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayLong / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const CArrayLong* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayLong-source element to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayLong::AssignArray(const CArrayLong*)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayLong *src =new CArrayLong;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Update

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Update

Update

Changes the element at the specified position array.

bool Update(
int pos, // Position
long element // Value
)

Parameters

pos

[in] Position of the element in the array to change

element

[in] New value element

Returned Value

true if successful, false - if you can not change the element.

Example:

//--- example for CArrayLong::Update(int,long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,1000000))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}


Shift

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Shift

Shift

Moves an item from a given position in the array to the specified offset.

bool Shift(
int pos, // Position
int shift // Shift
)

Parameters

pos

[in] Position of the moved element array

shift

[in] The value of displacement (both positive and negative).

Returned Value

true if successful, false - if you can not move the item.

Example:

//--- example for CArrayLong::Shift(int,int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}


Delete

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Delete

Delete

Removes the element from the given position in the array.

bool Delete(
int pos // Position
)

Parameters

pos

[in] Position removes the element in the array.

Returned Value

true if successful, false - if you can not remove the element.

Example:

//--- example for CArrayLong::Delete(int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


DeleteRange

MQL5 Reference / Standard Library / Data Structures / CArrayLong / DeleteRange

DeleteRange

Deletes a group of elements from a given position in the array.

bool DeleteRange(
int from, // Position of the first element
int to // Position of the last element
)

Parameters

from

[in] Position of the first removes the element in the array.

to

[in] Position of the last deleted element in the array.

Returned Value

true if successful, false - if you can not remove elements.

Example:

//--- example for CArrayLong::DeleteRange(int,int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


At

MQL5 Reference / Standard Library / Data Structures / CArrayLong / At

At

Gets the element from the given position in the array.

long At(
int pos // Position
)

Parameters

pos

[in] Position of the desired element in the array.

Returned Value

The value of the element in case of success, LONG_MAX if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE).

Note

Of course, LONG_MAX may be a valid value of an array element, so having a value, always check the last error code.

Example:

//--- example for CArrayLong::At(int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
long result=array.At(i);
if(result==LONG_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- Error reading from the array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayLong / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const long& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayLong::CompareArray(const long &[])
#include <Arrays\ArrayLong.mqh>
//---
long src[];
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayLong / CompareArray

CompareArrayconst

Compares array with another array.

bool CompareArrayconst(
const CArrayLong* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayLong-source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayLong::CompareArray(const CArrayLong*)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayLong *src=new CArrayLong;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}


InsertSort

MQL5 Reference / Standard Library / Data Structures / CArrayLong / InsertSort

InsertSort

Inserts element in a sorted array.

bool InsertSort(
long element // Element to insert
)

Parameters

element

[in] Value of the element to be inserted into a sorted array

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayLong::InsertSort(long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(1000000))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}


Search

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Search

Search

Searches for an element equal to the model in sorted array.

int Search(
long element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayLong::Search(long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(1000000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreat

MQL5 Reference / Standard Library / Data Structures / CArrayLong / SearchGreat

SearchGreat

Searches for an element of larger sample, in sorted array.

int SearchGreat(
long element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayLong::SearchGreat(long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(1000000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLess

MQL5 Reference / Standard Library / Data Structures / CArrayLong / SearchLess

SearchLess

Searches for an element less than the sample in the sorted array.

int SearchLess(
long element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayLong::SearchLess(long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(1000000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreatOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayLong / SearchGreatOrEqual

SearchGreatOrEqual

Searches for an element greater than or equal to the model in sorted array.

int SearchGreatOrEqual(
long element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayLong::SearchGreatOrEqual(long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(1000000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLessOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayLong / SearchLessOrEqual

SearchLessOrEqual

Searches for an element less than or equal to the model in sorted array.

int SearchLessOrEqual(
long element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayLong::SearchLessOrEqual(long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(1000000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchFirst

MQL5 Reference / Standard Library / Data Structures / CArrayLong / SearchFirst

SearchFirst

Finds the first element equal to the model in sorted array.

int SearchFirst(
long element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayLong::SearchFirst(long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(1000000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLast

MQL5 Reference / Standard Library / Data Structures / CArrayLong / SearchLast

SearchLast

Finds the last element equal to the model in sorted array.

int SearchLast(
long element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayLong::SearchLast(long)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(1000000)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


Save

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Save

Save

Saves data array in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayLong::Save(int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
int file_handle;
CArrayLong *array=new CArrayLong;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- add 100 arrays elements
for(int i=0;i<100;i++)
{
array.Add(i);
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
delete array;
}


Load

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Load

Load

Loads data array from a file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayLong::Load(int)
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
int file_handle;
CArrayLong *array=new CArrayLong;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use arrays elements
for(int i=0;i<array.Total();i++)
{
printf("Element[%d]=%I64",i,array.At(i));
}
delete array;
}


Type

MQL5 Reference / Standard Library / Data Structures / CArrayLong / Type

Type

Gets the type identifier of the array.

virtual int Type()

Returned Value

ID type of the array (for CArrayLong - 84).

Example:

//--- example for CArrayLong::Type()
#include <Arrays\ArrayLong.mqh>
//---
void OnStart()
{
CArrayLong *array=new CArrayLong;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}


CArrayFloat

MQL5 Reference / Standard Library / Data Structures / CArrayFloat

CArrayFloat

CArrayFloat class is a class of dynamic array of variables of type float.

Description

Class CArrayFloat provides the ability to work with a dynamic array of variables of type float.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.

Declaration

class CArrayFloat : public CArray

Title

#include <Arrays\ArrayFloat.mqh>

Class Methods

Function-Method | Action
Delta | Set the comparison tolerance
Reserve | Allocates memory to increase the size of the array
Resize | Sets a new (smaller) size of the array
Shutdown | Clears the array with a full memory release
Add | Adds an element to the end of the array
AddArray | Adds to the end of the array elements from another array
AddArray | Adds to the end of the array elements from another array
Insert | Inserts an element in the array to the specified position
InsertArray | Inserts an array of elements from another array with the specified position
InsertArray | Inserts an array of elements from another array with the specified position
AssignArray | Copies the array elements from another array
AssignArray | Copies the array elements from another array
Update | Changes the element at the specified position array
Shift | Moves an item from a given position in the array to the specified offset
Delete | Removes the element from the specified position array
DeleteRange | Deletes a group of elements from the specified position array
At | Gets the element from the specified position array
CompareArray | Compares array with another array
CompareArray | Compares array with another array
InsertSort | Inserts element in a sorted array
Search | Searches for an element equal to the model in sorted array
SearchGreat | Searches for an element of more samples in sorted array
SearchLess | Searches for an element less than the sample in the sorted array
SearchGreatOrEqual | Searches for an element greater than or equal to the model in sorted array
SearchLessOrEqual | Searches for an element less than or equal to the model in sorted array
SearchFirst | Finds the first element equal to the model in sorted array
SearchLast | Finds the last element equal to the model in sorted array
Save | Saves data array in the file
Load | Loads data array from a file
Type | Gets the type identifier of the array


Delta

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Delta

Delta

Set tolerance comparison.

void Delta(
float delta // Tolerance
)

Parameters

delta

[in] the new value of the admission of comparison.

Returned Value

No

Note

Admission of comparison used in the search. Values are considered equal if their difference is less than or equal to tolerance. The default tolerance is 0.0.

Example:

//--- example for CArrayFloat::Delta(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- set compare variation
array.Delta(0.001);
//--- use array
//--- . . .
//--- delete array
delete array;
}


Reserve

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Reserve

Reserve

Allocates memory to increase the size of the array.

bool Reserve(
int size // Number
)

Parameters

size

[in] The number of additional elements of the array.

Returned Value

true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase.

Note

To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayFloat::Reserve(int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


Resize

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Resize

Resize

Sets a new (smaller) size of the array.

bool Resize(
int size // Size
)

Parameters

size

[in] New size of the array.

Returned Value

true if successful, false - if there was an attempt to set the size of less than or equal to zero.

Note

Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayFloat::Resize(int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}


Shutdown

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Shutdown

Shutdown

Clears the array with a full memory release.

bool Shutdown()

Returned Value

true if successful, false - if an error occurred.

Example:

//--- example for CArrayFloat::Shutdown()
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}


Add

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Add

Add

Adds an element to the end of the array.

bool Add(
float element // Element to add
)

Parameters

element

[in] Value of the element to add to the array.

Returned Value

true if successful, false - if you can not add an element.

Example:

//--- example for CArrayFloat::Add(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const float& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayFloat::AddArray(const float &[])
#include <Arrays\ArrayFloat.mqh>
//---
float src[];
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const CArrayFloat* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayFloat-source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayFloat::AddArray(const CArrayFloat*)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayFloat *src=new CArrayFloat;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Insert

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Insert

Insert

Inserts an element in the array to the specified position.

bool Insert(
float element, // Element to insert
int pos // Position
)

Parameters

element

[in] Value of the element to be inserted into an array

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayFloat::Insert(float,int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / InsertArray

InsertArray

Inserts an array of elements from another array with the specified position.

bool InsertArray(
const float& src[], // Source array
int pos // Position
)

Parameters

src[]

[in] Reference to an array of source elements to insert

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayFloat::InsertArray(const float &[],int)
#include <Arrays\ArrayFloat.mqh>
//---
float src[];
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / InsertArray

InsertArray

Inserts an array of elements from another array specified position.

bool InsertArray(
CArrayFloat* src, // Pointer to the source
int pos // Position
)

Parameters

src

[in] Pointer to an instance of class CArrayFloat-source elements to insert.

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayFloat::InsertArray(const CArrayFloat*,int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayFloat *src=new CArrayFloat;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const float& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayFloat::AssignArray(const float &[])
#include <Arrays\ArrayFloat.mqh>
//---
float src[];
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const CArrayFloat* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayFloat-source element to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayFloat::AssignArray(const CArrayFloat*)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayFloat *src =new CArrayFloat;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Update

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Update

Update

Changes the element at the specified position array.

bool Update(
int pos, // Position
float element // Value
)

Parameters

pos

[in] Position of the element in the array to change

element

[in] New value element

Returned Value

true if successful, false - if you can not change the element.

Example:

//--- example for CArrayFloat::Update(int,float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,100.0))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}


Shift

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Shift

Shift

Moves an item from a given position in the array to the specified offset.

bool Shift(
int pos, // Position
int shift // Shift
)

Parameters

pos

[in] Position of the moved element array

shift

[in] The value of displacement (both positive and negative).

Returned Value

true if successful, false - if you can not move the item.

Example:

//--- example for CArrayFloat::Shift(int,int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}


Delete

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Delete

Delete

Removes the element from the given position in the array.

bool Delete(
int pos // Position
)

Parameters

pos

[in] Position removes the element in the array.

Returned Value

true if successful, false - if you can not remove the element.

Example:

//--- example for CArrayFloat::Delete(int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


DeleteRange

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / DeleteRange

DeleteRange

Deletes a group of elements from a given position in the array.

bool DeleteRange(
int from, // Position of the first element
int to // Position of last element
)

Parameters

from

[in] Position of the first removes the element in the array.

to

[in] Position of the last deleted element in the array.

Returned Value

true if successful, false - if you can not remove elements.

Example:

//--- example for CArrayFloat::DeleteRange(int,int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


At

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / At

At

Gets the element from the given position in the array.

float At(
int pos // Position
)

Parameters

pos

[in] Position of the desired element in the array.

Returned Value

The value of the element in case of success, FLT_MAX if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE).

Note

Of course, FLT_MAX may be a valid value of an array element, so having a value, always check the last error code.

Example:

//--- example for CArrayFloat::At(int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
float result=array.At(i);
if(result==FLT_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- Error reading from the array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const float& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayFloat::CompareArray(const float &[])
#include <Arrays\ArrayFloat.mqh>
//---
float src[];
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / CompareArray

AssignArrayconst

Copies the array elements from another array.

bool AssignArrayconst(
const CArrayFloat* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayFloat-source element to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayFloat::CompareArray(const CArrayFloat*)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayFloat *src=new CArrayFloat;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}


InsertSort

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / InsertSort

InsertSort

Inserts element in a sorted array.

bool InsertSort(
float element // Element to insert
)

Parameters

element

[in] Value of the element to be inserted into a sorted array

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayFloat::InsertSort(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(100.0))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}


Search

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Search

Search

Searches for an element equal to the sample in the sorted array.

int Search(
float element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayFloat::Search(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreat

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / SearchGreat

SearchGreat

Searches for an element of more samples in sorted array.

int SearchGreat(
float element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayFloat::SearchGreat(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLess

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / SearchLess

SearchLess

Searches for an element less than the sample in the sorted array.

int SearchLess(
float element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayFloat:: SearchLess(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreatOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / SearchGreatOrEqual

SearchGreatOrEqual

Searches for an element greater than or equal to the sample in the sorted array.

int SearchGreatOrEqual(
float element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayFloat::SearchGreatOrEqual(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLessOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / SearchLessOrEqual

SearchLessOrEqual

Searches for an element less than or equal to the sample in the sorted array.

int SearchLessOrEqual(
float element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayFloat::SearchLessOrEqual(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchFirst

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / SearchFirst

SearchFirst

Finds the first element equal to the sample in the sorted array.

int SearchFirst(
float element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayFloat::SearchFirst(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLast

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / SearchLast

SearchLast

Finds the last element equal to the model in sorted array.

int SearchLast(
float element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayFloat::SearchLast(float)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


Save

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Save

Save

Saves data array in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayFloat::Save(int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
int file_handle;
CArrayFloat *array=new CArrayFloat;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- add 100 arrays elements
for(int i=0;i<100;i++)
{
array.Add(i);
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
delete array;
}


Load

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Load

Load

Loads data array from a file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayFloat::Load(int)
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
int file_handle;
CArrayFloat *array=new CArrayFloat;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use arrays elements
for(int i=0;i<array.Total();i++)
{
printf("Element[%d]=%f",i,array.At(i));
}
delete array;
}


Type

MQL5 Reference / Standard Library / Data Structures / CArrayFloat / Type

Type

Gets the type identifier of the array.

virtual int Type()

Returned Value

ID type of the array (for CArrayFloat - 87).

Example:

//--- example for CArrayFloat::Type()
#include <Arrays\ArrayFloat.mqh>
//---
void OnStart()
{
CArrayFloat *array=new CArrayFloat;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}


CArrayDouble

MQL5 Reference / Standard Library / Data Structures / CArrayDouble

CArrayDouble

CArrayDouble class is a class of dynamic array of variables of type double.

Description

Class CArrayDouble provides the ability to work with a dynamic array of variables of type double.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.

Declaration

class CArrayDouble : public CArray

Title

#include <Arrays\ArrayDouble.mqh>

Class Methods

Function method | Action
Delta | Set the comparison tolerance
Reserve | Allocates memory to increase the size of the array
Resize | Sets a new (smaller) size of the array
Shutdown | Clears the array with a full memory release
Add | Adds an element to the end of the array
AddArray | Adds to the end of the array elements from another array
AddArray | Adds to the end of the array elements from another array
Insert | Inserts an element in the array to the specified position
InsertArray | Inserts an array of elements from another array with the specified position
InsertArray | Inserts an array of elements from another array with the specified position
AssignArray | Copies the array elements from another array
AssignArray | Copies the array elements from another array
Update | Changes the element at the specified position array
Shift | Moves an item from a given position in the array to the specified offset
Delete | Removes the element from the specified position array
DeleteRange | Deletes a group of elements from the specified position array
At | Gets the element from the specified position array
CompareArray | Compares array with another array
CompareArray | Compares array with another array
InsertSort | Inserts element in a sorted array
Search | Searches for an element equal to the model in sorted array
SearchGreat | Searches for an element of more samples in sorted array
SearchLess | Searches for an element less than the sample in the sorted array
SearchGreatOrEqual | Searches for an element greater than or equal to the model in sorted array
SearchLessOrEqual | Searches for an element less than or equal to the model in sorted array
SearchFirst | Finds the first element equal to the model in sorted array
SearchLast | Finds the last element equal to the model in sorted array
Save | Saves data array in the file
Load | Loads data array from a file
Type | Gets the type identifier of the array


Delta

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Delta

Delta

Set tolerance comparison.

void Delta(
double delta // Tolerance
)

Parameters

delta

[in] The new value of the admission of comparison.

Returned Value

No

Note

Admission of comparison used in the search. Values are considered equal if their difference is less than or equal to tolerance. The default tolerance is 0.0.

Example:

//--- example for CArrayDouble::Delta(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- set compare variation
array.Delta(0.001);
//--- use array
//--- . . .
//--- delete array
delete array;
}


Reserve

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Reserve

Reserve

Allocates memory to increase the size of the array.

bool Reserve(
int size // Number
)

Parameters

size

[in] The number of additional elements of the array.

Returned Value

true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase.

Note

To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayDouble::Reserve(int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


Resize

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Resize

Resize

Sets a new (smaller) size of the array.

bool Resize(
int size // Size
)

Parameters

size

[in] New size of the array.

Returned Value

true if successful, false - if there was an attempt to set the size of less than or equal to zero.

Note

Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayDouble::Resize(int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}


Shutdown

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Shutdown

Shutdown

Clears the array with a full memory release.

bool Shutdown()

Returned Value

true if successful, false - if an error occurred.

Example:

//--- example for CArrayDouble::Shutdown()
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}


Add

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Add

Add

Adds an element to the end of the array.

bool Add(
double element // Element to add
)

Parameters

element

[in] value of the element to add to the array.

Returned Value

true if successful, false - if you can not add an element.

Example:

//--- example for CArrayDouble::Add(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(i))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const double& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayDouble::AddArray(const double &[])
#include <Arrays\ArrayDouble.mqh>
//---
double src[];
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const CArrayDouble* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayDouble-source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayDouble::AddArray(const CArrayDouble*)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayDouble *src=new CArrayDouble;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Insert

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Insert

Insert

Inserts an element in the array to the specified position.

bool Insert(
double element, // Element to insert
int pos // Position
)

Parameters

element

[in] Value of the element to be inserted into an array

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayDouble::Insert(double,int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(i,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / InsertArray

InsertArray

Inserts an array of elements from another array specified position.

bool InsertArray(
const double& src[], // Source array
int pos // Position
)

Parameters

src[]

[in] Reference to an array of source elements to insert

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayDouble::InsertArray(const double &[],int)
#include <Arrays\ArrayDouble.mqh>
//---
double src[];
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / InsertArray

InsertArray

Inserts an array of elements from another array specified position.

bool InsertArray(
CArrayDouble* src, // Pointer to the source
int pos // Position
)

Parameters

src

[in] Pointer to an instance of class CArrayDouble-source elements to insert.

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayDouble::InsertArray(const CArrayDouble*,int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayDouble *src=new CArrayDouble;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const double& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayDouble::AssignArray(const double &[])
#include <Arrays\ArrayDouble.mqh>
//---
double src[];
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const CArrayDouble* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayDouble-source element to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayDouble::AssignArray(const CArrayDouble*)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayDouble *src =new CArrayDouble;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Update

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Update

Update

Changes the element at the specified position array.

bool Update(
int pos, // Position
double element // Value
)

Parameters

pos

[in] Position of the element in the array to change

element

[in] New value element

Returned Value

true if successful, false - if you can not change the element.

Example:

//--- example for CArrayDouble::Update(int,double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,100.0))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}


Shift

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Shift

Shift

Moves an item from a given position in the array to the specified offset.

bool Shift(
int pos, // Position
int shift // Shift
)

Parameters

pos

[in] Position of the moved element array

shift

[in] The value of displacement (both positive and negative).

Returned Value

true if successful, false - if you can not move the item.

Example:

//--- example for CArrayDouble::Shift(int,int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}


Delete

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Delete

Delete

Removes the element from the given position in the array.

bool Delete(
int pos // Position
)

Parameters

pos

[in] position removes the element in the array.

Returned Value

true if successful, false - if you can not remove the element.

Example:

//--- example for CArrayDouble::Delete(int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


DeleteRange

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / DeleteRange

DeleteRange

Deletes a group of elements from a given position in the array.

bool DeleteRange(
int from, // Position of the first element
int to // Position of last element
)

Parameters

from

[in] Position of the first removes the element in the array.

to

[in] Position of the last deleted element in the array.

Returned Value

true if successful, false - if you can not remove elements.

Example:

//--- example for CArrayDouble::DeleteRange(int,int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


At

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / At

At

Gets the element from the given position in the array.

double At(
int pos // Position
)

Parameters

pos

[in] Position of the desired element in the array.

Returned Value

The value of the element in case of success, DBL_MAX if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE).

Note

Of course, DBL_MAX may be a valid value of an array element, so having a value, always check the last error code.

Example:

//--- example for CArrayDouble::At(int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
double result=array.At(i);
if(result==DBL_MAX && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- Error reading from the array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const double& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayDouble::CompareArray(const double &[])
#include <Arrays\ArrayDouble.mqh>
//---
double src[];
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const CArrayDouble* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayDouble-source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayDouble::CompareArray(const CArrayDouble*)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayDouble *src=new CArrayDouble;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}


InsertSort

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / InsertSort

InsertSort

Inserts element in a sorted array.

bool InsertSort(
double element // Element to insert
)

Parameters

element

[in] value of the element to be inserted into a sorted array

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayDouble::InsertSort(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(100.0))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}


Search

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Search

Search

Searches for an element equal to the sample in the sorted array.

int Search(
double element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayDouble::Search(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreat

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / SearchGreat

SearchGreat

Searches for an element of more samples in sorted array.

int SearchGreat(
double element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayDouble::SearchGreat(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLess

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / SearchLess

SearchLess

Searches for an element less than the sample in the sorted array.

int SearchLess(
double element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayDouble:: SearchLess(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreatOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / SearchGreatOrEqual

SearchGreatOrEqual

Searches for an element greater than or equal to the sample in the sorted array.

int SearchGreatOrEqual(
double element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayDouble::SearchGreatOrEqual(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLessOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / SearchLessOrEqual

SearchLessOrEqual

Searches for an element less than or equal to the sample in the sorted array.

int SearchLessOrEqual(
double element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayDouble::SearchLessOrEqual(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchFirst

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / SearchFirst

SearchFirst

Finds the first element equal to the sample in the sorted array.

int SearchFirst(
double element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayDouble::SearchFirst(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLast

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / SearchLast

SearchLast

Finds the last element equal to the model in sorted array.

int SearchLast(
double element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayDouble::SearchLast(double)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast(100.0)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


Save

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Save

Save

Saves data array in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayDouble::Save(int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
int file_handle;
CArrayDouble *array=new CArrayDouble;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- add 100 arrays elements
for(int i=0;i<100;i++)
{
array.Add(i);
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- delete array
delete array;
}


Load

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Load

Load

Loads data array from a file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayDouble::Load(int)
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
int file_handle;
CArrayDouble *array=new CArrayDouble;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use arrays elements
for(int i=0;i<array.Total();i++)
{
printf("Element[%d]=%f",i,array.At(i));
}
//--- delete array
delete array;
}


Type

MQL5 Reference / Standard Library / Data Structures / CArrayDouble / Type

Type

Gets the type identifier of the array.

virtual int Type()

Returned Value

ID type of the array (for CArrayDouble - 87).

Example:

//--- example for CArrayDouble::Type()
#include <Arrays\ArrayDouble.mqh>
//---
void OnStart()
{
CArrayDouble *array=new CArrayDouble;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}


CArrayString

MQL5 Reference / Standard Library / Data Structures / CArrayString

CArrayString

CArrayString class is a class of dynamic array of variables of type string.

Description

Class CArrayString provides the ability to work with a dynamic array of variables of type string.In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array.In addition, the implemented methods of work with the file.

Declaration

class CArrayString : public CArray

Title

#include <Arrays\ArrayString.mqh>

Class Methods

Function-Method | Action
Reserve | Allocates memory to increase the size of the array
Resize | Sets a new (smaller) size of the array
Shutdown | Sets a new (smaller) size of the array
Add | Adds an element to the end of the array
AddArray | Adds to the end of the array elements from another array
AddArray | Adds to the end of the array elements from another array
Insert | Inserts an element in the array to the specified position
InsertArray | Inserts an array of elements from another array with the specified position
InsertArray | Inserts an array of elements from another array with the specified position
AssignArray | Copies the array elements from another array
AssignArray | Copies the array elements from another array
Update | Changes the element at the specified position array
Shift | Moves an item from a given position in the array to the specified offset
Delete | Removes the element from the specified position array
DeleteRange | Deletes a group of elements from the specified position array
At | Gets the element from the specified position array
CompareArray | Compares array with another array
CompareArray | Compares array with another array
InsertSort | Inserts element in a sorted array
Search | Searches for an element equal to the model in sorted array
SearchGreat | Searches for an element of more samples in sorted array
SearchLess | Searches for an element less than the sample in the sorted array
SearchGreatOrEqual | Searches for an element greater than or equal to the model in sorted array
SearchLessOrEqual | Searches for an element less than or equal to the model in sorted array
SearchFirst | Finds the first element equal to the model in sorted array
SearchLast | Finds the last element equal to the model in sorted array
Save | Saves data array in the file
Load | Loads data array from a file
Type | Gets the type identifier of the array


Reserve

MQL5 Reference / Standard Library / Data Structures / CArrayString / Reserve

Reserve

Allocates memory to increase the size of the array.

bool Reserve(
int size // Number
)

Parameters

size

[in] The number of additional elements of the array.

Returned Value

true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase.

Note

To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayString::Reserve(int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- reserve memory
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


Resize

MQL5 Reference / Standard Library / Data Structures / CArrayString / Resize

Resize

Sets a new (smaller) size of the array.

bool Resize(
int size // Size
)

Parameters

size

[in] New size of the array.

Returned Value

true if successful, false - if there was an attempt to set the size of less than or equal to zero.

Note

Changing the size of the array allows optimal use of memory.Superfluous elements on the right lost.To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayString::Resize(int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}


Shutdown

MQL5 Reference / Standard Library / Data Structures / CArrayString / Shutdown

Shutdown

Clears the array with a full memory release.

bool Shutdown()

Returned Value

true if successful, false - if an error occurred.

Example:

//--- example for CArrayString::Shutdown()
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}


Add

MQL5 Reference / Standard Library / Data Structures / CArrayString / Add

Add

Adds an element to the end of the array.

bool Add(
string element // Element to add
)

Parameters

element

[in] value of the element to add to the array.

Returned Value

true if successful, false - if you can not add an element.

Example:

//--- example for CArrayString::Add(string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(IntegerToString(i)))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayString / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const string& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayString::AddArray(const string &[])
#include <Arrays\ArrayString.mqh>
//---
string src[];
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayString / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const CArrayString* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayString - the source of elements to add.

Returned Value

true if successful, false - if you can not add items.

Example:

//--- example for CArrayString::AddArray(const CArrayString*)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayString *src=new CArrayString;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Insert

MQL5 Reference / Standard Library / Data Structures / CArrayString / Insert

Insert

Inserts an element in the array to the specified position.

bool Insert(
string element, // Element to insert
int pos // Position
)

Parameters

element

[in] Value of the element to be inserted into an array

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayString::Insert(string,int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(IntegerToString(i),0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayString / InsertArray

InsertArray

Inserts an array of elements from another array specified position.

bool InsertArray(
const string& src[], // Source array
int pos // Position
)

Parameters

src[]

[in] Reference to an array of source elements to insert

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayString::InsertArray(const string &[],int)
#include <Arrays\ArrayString.mqh>
//---
string src[];
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayString / InsertArray

InsertArray

Inserts an array of elements from another array specified position.

bool InsertArray(
CArrayString* src, // Pointer to the source
int pos // Position
)

Parameters

src

[in] Pointer to an instance of class CArrayString - the source of elements to insert.

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Example:

//--- example for CArrayString::InsertArray(const CArrayString*,int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayString *src=new CArrayString;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
return;
}
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayString / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const string& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayString::AssignArray(const string &[])
#include <Arrays\ArrayString.mqh>
//---
string src[];
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayString / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const CArrayString* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayString - source of elements to copy.

Returned Value

true if successful, false - if you can not copy the items.

Example:

//--- example for CArrayString::AssignArray(const CArrayString*)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayString *src =new CArrayString;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Update

MQL5 Reference / Standard Library / Data Structures / CArrayString / Update

Update

Changes the element at the specified position array.

bool Update(
int pos, // Position
string element // Value
)

Parameters

pos

[in] Position of the element in the array to change

element

[in] New value element

Returned Value

true if successful, false - if you can not change the element.

Example:

//--- example for CArrayString::Update(int, string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,"ABC"))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}


Shift

MQL5 Reference / Standard Library / Data Structures / CArrayString / Shift

Shift

Moves an item from a given position in the array to the specified offset.

bool Shift(
int pos, // Position
int shift // Shift
)

Parameters

pos

[in] Position of the moved element array

shift

[in] The value of displacement (both positive and negative).

Returned Value

true if successful, false - if you can not move the item.

Example:

//--- example for CArrayString::Shift(int,int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}


Delete

MQL5 Reference / Standard Library / Data Structures / CArrayString / Delete

Delete

Removes the element from the given position in the array.

bool Delete(
int pos // Position
)

Parameters

pos

[in] position removes the element in the array.

Returned Value

true if successful, false - if you can not remove the element.

Example:

//--- example for CArrayString::Delete(int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete element
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


DeleteRange

MQL5 Reference / Standard Library / Data Structures / CArrayString / DeleteRange

DeleteRange

Deletes a group of elements from a given position in the array.

bool DeleteRange(
int from, // Position of the first element
int to // Position of last element
)

Parameters

from

[in] Position of the first removes the element in the array.

to

[in] Position of the last deleted element in the array.

Returned Value

true if successful, false - if you can not remove elements.

Example:

//--- example for CArrayString::DeleteRange(int,int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


At

MQL5 Reference / Standard Library / Data Structures / CArrayString / At

At

Gets the element from the given position in the array.

string At(
int pos // Position
)

Parameters

pos

[in] Position of the desired element in the array.

Returned Value

The value of the element in case of success, "- if there was an attempt to get an element of not existing positions (the last error ERR_OUT_OF_RANGE).

Note

Of course, "" may be a valid value of an array element, so having a value, always check the last error code.

Example:

//--- example for CArrayString::At(int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
string result=array.At(i);
if(result=="" && GetLastError()==ERR_OUT_OF_RANGE)
{
//--- Error reading from the array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayString / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const string& src[] // Source array
)

Parameters

src[]

[in] Reference to an array of source elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayString::CompareArray(const string &[])
#include <Arrays\ArrayString.mqh>
//---
string src[];
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- compare with another array
int result=array.CompareArray(src);
//--- delete array
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayString / CompareArray

CompareArray

Compares array with another array.

bool CompareArrays(
const CArrayString* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayString - the source of elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayString::CompareArray(const CArrayString*)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayString *src=new CArrayString;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- add source arrays elements
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}


InsertSort

MQL5 Reference / Standard Library / Data Structures / CArrayString / InsertSort

InsertSort

Inserts element in a sorted array.

bool InsertSort(
string element // Element to insert
)

Parameters

element

[in] value of the element to be inserted into a sorted array

Returned Value

true if successful, false - if you can not insert the element.

Example:

//--- example for CArrayString::InsertSort(string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort("ABC"))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}


Search

MQL5 Reference / Standard Library / Data Structures / CArrayString / Search

Search

Searches for an element equal to the sample in the sorted array.

int Search(
string element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayString::Search(string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.Search("ABC")!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreat

MQL5 Reference / Standard Library / Data Structures / CArrayString / SearchGreat

SearchGreat

Searches for an element of more samples in sorted array.

int SearchGreat(
string element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayString::SearchGreat(string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreat("ABC")!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLess

MQL5 Reference / Standard Library / Data Structures / CArrayString / SearchLess

SearchLess

Searches for an element less than the sample in the sorted array.

int SearchLess(
string element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayString:: SearchLess(string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLess("ABC")!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreatOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayString / SearchGreatOrEqual

SearchGreatOrEqual

Searches for an element greater than or equal to the sample in the sorted array.

int SearchGreatOrEqual(
string element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayString:: SearchGreatOrEqual(string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchGreatOrEqual("ABC")!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLessOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayString / SearchLessOrEqual

SearchLessOrEqual

Searches for an element less than or equal to the sample in the sorted array.

int SearchLessOrEqual(
string element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayString:: SearchLessOrEqual(string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLessOrEqual("ABC")!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchFirst

MQL5 Reference / Standard Library / Data Structures / CArrayString / SearchFirst

SearchFirst

Finds the first element equal to the sample in the sorted array.

int SearchFirst(
string element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayString:: SearchFirst(string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchFirst("ABC")!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLast

MQL5 Reference / Standard Library / Data Structures / CArrayString / SearchLast

SearchLast

Finds the last element equal to the model in sorted array.

int SearchLast(
string element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayString:: SearchLast(string)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- search element
if(array.SearchLast("ABC")!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


Save

MQL5 Reference / Standard Library / Data Structures / CArrayString / Save

Save

Saves data array in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayString::Save(int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
int file_handle;
CArrayString *array=new CArrayString;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- add 100 arrays elements
for(int i=0;i<100;i++)
{
array.Add(IntegerToString(i));
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
delete array;
}


Load

MQL5 Reference / Standard Library / Data Structures / CArrayString / Load

Load

Loads data array from a file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayString::Load(int)
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
int file_handle;
CArrayString *array=new CArrayString;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use arrays elements
for(int i=0;i<array.Total();i++)
{
printf("Element [% d] = '% s'",i,array.At(i));
}
delete array;
}


Type

MQL5 Reference / Standard Library / Data Structures / CArrayString / Type

Type

Gets the type identifier of the array.

virtual int Type()

Returned Value

ID type of the array (for CArrayString - 89).

Example:

//--- example for CArrayString::Type()
#include <Arrays\ArrayString.mqh>
//---
void OnStart()
{
CArrayString *array=new CArrayString;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}


CArrayObj

MQL5 Reference / Standard Library / Data Structures / CArrayObj

2CArrayObj

CArrayObj class is a class of dynamic array of pointers to instances of CObject and his heirs.

Description

Class CArrayObj provides the ability to work with a dynamic array of pointers to instances of CObject and his heirs. This gives the possibility to work as a multidimensional dynamic arrays of primitive data types, and the more difficult for organized data structures.

In the class implemented the ability to add / insert / delete elements in an array, sort array, searching in sorted array. In addition, the implemented methods of work with the file.

There are certain subtleties of the class CArrayObj.

Declaration

class CArrayObj : public CArray

Title

#include <Arrays\ArrayObj.mqh>

Class Method

Function-Method | Action
FreeMode | Gets the flag memory management
FreeMode | Sets the flag memory management
Reserve | Allocates memory to increase the size of the array
Resize | Sets a new (smaller) size of the array
Shutdown | Clears the array with a total exemption memory array (not element).
Add | Adds an element to the end of the array
AddArray | Adds an element to the end of the array
Insert | Inserts an element in the array to the specified position
InsertArray | Inserts an array of elements from another array with the specified position
AssignArray | Copies the array elements from another array
Update | Changes the element at the specified position array
Shift | Moves an item from a given position in the array to the specified offset
Detach | Gets the element from the specified position and removing it from the array
Delete | Removes the element from the specified position array
DeleteRange | Deletes a group of elements from the specified position array
Clear | Removes all elements of the array without the release of the memory array
At | Gets the element from the specified position array
CompareArray | Compares array with another array
InsertSort | Inserts element in a sorted array
Search | Searches for an element equal to the model in sorted array
SearchGreat | Searches for an element of more samples in sorted array
SearchLess | Searches for an element less than the sample in the sorted array
SearchGreatOrEqual | Searches for an element greater than or equal to the model in sorted array
SearchLessOrEqual | Searches for an element less than or equal to the model in sorted array
SearchFirst | Finds the first element equal to the model in sorted array
SearchLast | Finds the last element equal to the model in sorted array
Save | Saves data array in the file
Load | Loads data array from a file
Type | Gets the type identifier of the array

Practical application of arrays are descendants of class CObject (including all classes of the standard library).

For example, consider the options for two-dimensional array:

#include <Arrays\ArrayDouble.mqh>
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
int i,j;
int first_size=10;
int second_size=100;
//--- create array
CArrayObj *array=new CArrayObj;
CArrayDouble *sub_array;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create subarrays
for(i=0;i<first_size;i++)
{
sub_array=new CArrayDouble;
if(sub_array==NULL)
{
delete array;
printf("Object create error");
return;
}
//--- fill array
for(j=0;j<second_size;j++)
{
sub_array.Add(i*j);
}
array.Add(sub_array);
}
//--- create array OK
for(i=0;i<first_size;i++)
{
sub_array=array.At(i);
for(j=0;j<second_size;j++)
{
double element=sub_array.At(j);
//--- use array element
}
}
delete array;
}
Subtleties

The class has a mechanism to control dynamic memory, so be careful when working with elements of the array.

Mechanism of memory management can be switched on / off using the method FreeMode (bool). By default, the mechanism is enabled.

Accordingly, there are two options for dealing with the class CArrayObj:

1. Mechanism of memory management is enabled. (default)

In this case, CArrayObj take responsibility for freeing the memory elements after their removal from the array. In this program the user should not free the array elements.

Example:

int i;
//--- Create an array
CArrayObj *array=new CArrayObj;
//--- Fill array elements
for(i=0;i<10;i++) array.Add(new CObject);
//--- Do something
for(i=0;i<array.Total();i++)
{
CObject *object=array.At(i);
//--- Action with an element
. . .
}
//--- Remove the array with the elements
delete array;
2. Mechanism of memory management is turned off.

In this case, CArrayObj not otvetstvechaet for freeing the memory elements after their removal from the array. In this program the user must free the array elements.

Example:

int i;
//--- Create an array
CArrayObj *array=new CArrayObj;
//--- Disable the mechanism of memory management
array.FreeMode(false);
//--- Fill array elements
for(i=0;i<10;i++) array.Add(new CObject);
//--- Do something
for(i=0;i<array.Total();i++)
{
CObject *object=array.At(i);
//--- Action with an element
. . .
}
//--- Remove array elements
while(array.Total()) delete array.Detach();
//--- Remove empty array
delete array;


FreeMode

MQL5 Reference / Standard Library / Data Structures / CArrayObj / FreeMode

FreeMode

Gets the flag memory management.

bool FreeMode()

Returned Value

Flag of memory management.

Example:

//--- example for CArrayObj::FreeMode()
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get free mode flag
bool array_free_mode=array.FreeMode();
//--- delete array
delete array;
}


FreeMode

MQL5 Reference / Standard Library / Data Structures / CArrayObj / FreeMode

FreeMode

Sets the flag memory management.

void FreeMode(
bool mode // New flag
)

Parameters

mode

[in] New value of the flag memory management.

Returned Value

No.

Note

Setting the flag memory management - an important point in the use of class CArrayObj.Since the array elements are pointers to dynamic objects, it is important to determine what to do with them when removing from the array.

If the flag is set, removing an element from the array, the element is automatically deleted by the operator delete.If the flag is not set, it is assumed that a pointer to the deleted object is still somewhere in the user program and will be relieved of it (the program) then.

If the user resets the flag memory management, the user must understand their responsibility for the removal of the array before the completion of the program, because otherwise, is not freed memory occupied by the elements when they create new operator.

When large amounts of data, it could lead, eventually, even to break your terminal.If the user does not reset the flag memory management, there is another "reef".

Using pointers, array, stored somewhere in the local variables, after removing the array will lead to a critical error and crashes the program user.By default, the memory management flag is set, ie the class of the array is responsible for freeing the memory elements.

Example:

//--- example for CArrayObj::FreeMode(bool)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- reset free mode flag
array.FreeMode(false);
//--- use array
//--- . . .
//--- delete array
delete array;
}


Reserve

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Reserve

Reserve

Allocates memory to increase the size of the array.

bool Reserve(
int size // Number
)

Parameters

size

[in] The number of additional elements of the array.

Returned Value

true if successful, false - if there was an attempt to seek the amount is less than or equal to zero, or if the array did not increase.

Note

To reduce memory fragmentation, increase the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayObj::Reserve(int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
if(!array.Reserve(1024))
{
printf("Reserve error");
delete array;
return;
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


Resize

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Resize

Resize

Sets a new (smaller) size of the array.

bool Resize(
int size // Size
)

Parameters

size

[in] New size of the array.

Returned Value

To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Note

Changing the size of array allows to use memory in the optimal way. Excess element located to the right are lost. The memory for lost elements is released or not depending on the mode of memory management.

To reduce fragmentation of memory, change the size of the array is made with a step previously given through the method of Step (int), or 16 (default).

Example:

//--- example for CArrayObj::Resize(int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- resize array
if(!array.Resize(10))
{
printf("Resize error");
delete array;
return;
}
//--- delete array
delete array;
}


Clear

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Clear

Clear

Removes all elements of the array without the release of the memory array.

void Clear()

Returned Value

No.

Note

If enabled memory management, memory, deleted items are exempt.

Example:

//--- example for CArrayObj::Clear()
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- clear array
array.Clear();
//--- delete array
delete array;
}


Shutdown

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Shutdown

Shutdown

Clears the array with a total exemption memory array (not element).

bool Shutdown()

Returned Value

true if successful, false - if an error occurred.

Note

If enabled memory management, memory, deleted items are exempt.

Example:

//--- example for CArrayObj::Shutdown()
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shutdown array
if(!array.Shutdown())
{
printf("Shutdown error");
delete array;
return;
}
//--- delete array
delete array;
}


CreateElement

MQL5 Reference / Standard Library / Data Structures / CArrayObj / CreateElement

CreateElement

Creates a new array element at the specified position.

bool CreateElement(
int index // Position
)

Parameters

index

[in] position in which you want to create a new element.

Returned Value

true if successful, false - if you can not create element.

Note

Method CreateElement (int) in class CArrayObj always returns false and does not perform any action. If necessary, in a derived class, method CreateElement (int) should be implemented.

Example:

//--- example for CArrayObj::CreateElement(int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
int size=100;
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- fill array
array.Reserve(size);
for(int i=0;i<size;i++)
{
if(!array.CreateElement(i))
{
printf("Element create error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


Add

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Add

Add

Adds an element to the end of the array.

bool Add(
CObject* element // Element to add
)

Parameters

element

[in] value of the element to add to the array.

Returned Value

true if successful, false - if you can not add an element.

Note

Element is not added to the array if the value for transmit invalid pointer (such as NULL).

Example:

//--- example for CArrayObj::Add(CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add 100 arrays elements
for(int i=0;i<100;i++)
{
if(!array.Add(new CObject))
{
printf("Element addition error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


AddArray

MQL5 Reference / Standard Library / Data Structures / CArrayObj / AddArray

AddArray

Adds to the end of the array elements from another array.

bool AddArray(
const CArrayObj * src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayDouble - source of elements to add.

Returned Value

true if successful, false - if you can not add items.

Note

Adding elements of the array in the array is actually copying the pointers.Therefore, when calling the method, there is a "reef" - that there may be a pointer to a dynamic object in more than one variable.

//--- example
extern bool make_error;
extern int error;
extern CArrayObj *src;
//--- Create a new instance CArrayObj
//--- Default memory management is turned on
CArrayObj *array=new CArrayObj;
//--- Add (copy) the elements of the array-istochika
if(array!=NULL)
bool result=array.AddArray(src);
if(make_error)
{
//--- Commit wrongdoing
switch(error)
{
case 0:
//--- Remove the array-source, without checking its flag memory management
delete src;
//--- Result:
//--- May appeal
//--- For "bitomu" pointer in the array receiver
break;
case 1:
//--- Disable the mechanism of memory management in an array of source
if(src.FreeMode()) src.FreeMode(false);
//--- But do not remove the array-source
//--- Result:
//--- After removal of the array, the receiver may appeal
//--- For "bitomu" pointer in the array-source
break;
case 2:
//--- Disable the mechanism of memory management in an array of source
src.FreeMode(false);
//--- Disable the mechanism of memory management in an array receiver
array.FreeMode(false);
//--- Result:
//--- After the completion of the program, obtain a "memory leak"
break;
}
}
else
{
//--- Disable the mechanism of memory management in an array of source
if(src.FreeMode()) src.FreeMode(false);
//--- Remove the array-source
delete src;
//--- Result:
//--- Treatment for an array-recepient be correct
//--- Delete the array, the receiver will delete its elements
}

Example:

//--- example for CArrayObj::AddArray(const CArrayObj*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayObj *src=new CArrayObj;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- reset free mode flag
src.FreeMode(false);
//--- fill source array
//--- . . .
//--- add another array
if(!array.AddArray(src))
{
printf("Array addition error");
delete src;
delete array;
return;
}
//--- delete source array without elements
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Insert

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Insert

Insert

Inserts an element in the array to the specified position.

bool Insert(
CObject* element, // Element to insert
int pos // Position
)

Parameters

element

[in] value of the element to be inserted into an array

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not insert the element.

Note

Element is not added to the array if the value for transmit invalid pointer (such as NULL).

Example:

//--- example for CArrayObj::Insert(CObject*,int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- insert elements
for(int i=0;i<100;i++)
{
if(!array.Insert(new CObject,0))
{
printf("Insert error");
delete array;
return;
}
}
//--- use array
//--- . . .
//--- delete array
delete array;
}


InsertArray

MQL5 Reference / Standard Library / Data Structures / CArrayObj / InsertArray

InsertArray

Inserts an array of elements from another array specified position.

bool InsertArray(
const CArrayObj* src, // Pointer to the source
int pos // Position
)

Parameters

src

[in] Pointer to an instance of class CArrayObj-source elements to insert.

pos

[in] Position in the array to insert

Returned Value

true if successful, false - if you can not paste items.

Note

See: CArrayObj::AddArray(const CArrayObj*).

Example:

//--- example for CArrayObj::InsertArray(const CArrayObj*,int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayObj *src=new CArrayObj;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- reset free mode flag
src.FreeMode(false);
//--- fill source array
//--- . . .
//--- insert another array
if(!array.InsertArray(src,0))
{
printf("Array inserting error");
delete src;
delete array;
return;
}
//--- delete source array without elements
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


AssignArray

MQL5 Reference / Standard Library / Data Structures / CArrayObj / AssignArray

AssignArray

Copies the array elements from another array.

bool AssignArray(
const CArrayObj* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayObj - source of elements to copy.

Returned Value

true if successful, false - if you can not copy the items.

Note

If the challenge AssignArray array receiver is not empty, all its elements will be removed from the array and, if the flag memory management, memory, deleted items will be released.Array-receiver is an exact copy of the array source. Additionally see CArrayObj::AddArray(const CArrayObj*).

Example:

//--- example for CArrayObj::AssignArray(const CArrayObj*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayObj *src=new CArrayObj;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- reset free mode flag
src.FreeMode(false);
//--- fill source array
//--- . . .
//--- assign another array
if(!array.AssignArray(src))
{
printf("Array assigned error");
delete src;
delete array;
return;
}
//--- arrays is identical
//--- delete source array without elements
delete src;
//--- use array
//--- . . .
//--- delete array
delete array;
}


Update

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Update

Update

Changes the element at the specified position array.

bool Update(
int pos, // Position
CObject* element // Value
)

Parameters

pos

[in] Position of the element in the array to change

element

[in] New value element

Returned Value

true if successful, false - if you can not change the element.

Note

The element does not change if we as a parameter to pass an invalid pointer (ie NULL). If enabled memory management, memory placeholder released.

Example:

//--- example for CArrayObj::Update(int,CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- update element
if(!array.Update(0,new CObject))
{
printf("Update error");
delete array;
return;
}
//--- delete array
delete array;
}


Shift

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Shift

Shift

Moves an item from a given position in the array to the specified offset.

bool Shift(
int pos, // Position
int shift // Shift
)

Parameters

pos

[in] Position of the moved element array

shift

[in] The value of displacement (both positive and negative).

Returned Value

true if successful, false - if you can not move the item.

Example:

//--- example for CArrayObj::Shift(int,int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- shift element
if(!array.Shift(10,-5))
{
printf("Shift error");
delete array;
return;
}
//--- delete array
delete array;
}


Detach

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Detach

Detach

Remove an item from a given position in the array.

CObject* Detach(
int pos // Position
)

Parameters

pos

[in] Position of the seized item in the array.

Returned Value

Pointer to the removal of elements in case of success, NULL - if you can not remove the element.

Note

When removed from the array element is not removed in any state of the flag memory management. Pointer to the array element withdrawn from the ingredients of the release after use.

Example:

//--- example for CArrayObj::Detach(int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
CObject *object=array.Detach(0);
if(object==NULL)
{
printf("Detach error");
delete array;
return;
}
//--- use element
//--- . . .
//--- delete element
delete object;
//--- delete array
delete array;
}


Delete

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Delete

Delete

Removes the element from the given position in the array.

bool Delete(
int pos // Position
)

Parameters

pos

[in] position removes the element in the array.

Returned Value

true if successful, false - if you can not remove the element.

Note

If enabled memory management, memory, deleted items are exempt.

Example:

//--- example for CArrayObj::Delete(int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
if(!array.Delete(0))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


DeleteRange

MQL5 Reference / Standard Library / Data Structures / CArrayObj / DeleteRange

DeleteRange

Deletes a group of elements from a given position in the array.

bool DeleteRange(
int from, // Position of the first element
int to // Position of last element
)

Parameters

from

[in] Position of the first removes the element in the array.

to

[in] Position of the last deleted element in the array.

Returned Value

true if successful, false - if you can not remove elements.

Note

If enabled memory management, memory, deleted items are exempt.

Example:

//--- example for CArrayObj::DeleteRange(int,int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- delete elements
if(!array.DeleteRange(0,10))
{
printf("Delete error");
delete array;
return;
}
//--- delete array
delete array;
}


At

MQL5 Reference / Standard Library / Data Structures / CArrayObj / At

At

Gets the element from the given position in the array.

CObject* At(
int pos // Position
)

Parameters

pos

[in] Position of the desired element in the array.

Returned Value

The value of the element, if successful, NULL-if there was an attempt to get an element of non-existent position.

Example:

//--- example for CArrayObj::At(int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add elements
//--- . . .
for(int i=0;i<array.Total();i++)
{
CObject *result=array.At(i);
if(result==NULL)
{
//--- Error reading from the array
printf("Get element error");
delete array;
return;
}
//--- use element
//--- . . .
}
delete array;
}


CompareArray

MQL5 Reference / Standard Library / Data Structures / CArrayObj / CompareArray

CompareArray

Compares array with another array.

bool CompareArray(
const CArrayObj* src // Pointer to the source
)

Parameters

src

[in] Pointer to an instance of class CArrayObj - the source of elements for comparison.

Returned Value

true if arrays are equal, false - if not.

Example:

//--- example for CArrayObj::CompareArray(const CArrayObj*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- create source array
CArrayObj *src=new CArrayObj;
if(src==NULL)
{
printf("Object create error");
delete array;
return;
}
//--- fill source array
//--- . . .
//--- compare with another array
int result=array.CompareArray(src);
//--- delete arrays
delete src;
delete array;
}


InsertSort

MQL5 Reference / Standard Library / Data Structures / CArrayObj / InsertSort

InsertSort

Inserts element in a sorted array.

bool InsertSort(
CObject* element // Element to insert
)

Parameters

element

[in] Value of the element to be inserted into a sorted array

Returned Value

true if successful, false - if you can not insert the element.

Note

Element is not added to the array if the value for transmit invalid pointer (such as NULL).

Example:

//--- example for CArrayObj::InsertSort(CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- insert element
if(!array.InsertSort(new CObject))
{
printf("Insert error");
delete array;
return;
}
//--- delete array
delete array;
}


Search

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Search

Search

Searches for an element equal to the sample in the sorted array.

int Search(
CObject* element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayObj::Search(CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.Search(sample)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreat

MQL5 Reference / Standard Library / Data Structures / CArrayObj / SearchGreat

SearchGreat

Searches for an element of more samples in sorted array.

int SearchGreat(
CObject* element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayObj::SearchGreat(CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchGreat(sample)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLess

MQL5 Reference / Standard Library / Data Structures / CArrayObj / SearchLess

SearchLess

Searches for an element less than the sample in the sorted array.

int SearchLess(
CObject* element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayObj:: SearchLess(CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchLess(sample)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchGreatOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayObj / SearchGreatOrEqual

SearchGreatOrEqual

Searches for an element greater than or equal to the sample in the sorted array.

int SearchGreatOrEqual(
CObject* element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayObj::SearchGreatOrEqual(CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchGreatOrEqual(sample)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLessOrEqual

MQL5 Reference / Standard Library / Data Structures / CArrayObj / SearchLessOrEqual

SearchLessOrEqual

Searches for an element less than or equal to the sample in the sorted array.

int SearchLessOrEqual(
CObject* element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayObj:: SearchLessOrEqual(CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchLessOrEqual(sample)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchFirst

MQL5 Reference / Standard Library / Data Structures / CArrayObj / SearchFirst

SearchFirst

Finds the first element equal to the sample in the sorted array.

int SearchFirst(
CObject* element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayObj::SearchFirst(CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchFirst(sample)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


SearchLast

MQL5 Reference / Standard Library / Data Structures / CArrayObj / SearchLast

SearchLast

Finds the last element equal to the model in sorted array.

int SearchLast(
CObject* element // Sample
)

Parameters

element

[in] The sample element to search in the array.

Returned Value

The position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CArrayObj:: SearchLast(CObject*)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- sort array
array.Sort();
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete array;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(array.SearchLast(sample)!=-1) printf("Element found");
else printf("Element not found");
//--- delete array
delete array;
}


Save

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Save

Save

Saves data array in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to previously opened by FileOpen (...) function binary file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CArrayObj::Save(int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
int file_handle;
CArrayObj *array=new CArrayObj;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- add arrays elements
//--- . . .
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
delete array;
}


Load

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Load

Load

Loads data array from a file.s

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle to open earlier, with the function FileOpen (...), binary file.

Returned Value

true - if successfully completed, false - if an error.

Note

When reading from the file array to create each element of the method is called CArrayObj::CreateElement(int).

Example:

//--- example for CArrayObj::Load(int)
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
int file_handle;
CArrayObj *array=new CArrayObj;
//---
if(array!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!array.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete array;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use arrays elements
//--- . . .
//--- delete array
delete array;
}


Type

MQL5 Reference / Standard Library / Data Structures / CArrayObj / Type

Type

Gets the type identifier of the array.

virtual int Type()

Returned Value

ID type of the array (for CArrayObj - 7778).

Example:

//--- example for CArrayObj::Type()
#include <Arrays\ArrayObj.mqh>
//---
void OnStart()
{
CArrayObj *array=new CArrayObj;
//---
if(array==NULL)
{
printf("Object create error");
return;
}
//--- get array type
int type=array.Type();
//--- delete array
delete array;
}


CList

MQL5 Reference / Standard Library / Data Structures / CList

CList

CList Class is a class of dynamic list of instances of the class CObject and his heirs.

Description

Class CList provides the ability to work with a list of instances of CObject and his heirs. In the class implemented the ability to add / insert / delete items in the list, sort the list, search in sorted list. In addition, the implemented methods of work with the file.

There are some subtleties of working with the class CList. The class has a mechanism to control dynamic memory, so be careful when working with elements of the list.

Subtleties of the mechanism of memory management similar to those described in CArrayObj.

Declaration

class CList : public CObject

Title

#include <Arrays\List.mqh>

Class Methods

Function-Method | Action
FreeMode | Gets the flag memory management when deleting list items.
FreeMode | Sets the flag memory management when deleting items in the list
Total | Gets the number of elements in the list
IsSorted | Gets flag sorted list
SortMode | Gets the version of the sorting
CreateElement | Creates a new item to the list
Add | Adds element to the end of the list
Insert | Inserts element in the list in the specified position
DetachCurrent | Remove an item from the current position of the list without deleting it "physically"
DeleteCurrent | Removes the element from the current position in the list
DeleteAtIndex | Removes the element from the specified position in the list
Clear | Removes all list items
IndexOf | Gets the index of the list item
GetFirstNode | Gets the first element of the list
GetPrevNode | Gets the previous element list
GetCurrentNode | Gets the current list item
GetNextNode | Gets the next item in the list
GetLastNode | Gets the last item
Sort | Sort list
MoveToIndex | Moves the current item list to the specified position
Exchange | Changes elements of the list seats
CompareList | Compares the list with another list
Search | Searches for an element equal to the model in sorted list
Save | Saves data in the file list
Load | Loads data from file list
Type | Gets the type identifier list


FreeMode

MQL5 Reference / Standard Library / Data Structures / CList / FreeMode

FreeMode

Gets the flag memory management when deleting list items.

bool FreeMode()

Returned Value

Flag of memory management.

Example:

//--- example for CList::FreeMode()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- get free mode flag
bool list_free_mode=list.FreeMode();
//--- delete list
delete list;
}


FreeMode

MQL5 Reference / Standard Library / Data Structures / CList / FreeMode

FreeMode

Sets the flag memory management when deleting list items.

void FreeMode(
bool mode // New value
)

Parameters

mode

[in] New value of the flag memory management.

Note

Setting the flag memory management - an important point in the use of class CList.Since the elements of the list are pointers to dynamic objects, it is important to determine what to do with them when you delete from the list.If the flag is set, then when you delete an item from the list, the item is automatically deleted by the operator delete.If the flag is not set, it is assumed that a pointer to the deleted object is still somewhere in the user program and will be relieved of it (the program) then.

If the user resets the flag memory management, the user must understand their responsibility for the removal of items in the list before completing the program, because otherwise, is not freed memory occupied by the elements when they create new operator.When large amounts of data, it could lead, eventually, even to break your terminal.

If the user does not reset the flag memory management, there is another "reef".Using pointers-list items that are stored somewhere in the local variables, after removing the list, will lead to a critical error and crashes the program user.By default, the memory management flag is set, ie the class list, is responsible for freeing the memory elements.

Example:

//--- example for CList::FreeMode(bool)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- reset free mode flag
list.FreeMode(false);
//--- use list
//--- . . .
//--- delete list
delete list;
}


Total

MQL5 Reference / Standard Library / Data Structures / CList / Total

Total

Gets the number of elements in the list.

int Total()

Returned Value

Number of elements in the list.

Example:

//--- example for CList::Total()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- check total
int total=list.Total();
//--- use list
//--- ...
//--- delete list
delete list;
}


IsSorted

MQL5 Reference / Standard Library / Data Structures / CList / IsSorted

IsSorted

Gets the flag sorted list.

bool IsSorted(
int mode=0 // Sorting mode
)

Parameters

mode=0

[in] Tested version sorting

Returned Value

Flag of the sorted list. If the list is sorted by the specified option? true, otherwise? false.

Note

Flag of the sorted list can not be changed directly. Flag set by Sort (int) and resets any methods to add / insert.

Example:

//--- example for CList::IsSorted()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- check sorted
if(list.IsSorted(0))
{
//--- use methods for sorted list
//--- ...
}
//--- delete list
delete list;
}


SortMode

MQL5 Reference / Standard Library / Data Structures / CList / SortMode

SortMode

Gets the version of the sort.

int SortMode()

Returned Value

Option sorting, or -1 if the list is not sorted.

Example:

//--- example for CList::SortMode()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- check sort mode
int sort_mode=list.SortMode();
//--- use list
//--- ...
//--- delete list
delete list;
}


CreateElement

MQL5 Reference / Standard Library / Data Structures / CList / CreateElement

CreateElement

Creates a new item to the list.

bool CreateElement()

Returned Value

Pointer to the newly created element, if successful, NULL - if you can not create element.

Note

Method CreateElement () in class CList always returns NULL and does not perform any actions. If necessary, in a derived class, method CreateElement () should be implemented.

Example:

//--- example for CList::CreateElement(int)
#include <Arrays\List.mqh>
//---
void OnStart()
{
int size=100;
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- fill list
for(int i=0;i<size;i++)
{
CObject *object=list.CreateElement();
if(object==NULL)
{
printf("Element create error");
delete list;
return;
}
list.Add(object);
}
//--- use list
//--- . . .
//--- delete list
delete list;
}


Add

MQL5 Reference / Standard Library / Data Structures / CList / Add

Add

Adds an element to the end of the list.

bool Add(
CObject* element // Element to add
)

Parameters

element

[in] Value of the element to add to the list.

Returned Value

true if successful, false - if you can not add an element.

Note

Element is not added to the list, if the parameter does not pass valid pointer (ie NULL).

Example:

//--- example for CList::Add(Cobject*)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add 100 elements
for(int i=0;i<100;i++)
{
if(!list.Add(new CObject))
{
printf("Element addition error");
delete list;
return;
}
}
//--- use list
//--- . . .
//--- delete list
delete list;
}


Insert

MQL5 Reference / Standard Library / Data Structures / CList / Insert

Insert

Inserts element in the list in the specified position.

bool Insert(
CObject* element, // Element to insert
int pos // Position
)

Parameters

element

[in] value of the element to insert in the list

pos

[in] Position in the list to insert

Returned Value

true if successful, false - if you can not insert the element.

Note

Element is not added to the list, if the parameter does not pass valid pointer (ie NULL).

Example:

//--- example for CList::Insert(CObject*,int)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- insert 100 elements
for(int i=0;i<100;i++)
{
if(!list.Insert(new CObject,0))
{
printf("Element insert error");
delete list;
return;
}
}
//--- use list
//--- . . .
//--- delete list
delete list;
}


DetachCurrent

MQL5 Reference / Standard Library / Data Structures / CList / DetachCurrent

DetachCurrent

Extracts an element from the current position without its "physical" deleteion.

CObject* DetachCurrent()

Returned Value

Pointer to the removal of elements in case of success, NULL - if you can not remove the element.

Note

When removed from the list, the item is not removed in any state of the flag memory management. Pointer to withdraw from the list of ingredients of the release element after use.

Example:

//--- example for CList::DetachCurrent()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.DetachCurrent();
if(object==NULL)
{
printf("Detach error");
delete list;
return;
}
//--- use element
//--- . . .
//--- delete element
delete object;
//--- delete list
delete list;
}


DeleteCurrent

MQL5 Reference / Standard Library / Data Structures / CList / DeleteCurrent

DeleteCurrent

Removes the element from the current position in the list.

bool DeleteCurrent()

Returned Value

true if successful, false - if you can not remove the element.

Note

If enabled memory management, memory, removes the element is released.

Example:

//--- example for CList::DeleteCurrent()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
if(!list.DeleteCurrent())
{
printf("Delete error");
delete list;
return;
}
//--- delete list
delete list;
}


DeleteAtIndex

MQL5 Reference / Standard Library / Data Structures / CList / DeleteAtIndex

DeleteAtIndex

Removes the element from the given position in the list.

bool DeleteAtIndex(
int pos // Position
)

Parameters

pos

[in] position removes the element in the list.

Returned Value

true if successful, false - if you can not remove the element.

Note

If enabled memory management, memory, removes the element is released.

Example:

//--- example for CList::Delete(int)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
if(!list.Delete(0))
{
printf("Delete error");
delete list;
return;
}
//--- delete list
delete list;
}


Clear

MQL5 Reference / Standard Library / Data Structures / CList / Clear

Clear

Removes all elements of the list.

void Clear()

Note

If enabled memory management, memory, deleted items are exempt.

Example:

//--- example for CList::Clear()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
//--- clear list
list.Clear();
//--- delete list
delete list;
}


IndexOf

MQL5 Reference / Standard Library / Data Structures / CList / IndexOf

IndexOf

Gets the index of the list item.

int IndexOf(
CObject* element // Pointer to the element
)

Parameters

element

[in] Pointer to the list item.

Returned Value

Index item in the list, or -1.

Example:

//--- example for CList::IndexOf(CObject*)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
CObject *object=new CObject;
if(object==NULL)
{
printf("Element create error");
delete list;
return;
}
if(list.Add(object))
{
int pos=list.IndexOf(object);
}
//--- delete list
delete list;
}


GetFirstNode

MQL5 Reference / Standard Library / Data Structures / CList / GetFirstNode

GetFirstNode

Gets the first element of the list.

CObject* GetFirstNode()

Returned Value

Pointer to the first item in case of success, NULL - if you can not get a pointer.

Example:

//--- example for CList::GetFirstNode()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetFirstNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}


GetPrevNode

MQL5 Reference / Standard Library / Data Structures / CList / GetPrevNode

GetPrevNode

Gets the previous element of the list.

CObject* GetPrevNode()

Returned Value

Pointer to the previous element, if successful, NULL - if you can not get a pointer.

Example:

//--- example for CList::GetPrevNode()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetPrevNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}


GetCurrentNode

MQL5 Reference / Standard Library / Data Structures / CList / GetCurrentNode

GetCurrentNode

Gets the current list item.

CObject* GetCurrentNode()

Returned Value

Pointer to the current item, if successful, NULL - if you can not get a pointer.

Example:

//--- example for CList::GetCurrentNode()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetCurrentNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}


GetNextNode

MQL5 Reference / Standard Library / Data Structures / CList / GetNextNode

GetNextNode

Gets the next item in the list.

CObject* GetNextNode()

Returned Value

Pointer to the next item if successful, NULL - if you can not get a pointer.

Example:

//--- example for CList::GetNextNode()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetNextNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}


GetLastNode

MQL5 Reference / Standard Library / Data Structures / CList / GetLastNode

GetLastNode

Gets the last element of the list.

CObject* GetLastNode()

Returned Value

Pointer to the last element in the case of success, NULL - if you can not get a pointer.

Example:

//--- example for CList::GetLastNode()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add list elements
//--- . . .
CObject *object=list.GetLastNode();
if(object==NULL)
{
printf("Get node error");
delete list;
return;
}
//--- use element
//--- . . .
//--- do not delete element
//--- delete list
delete list;
}


Sort

MQL5 Reference / Standard Library / Data Structures / CList / Sort

Sort

Sorts a list.

void Sort(
int mode // Sorting mode
)

Parameters

mode

[in] Sorting mode.

Returned Value

No.

Note

Sorting the list is always in ascending order.

Example:

//--- example for CList::Sort(int)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- sorting by mode 0
list.Sort(0);
//--- use list
//--- ...
//--- delete list
delete list;
}


MoveToIndex

MQL5 Reference / Standard Library / Data Structures / CList / MoveToIndex

MoveToIndex

Moves the current item list to the specified position.

bool MoveToIndex(
int pos // Position
)

Parameters

pos

[in] Position in the list to move.

Returned Value

true if successful, false - if you can not move the item.

Example:

//--- example for CList::MoveToIndex(int)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- move current node to begin
list.MoveToIndex(0);
//--- use list
//--- . . .
//--- delete list
delete list;
}


Exchange

MQL5 Reference / Standard Library / Data Structures / CList / Exchange

Exchange

Changes elements of the list seats.

bool Exchange(
CObject* node1, // List item
CObject* node2 // List item
)

Parameters

node1

[in] List item

node2

[in] List item

Returned Value

true if successful, false - if you can not change the elements in some places.

Example:

//--- example for CList::Exchange(CObject*,CObject*)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- exchange
list.Exchange(list.GetFirstNode(),list.GetLastNode());
//--- use list
//--- . . .
//--- delete list
delete list;
}


CompareList

MQL5 Reference / Standard Library / Data Structures / CList / CompareList

CompareList

Compares the list with another list.

bool CompareList(
CList* list // With whom we compare
)

Parameters

list

[in] A pointer to an instance of class CList-source elements for comparison.

Returned Value

true if the lists are equal, false - if not.

Example:

//--- example for CList::CompareList(const CList*)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- create source list
CList *src=new CList;
if(src==NULL)
{
printf("Object create error");
delete list;
return;
}
//--- fill source list
//--- . . .
//--- compare with another list
bool result=list.CompareList(src);
//--- delete lists
delete src;
delete list;
}


Search

MQL5 Reference / Standard Library / Data Structures / CList / Search

Search

Searches for an element equal to the model in the sorted list.

CObject* Search(
CObject* element // Sample
)

Parameters

element

[in] Sample cell to search for in the list.

Returned Value

Pointer to the found item if successful, NULL - if the item was not found.

Example:

//--- example for CList::Search(CObject*)
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- add lists elements
//--- . . .
//--- sort list
list.Sort(0);
//--- create sample
CObject *sample=new CObject;
if(sample==NULL)
{
printf("Sample create error");
delete list;
return;
}
//--- set sample attributes
//--- . . .
//--- search element
if(list.Search(sample)!=NULL) printf("Element found");
else printf("Element not found");
//--- delete list
delete list;
}


Save

MQL5 Reference / Standard Library / Data Structures / CList / Save

Save

Saves data in the file list.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] handle of the previously opened using the function FileOpen (...) file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CList::Save(int)
#include <Arrays\List.mqh>
//---
void OnStart()
{
int file_handle;
CList *list=new CList;
//---
if(list!=NULL)
{
printf("Object create error");
return;
}
//--- add lists elements
//--- . . .
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!list.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete list;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- delete list
delete list;
}


Load

MQL5 Reference / Standard Library / Data Structures / CList / Load

Load

Loads list data from a file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] Handle of the previously open, with the function FileOpen (...), binary

Returned Value

true - if successfully completed, false - if an error.

Note

When reading from the file list items to create each element of the method is called CList:: CreateElement ().

Example:

//--- example for CLoad::Load(int)
#include <Arrays\List.mqh>
//---
void OnStart()
{
int file_handle;
CList *list=new CList;
//---
if(list!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!list.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete list;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use list elements
//--- . . .
//--- delete list
delete list;
}


Type

MQL5 Reference / Standard Library / Data Structures / CList / Type

Type

Gets the type identifier list.

virtual int Type()

Returned Value

Type identifier list (for CList - 7779).

Example:

//--- example for CList::Type()
#include <Arrays\List.mqh>
//---
void OnStart()
{
CList *list=new CList;
//---
if(list==NULL)
{
printf("Object create error");
return;
}
//--- get list type
int type=list.Type();
//--- delete list
delete list;
}


Graphic Objects

MQL5 Reference / Standard Library / Graphic Objects

Graphic Objects

This section contains the technical details of working with classes of graphical objects and a description of the relevant components of the standard library MQL5.

The use of classes of graphical objects, will save time when creating custom programs (scripts, expert).

Standard library MQL5 (in terms of graphical objects) is placed in the working directory of the terminal in the folder Include \ ChartObjects.

Class Name | Class Purpose
CChartObject | Base class of a graphic object


CChartObject

MQL5 Reference / Standard Library / Graphic Objects / CChartObject

CChartObject

Class CChartObject is the base class for classes of graphical objects chart the standard library MQL5.

Description

Class CChartObject provides all its descendants for simplified access the API MQL5.

Declaration

class CChartObject : public CObject

Title

#include <ChartObjects\ChartObject.mqh>

Class Methods

Function-Method | Action
ChartId | Gets the ID chart, who owns a graphic
Window | Gets the number of windows in which the chart is a graphic
Name | Gets/sets the name of a graphic object
NumPoints | Gets the number of anchor points
Attach | Binds a graphic chart
SetPoint | Sets the anchor point
Delete | Deletes a graphic chart
Detach | Untie a graphic chart
ShiftObject | The relative movement of the object
ShiftPoint | The relative movement of the object point
Time | Gets/sets the time coordinates of the object point
Price | Gets/sets the price coordinate of a point object
Color | Gets/sets the color of the object
Style | Gets/sets the line style object
Width | Gets/sets the width of the line object
BackGround | Gets/sets the flag drawing object background
Selected | Gets/sets the flag sit on an object
Selectable | Gets/sets the flag selectable object
Description | Gets/sets the text of the object
Timeframes | Gets/sets the mask of flags visibility of the object
CreateTime | Gets the time object creation
LevelsCount | Gets/sets the number of levels of object
LevelColor | Gets/sets the color of the line level
LevelStyle | Gets/sets the line style level
LevelWidth | Gets/sets the width of the line level
LevelValue | Gets/sets the level
LevelDescription | Gets/sets the text level
GetInteger | Gets the value of the object properties
SetInteger | Sets the object properties
GetDouble | Gets the value of the object properties
SetDouble | Sets the object properties
GetString | Gets the value of the object properties
SetString | Sets the object properties
Save | Virtual method entry in the file
Load | Virtual method of reading from a file
Type | Virtual method of identification


ChartId

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / ChartId

ChartId

Gets the ID chart, who owns a graphic object.

long ChartId()

Returned Value

Id chart on which the graphic object. If not bound object, it returns -1.

Example:

//--- example for CChartObject::ChartId
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get chart idintifier of chart object
long chatr_id=object.ChartId();
//--- delete object
delete object;
}


Window

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Window

Window

Gets the number of windows in which the chart is a graphic object.

int Window()

Returned Value

Number of windows in which the chart is a graphic object (0 - main window). If not bound object, it returns -1.

Example:

//--- example for CChartObject::Window
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get window of chart object
int window=object.Window();
//--- delete object
delete object;
}


Name

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Name

Name (get method)

Gets the name of the graphic object.

string Name()

Returned Value

Name of the graphic object tied to an instance of the class. If no bound object returns NULL.

Name (set method)

Sets the name of the graphic object.

bool Name(
string name // new name
)

Parameters

name

[in] The new name of the graphic object.

Returned Value

true if successful, false - if you can not change the name.

Example:

//--- example for CChartObject::Name
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get name of chart object
string object_name=object.Name();
if(object_name!="MyChartObject")
{
//--- set name of chart object
object.Name("MyChartObject");
}
//--- delete object
delete object;
}


NumPoints

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / NumPoints

NumPoints

Gets the number of anchor points of a graphic object.

int NumPoints()

Returned Value

Number of points linking a graphic object that is bound to an instance of the class. If not bound object, it returns 0.

Example:

//--- example for CChartObject::NumPoints
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get points count of chart object
int points=object.NumPoints();
//--- delete object
delete object;
}


Attach

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Attach

Attach

Binds a graphical object to an instance of the class.

bool Attach(
long chart_id, // Chart ID
string name, // Name of the object
int window, // Chart window
int points // Number of points
)

Parameters

chart_id

[out] Chart identifier.

name

[in] Name of the graphic object.

window

[in] Chart window number (0 - main window).

points

[in] Number of points anchor graphic object.

Returned Value

true - if successful, false - if you can not bind object.

Example:

//--- example for CChartObject::Attach
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- attach chart object
if(!object.Attach(ChartID(),"MyObject",0,2))
{
printf("Object attach error");
delete object;
return;
}
//--- delete object
delete object;
}


SetPoint

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / SetPoint

SetPoint

Sets the new coordinates of this anchor point graphic object.

bool SetPoint(
int point, // Point number
datetime new_time, // Time coordinate
double new_price // Price coordinate
)

Parameters

point

[in] Number anchor point graphic object.

new_time

[in] The new value of the coordinates of this point of time bindings.

new_price

[in] New value coordinates of the price specified anchor point.

Returned Value

true - if successful, false - if you can not change the coordinates of the point.

Example:

//--- example for CChartObject::SetPoint
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
double price;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
if(object.NumPoints()>0)
{
//--- set point of chart object
object.SetPoint(0,CurrTime(),price);
}
//--- delete object
delete object;
}


Delete

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Delete

Delete

Removes a graphical object with the attached chart.

bool Delete()

Returned Value

true - if successful, false - if you can not remove the object.

Example:

//--- example for CChartObject::Delete
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- detach chart object
if(!object.Delete())
{
printf("Object delete error");
delete object;
return;
}
//--- delete object
delete object;
}


Detach

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Detach

Detach

Untie graphic object.

bool Detach()

Returned Value

true - if successful, false - if you can not decouple the object.

Example:

//--- example for CChartObject::Detach
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- detach chart object
if(!object.Detach())
{
printf("Object detach error");
delete object;
return;
}
//--- delete object
delete object;
}


ShiftObject

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / ShiftObject

ShiftObject

Moves a graphic object.

bool ShiftObject(
datetime d_time, // Increment of time coordinate
double d_price // Increment of price coordinate
)

Parameters

d_time

[in] Increment the coordinates of all points of time bindings

d_price

[in] Increment the coordinates of the prices of all waypoints.

Returned Value

true - if successful, false - if you can not move the object.

Example:

//--- example for CChartObject::ShiftObject
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
datetime d_time;
double d_price;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- shift chart object
object.ShiftObject(d_time,d_price);
//--- delete object
delete object;
}


ShiftPoint

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / ShiftPoint

ShiftPoint

Moves a specified point anchor graphic.

bool ShiftPoint(
int point, // Point number
datetime d_time, // Increment of time coordinate
double d_price // Increment of price coordinate
)

Parameters

point

[in] Number anchor point graphic object.

d_time

[in] Increment the coordinates of time specified anchor point.

d_price

[in] Increment the coordinates of the price specified anchor point.

Returned Value

true - if successful, false - if you can not move the point.

Example:

//--- example for CChartObject::ShiftPoint
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
datetime d_time;
double d_price;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
if(object.NumPoints()>0)
{
//--- shift point of chart object
object.ShiftPoint(0,d_time,d_price);
}
//--- delete object
delete object;
}


Time

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Time

Time (get method)

The coordinates of time specified anchor point graphic object.

datetime Time(
int point // Point number
)

Parameters

point

[in] Number anchor point graphic object.

Returned Value

Coordinates of time specified anchor point graphic object that is bound to an instance of the class. If not bound object or the object is not this point, it returns 0.

Time (set method)

Sets the coordinate of time specified anchor point graphic object.

bool Time(
int point, // Point number
datetime new_time // Time
)

Parameters

point

[in] Number anchor point graphic object.

new_time

[in] The new value of the coordinates of this point of time anchor graphic object.

Returned Value

true - if successful, false - if you can not change the coordinate of time.

Example:

//--- example for CChartObject::Time
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
for(int i=0;i<object.NumPoints();i++)
{
//--- get time of point chart object
datetime point_time=object.Time(i);
if(point_time==0)
{
//--- set time of point chart object
object.Time(i,TimeCurrent());
}
}
//--- delete object
delete object;
}


Price

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Price

Price (get method)

Gets the coordinate of the price specified anchor point graphic object.

double Price(
int point // Point number
)

Parameters

point

[in] Number anchor point graphic object.

Returned Value

Coordinate prices specified anchor point graphic object that is bound to an instance of the class. If not bound object or the object is not this point, it returns 0.0.

Price (set method)

Sets the coordinate of the price specified anchor point graphic object.

bool Price(
int point, // Point number
double new_price // Price
)

Parameters

point

[in] Number anchor point graphic object.

new_price

[in] News value coordinates of the price specified anchor point graphic object.

Returned Value

true - if successful, false - if you can not change the coordinate prices.

Example:

//--- example for CChartObject::Price
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
double price;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
for(int i=0;i<object.NumPoints();i++)
{
//--- get price of point chart object
double point_price=object.Price(i);
if(point_price!=price)
{
//--- set price of point chart object
object.Price(i,price);
}
}
//--- delete object
delete object;
}


Color

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Color

Color (get method)

Gets the line color graphic object.

color Color()

Returned Value

Color line drawing object that is bound to an instance of the class. If no bound object returns 0.

Color (set method)

Sets the color of the line graphic object.

bool Color(
color new_color // New color
)

Parameters

new_color

[in] New value line color graphic object.

Returned Value

true - if successful, false - if you can not change the color.

Example:

//--- example for CChartObject::Color
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get color of chart object
color object_color=object.Color();
if(object_color!=Red)
{
//--- set color of chart object
object.Color(Red);
}
//--- delete object
delete object;
}


Style

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Style

Style (get method)

Gets the line style graphic.

ENUM_LINE_STYLE Style()

Returned Value

Style line graphic object that is bound to an instance of the class. If no bound object, returns STYLE_SOLID.

Style (set method)

Sets the line style graphic.

bool Style(
ENUM_LINE_STYLE new_style // Style
)

Parameters

new_style

[in] New value-style line drawing object.

Returned Value

true - if successful, false - if you can not change the style.

Example:

//--- example for CChartObject::Style
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get style of chart object
ENUM_LINE_STYLE style=object.Style();
if(style!=STYLE_SOLID)
{
//--- set style of chart object
object.Style(STYLE_SOLID);
}
//--- delete object
delete object;
}


Width

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Width

Width (get method)

Gets the thickness of the line graphic object.

int Width()

Returned Value

The thickness of the line graphic object that is bound to an instance of the class. If not bound object, it returns 0.

Width (set method)

Sets the thickness of the line graphic object.

bool Width(
int new_width // Thickness
)

Parameters

new_width

[in] The new value of the thickness of the line graphic object.

Returned Value

true - if successful, false - if you can not change the thickness.

Example:

//--- example for CChartObject::Width
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get width of chart object
int width=object.Width();
if(width!=1)
{
//--- set width of chart object
object.Width(1);
}
//--- delete object
delete object;
}


BackGround

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / BackGround

Background (get method)

Gets the flag drawing a graphic object in the background.

bool Background()

Returned Value

Flag of drawing in the background, a graphic object that is bound to an instance of the class. If not bound object returns false.

Background (set method)

Sets the flag drawing a graphic object in the background.

bool Background(
bool background // Value of the flag
)

Parameters

background

[in] New value of the flag drawing a graphic object in the background.

Returned Value

true - if successful, false - if you can not change the flag.

Example:

//--- example for CChartObject::Background
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get background flag of chart object
bool background_flag=object.Background();
if(!background_flag)
{
//--- set background flag of chart object
object.Background(true);
}
//--- delete object
delete object;
}


Selected

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Selected

Selected (get method)

Gets the flag "reprimand" graphic object.

bool Selected()

Returned Value

Flag "slate", a graphic object that is bound to an instance of the class. If not bound object returns false.

Selected (set method)

Sets the flag "reprimand" graphic object.

bool Selected(
bool selected // Value of the flag
)

Parameters

selected

[in] New value of the flag "reprimand" graphic object.

Returned Value

true - if successful, false - if you can not change the flag.

Example:

//--- example for CChartObject::Selected
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get selected flag of chart object
bool selected_flag=object.Selected();
if(selected_flag)
{
//--- set selected flag of chart object
object.Selected(false);
}
//--- delete object
delete object;
}


Selectable

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Selectable

Selectable (get method)

Gets the flag "selectable" graphic object.

bool Selectable()

Returned Value

Flag "selectable", a graphic object that is bound to an instance of the class. If not bound object returns false.

Selectable (set method)

Sets the flag "selectable" graphic object.

bool Selectable(
bool selectable // Value of the flag
)

Parameters

selectable

[in] New value of the flag "selectable" graphic object.

Returned Value

true - if successful, false - if you can not change the flag.

Example:

//--- example for CChartObject::Selectable
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get selectable flag of chart object
bool selectable_flag=object.Selectable();
if(selectable_flag)
{
//--- set selectable flag of chart object
object.Selectable(false);
}
//--- delete object
delete object;
}


Description

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Description

Description (get method)

Gets a description (text) graphic object.

string Description()

Returned Value

Description (text) graphic object that is bound to an instance of the class. If no bound object, it returns NULL.

Description (set method)

Sets the description (text) graphic object.

bool Description(
string text // Text
)

Parameters

text

[in] New value descriptions (text) graphic object.

Returned Value

true - if successful, false - if you can not change the description (text).

Example:

//--- example for CChartObject::Description
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get description of chart object
string description=object.Description();
if(description=="")
{
//--- set description of chart object
object.Description("MyObject");
}
//--- delete object
delete object;
}


Timeframes

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Timeframes

Timeframes (get method)

Gets the visibility flag graphic object.

int Timeframes()

Returned Value

Flags visibility graphic object that is bound to an instance of the class. If not bound object, it returns 0.

Timeframes (set method)

Sets the visibility flag graphic.

bool Timeframes(
int new_timeframes // Visibility flags
)

Parameters

new_timeframes

[in] New flags visibility graphic object.

Returned Value

true - if successful, false - if you can not change the flags of visibility.

Example:

//--- example for CChartObject::Timeframes
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get timeframes of chart object
int timeframes=object.Timeframes();
if(!(timeframes&OBJ_PERIOD_H1))
{
//--- set timeframes of chart object
object.Timeframes(timeframes|OBJ_PERIOD_H1);
}
//--- delete object
delete object;
}


CreateTime

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / CreateTime

CreateTime

Gets the time to create graphical object.

datetime CreateTime()

Returned Value

Time to create graphical object that is bound to an instance of the class. If not bound object, it returns 0.

Example:

//--- example for CChartObject::CreateTime
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get create time of chart object
datetime create_time=object.CreateTime();
//--- delete object
delete object;
}


LevelsCount

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / LevelsCount

LevelsCount (get method)

Gets the number of levels of graphical object.

int LevelsCount()

Returned Value

Number of levels of graphical object that is bound to an instance of the class. If not bound object, it returns 0.See also

LevelsCount (set method)

Sets the number of levels of graphical object.

bool LevelsCount(
int levels // Number of levels
)

Parameters

levels

[in] the number of new levels of graphic object.

Returned Value

true - if successful, false - if you can not change the number of levels.

Example:

//--- example for CChartObject::LevelsCount
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get levels count of chart object
int levels_count=object.LevelsCount();
//--- set levels count of chart object
object.LevelsCount(levels_count+1);
//--- delete object
delete object;
}


LevelColor

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / LevelColor

LevelColor (get method)

Gets the line color specified level of graphic object.

color LevelColor()

Returned Value

Color Line level specified graphic object that is bound to an instance of the class. If not bound object or the object is no specified level, it returns 0.

LevelColor (set method)

Sets the line color specified level of graphic object.

bool LevelColor(
color new_color // New color
)

Parameters

new_color

[in] New value line color of the level of graphic object.

Returned Value

true - if successful, false - if you can not change the color.

Example:

//--- example for CChartObject::LevelColor
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- get level color of chart object
color level_color=object.LevelColor(i);
if(level_color!=Red)
{
//--- set level color of chart object
object.LevelColor(i,Red);
}
}
//--- delete object
delete object;
}


LevelStyle

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / LevelStyle

LevelStyle (get method)

Gets the line style specified level of graphical object.

ENUM_LINE_STYLE LevelStyle(
int level // Level number
)

Parameters

level

[in] Number of levels of graphical object.

Returned Value

Line style specified level graphical object that is bound to an instance of the class. If not bound object or the object is no specified level of returns STYLE_SOLID.

LevelStyle (set method)

Sets the line style specified level of graphical object.

int LevelStyle(
int level, // Level number
ENUM_LINE_STYLE style // Line Style
)

Parameters

level

[in] Number of levels of graphical object.

style

[in] New value-style line level specified graphical object.

Returned Value

true - if successful, false - if you can not change the style.

Example:

//--- example for CChartObject::LevelStyle
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- get level style of chart object
ENUM_LINE_STYLE level_style=object.LevelStyle(i);
if(level_style!=STYLE_SOLID)
{
//--- set level style of chart object
object.LevelStyle(i,STYLE_SOLID);
}
}
//--- delete object
delete object;
}


LevelWidth

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / LevelWidth

LevelWidth (get method)

Gets the line thickness specified level of graphic object.

int LevelWidth(
int level // Level number
)

Parameters

level

[in] Number of levels of graphical object.

Returned Value

The thickness of the lines of the level of graphical object that is bound to an instance of the class. If not bound object or the object is no specified level, it returns 0.

LevelWidth (set method)

Finds the last element equal to the model in sorted array.

bool LevelWidth(
int level, // Level number
int new_width // New width
)

Parameters

level

[in] Number of levels of graphical object.

new_width

[in] New value line thickness specified level graphical object.

Returned Value

position of the found element, if successful, -1 - if the item was not found.

Example:

//--- example for CChartObject::LevelWidth
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- get level width of chart object
int level_width=object.LevelWidth(i);
if(level_width!=1)
{
//--- set level width of chart object
object.LevelWidth(i,1);
}
}
//--- delete object
delete object;
}


LevelValue

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / LevelValue

LevelValue (get method)

Gets the value of the level of graphic object.

double LevelValue(
int level // Level number
)

Parameters

level

[in] Number of levels of graphical object.

Returned Value

The value of this level of graphical object that is bound to an instance of the class. If not bound object or the object is no level specified, returns 0.0.

LevelValue (set method)

Sets the value of the specified level of graphic object.

bool LevelValue(
int level, // Level number
double new_value // New value
)

Parameters

level

[in] Number of levels of graphical object.

new_value

[in] New value of the level of graphic object.

Returned Value

true - if successful, false - if you can not change the level.

Example:

//--- example for CChartObject::LevelValue
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- get level value of chart object
double level_value=object.LevelValue(i);
if(level_value!=0.1*i)
{
//--- set level value of chart object
object.LevelValue(i,0.1*i);
}
}
//--- delete object
delete object;
}


LevelDescription

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / LevelDescription

LevelDescription (get method)

Gets a description (text) of the level of graphical object.

string LevelDescription(
int level // Level number
)

Parameters

level

[in] Number of levels of graphical object.

Returned Value

Description (text) of the level of graphical object that is bound to an instance of the class. If not bound object or the object is no specified level, returns NULL.

LevelDescription (set method)

Sets the description (text) of the level of graphical object.

bool LevelDescription(
int level , // Level number
string text // Text
)

Parameters

level

[in] Number of level of graphical object.

text

[in] New value of description (text) of the level of graphic object.

Returned Value

true - if successful, false - if you can not change the description (text).

Example:

//--- example for CChartObject::LevelDescription
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- get level description of chart object
string level_description=object.LevelDescription(i);
if(level_description=="")
{
//--- set level description of chart object
object.LevelDescription(i,"Level_"+IntegerToString(i));
}
}
//--- delete object
delete object;
}


GetInteger

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / GetInteger

GetInteger

Provides simplified access to the functions of API MQL5 ObjectGetInteger() for integer-value properties (of type bool, char, uchar, short, ushort, int, uint, ling, ulong, datetime, color) bound to an instance of the class graphic.There are two versions of a function call:

Getting a property value without checking the correctness

long GetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id, // Identifier of integer-property
int modifier=-1 // Modifier
)

Parameters

prop_id

[in] ID of double-graphic properties.

modifier=-1

[in] Modifier (index) double-features.

Returned Value

Value of integer-property.

Getting a property value in verifying the correctness of such treatment

bool GetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id, // Identifier of integer-property
int modifier, // Modifier
long& value // Link to variable
)

Parameters

prop_id

[in] ID integer-graphic properties of the object.

modifier

[in] Modifier (index) integer-property.

value

[out] Reference to a variable to accommodate the integer-value properties.

Returned Value

true - if successful, false - if you can not get integer-property.

Example:

//--- example for CChartObject::GetInteger
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get color of chart object by easy method
printf("Objects color is %s",ColorToString(object.GetInteger(OBJPROP_COLOR),true));
//--- get color of chart object by classic method
long color_value;
if(!object.GetInteger(OBJPROP_COLOR,0,color_value))
{
printf("Get integer property error %d",GetLastError());
delete object;
return;
}
else
printf("Objects color is %s",color_value);
for(int i=0;i<object.LevelsCount();i++)
{
//--- get levels width by easy method
printf("Level %d width is %d",i,object.GetInteger(OBJPROP_LEVELWIDTH,i));
//--- get levels width by classic method
long width_value;
if(!object.GetInteger(OBJPROP_LEVELWIDTH,i,width_value))
{
printf("Get integer property error %d",GetLastError());
delete object;
return;
}
else
printf("Level %d width is %d",i,width_value);
}
//--- delete object
delete object;
}


SetInteger

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / SetInteger

SetInteger

Provides simplified access to the functions of API MQL5 ObjectSetInteger() to change the integer-properties (with types bool, char, uchar, short, ushort, int, uint, ling, ulong, datetime, color) bound to an instance of the class graphic.There are two versions of a function call:

Setting a property value that does not require a modifier

bool SetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id, // Identifier of integer-property
long value // Value
)

Parameters

prop_id

[in] ID integer-graphic properties of the object.

value

[in] new mutable integer-value properties.

Setting a property value indicating the modifier

bool SetInteger(
ENUM_OBJECT_PROPERTY_INTEGER prop_id, // Identifier of integer-property
int modifier, // Modifier
long value // Value
)

Parameters

prop_id

[in] ID integer-graphic properties of the object.

modifier

[in] Modifier (index) integer-property.

value

[in] new mutable integer-value properties.

Returned Value

true - if successful, false - if you can not change the integer-property.

Example:

//--- example for CChartObject::SetInteger
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- set new color of chart object
if(!object.SetInteger(OBJPROP_COLOR,Red))
{
printf("Set integer property error %d",GetLastError());
delete object;
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- set levels width
if(!object.SetInteger(OBJPROP_LEVELWIDTH,i,i))
{
printf("Set integer property error %d",GetLastError());
delete object;
return;
}
}
//--- delete object
delete object;
}


GetDouble

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / GetDouble

GetDouble

Provides simplified access to the functions of API MQL5 ObjectGetDouble() to get the values double-properties (having type float and double) bound to an instance of the class graphic object. There are two versions of a function call:

Getting a property value without checking the correctness

double GetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id, // Identifier of double-property
int modifier=-1 // Modifier
)

Parameters

prop_id

[in] ID of double-graphic properties.

modifier=-1

[in] Modifier (index) double-features.

Returned Value

The value of double-features.

Getting a property value in verifying the correctness of such treatment

bool GetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id, // Identifier of double-property
int modifier, // Modifier
double& value // Link to variable
)

Parameters

prop_id

[in] ID of double-graphic properties.

modifier

[in] Modifier (index) double-features.

value

[out] Reference to a variable to accommodate the double-value properties.

Returned Value

true - if successful, false - if you can not get a double-feature.

Example:

//--- example for CChartObject::GetDouble
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- get levels value by easy method
printf("Level %d value=%f",i,object.GetDouble(OBJPROP_LEVELVALUE,i));
//--- get levels value by classic method
double value;
if(!object.SetDouble(OBJPROP_LEVELVALUE,i,value))
{
printf("Get double property error %d",GetLastError());
delete object;
return;
}
else
printf("Level %d value=%f",i,value);
}
//--- delete object
delete object;
}


SetDouble

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / SetDouble

SetDouble

Provides simplified access to the functions of API MQL5 ObjectSetDouble() to change the double-properties (having type float and double) bound to an instance of the class graphic object. There are two versions of a function call:

Setting a property value that does not require a modifier

bool SetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id, // Identifier of double-property
double value // Value
)

Parameters

prop_id

[in] ID of double-graphic properties.

value

[in] New value mutable double-features.

Setting a property value indicating the modifier

bool SetDouble(
ENUM_OBJECT_PROPERTY_DOUBLE prop_id, // Identifier of double-property
int modifier, // Modifier
double value // Value
)

Parameters

prop_id

[in] ID of double-graphic properties.

modifier

[in] Modifier (index) of double-property.

value

[in] New value mutable double-property.

Returned Value

true - if successful, false - if you can not change the double-feature.

Example:

//--- example for CChartObject::SetDouble
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- set level value of chart object
if(!object.SetDouble(OBJPROP_LEVELVALUE,i,0.1*i))
{
printf("Set double property error %d",GetLastError());
delete object;
return;
}
}
//--- delete object
delete object;
}


GetString

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / GetString

GetString

Provides simplified access to the functions of API MQL5 ObjectGetString() for string-value properties, is bound to an instance of the class graphic object. There are two versions of a function call:

Getting a property value without checking the correctness

string GetString(
ENUM_OBJECT_PROPERTY_STRING prop_id, // Identifier of string-property
int modifier=-1 // Modifier
)

Parameters

prop_id

[in] Identifier string-properties of graphic object.

modifier=-1

[in] Modifier (index) string-properties.

Returned Value

Value of string-property.

Getting a property value in verifying the correctness of such treatment

bool GetString(
ENUM_OBJECT_PROPERTY_STRING prop_id, // Identifier of string-property
int modifier, // Modifier
string& value // Link to variable
)

Parameters

prop_id

[in] Identifier string-properties of graphic object.

modifier

[in] Modifier (index) string-properties.

value

[out] Reference to a variable to accommodate the string-value properties.

Returned Value

true - if successful, false - if you can not get a string-property.

Example:

//--- example for CChartObject::GetString
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
string value;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get name of chart object by easy method
printf("Object name is '%s'",object.GetString(OBJPROP_NAME));
//--- get name of chart object by classic method
if(!object.GetString(OBJPROP_NAME,0,value))
{
printf("Get string property error %d",GetLastError());
delete object;
return;
}
else
printf("Object name is '%s'",value);
for(int i=0;i<object.LevelsCount();i++)
{
//--- get levels description by easy method
printf("Level %d description is '%s'",i,object.GetString(OBJPROP_LEVELTEXT,i));
//--- get levels description by classic method
if(!object.GetString(OBJPROP_LEVELTEXT,i,value))
{
printf("Get string property error %d",GetLastError());
delete object;
return;
}
else
printf("Level %d description is '%s'",i,value);
}
//--- delete object
delete object;
}


SetString

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / SetString

SetString

Provides simplified access to the functions of API MQL5 ObjectSetString() to change the properties of string-tied to the instance of the class graphic object. There are two versions of a function call:

Setting a property value that does not require a modifier

bool SetString(
ENUM_OBJECT_PROPERTY_STRING prop_id, // Identifier of string-property
string value // Value
)

Parameters

prop_id

[in] Identifier string-properties of graphic object.

value

[in] New value mutable string-properties.

Setting a property value indicating the modifier

bool SetString(
ENUM_OBJECT_PROPERTY_STRING prop_id, // Identifier of string-property
int modifier, // Modifier
string value // Value
)

Parameters

prop_id

[in] Identifier string-properties of graphic object.

modifier

[in] Modifier (index) string-properties.

value

[in] New value mutable string-properties.

Returned Value

true - if successful, false - if you can not change the string-property.

Example:

//--- example for CChartObject::SetString
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object;
//---
object=new CChartObject;
if(object==NULL)
{
printf("Object create error");
return;
}
//--- set new name of chart object
if(!object.SetString(OBJPROP_NAME,"MyObject"))
{
printf("Set string property error %d",GetLastError());
delete object;
return;
}
for(int i=0;i<object.LevelsCount();i++)
{
//--- set levels description
if(!object.SetString(OBJPROP_LEVELTEXT,i,"Level_"+IntegerToString(i)))
{
printf("Set string property error %d",GetLastError());
delete object;
return;
}
}
//--- delete object
delete object;
}


Save

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Save

Save

Saves parameters of the object in the file.

virtual bool Save(
int file_handle // File handle
)

Parameters

file_handle

[in] handle of the previously opened using the function FileOpen (...) file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CChartObject::Save
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
int file_handle;
CChartObject *object=new CChartObject;
//---
if(object!=NULL)
{
printf("Object create error");
return;
}
//--- set object parameters
//--- . . .
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_WRITE|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!object.Save(file_handle))
{
//--- file save error
printf("File save: Error %d!",GetLastError());
delete object;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- delete object
delete object;
}


Load

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Load

Load

Loads the parameters of the object from the file.

virtual bool Load(
int file_handle // File handle
)

Parameters

file_handle

[in] handle of the previously opened using the function FileOpen (...) file.

Returned Value

true - if successfully completed, false - if an error.

Example:

//--- example for CChartObject::Load
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
int file_handle;
CChartObject *object=new CChartObject;
//---
if(object!=NULL)
{
printf("Object create error");
return;
}
//--- open file
file_handle=FileOpen("MyFile.bin",FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle>=0)
{
if(!object.Load(file_handle))
{
//--- file load error
printf("File load: Error %d!",GetLastError());
delete object;
FileClose(file_handle);
//---
return;
}
FileClose(file_handle);
}
//--- use object
//--- . . .
//--- delete object
delete object;
}


Type

MQL5 Reference / Standard Library / Graphic Objects / CChartObject / Type

Type

Gets the type identifier graphic object.

virtual int Type()

Returned Value

ID type of object (for CChartObject - 0x8888).

Example:

//--- example for CChartObject::Type
#include <ChartObjects\ChartObject.mqh>
//---
void OnStart()
{
CChartObject *object=new CChartObject;
//---
if(object==NULL)
{
printf("Object create error");
return;
}
//--- get object type
int type=object.Type();
//--- delete object
delete object;
}


File Operations

MQL5 Reference / Standard Library / File Operations

File Operations


Operations with Strings

MQL5 Reference / Standard Library / Operations with Strings

Operations with Strings


Technical Indicators

MQL5 Reference / Standard Library / Technical Indicators

Technical Indicators


Migrating from MQL4

MQL5 Reference / Migrating from MQL4 Back

Migrating from MQL4

Language MQL5 is the development of its predecessor - the language MQL4, which is written a myriad of indicators, scripts, and expert.Despite the fact that most new programming language compatible with the language of the previous generation, there are still some differences between these languages.And when transferring programs these differences need to know.

This section contains information that is intended to facilitate the adaptation of its code so programmers who know MQL4, to a new language MQL5.

First it should be noted:

· Functions start (), init () and deinit () absent;
· The number of indicator buffers is not limited;
· Download dll occurs immediately after downloading an expert (or any other mql5-program);
· Shortened test logical conditions;
· In going beyond the current performance of the array is terminated (critical - with the withdrawal of errors);
· Operator Precedence in C + +;
· Works implicit type conversion (even from string to a number);
· Local variables are not automatically initialized (except strings);
· Conventional local arrays automatically destroyed.

Special functions init, start and deinit

In language MQL4 there were only three predefined functions that could be present in the code indicator, an adviser or a script (not taking into account the include files *.mqh files and libraries).These functions have in MQL5, but have their analogues.The table shows the approximate match functions.

MQL4 | MQL5
init | OnInit
start | OnStart
deinit | OnDeinit

Functions OnInit and OnDeinit perform the same role as the init and deinit in MQL4 - they are designed to accommodate the code, which must be performed during initialization and deinitsiplizatsii mql5-programs.You can either just rename this function properly, or leave them as is, but add a call to these functions in the field sootvestvvuyuschih.

Example:

void OnInit()
{
//--- Functions is called to initialize
init();
}
void OnDeinit(const int reason)
{
//--- Call the function with deinitialization
deinit();
//---
}

Start function is replaced by OnStart only in scripts, but for the expert and the indicator should it be renamed, respectively, in OnTick and OnCalculate. It is in these three functions is necessary to place code that must be fulfilled during the mql5-program:

mql5-program | main function
script | OnStart
indicator | OnCalculate
expert | OnTick

If the primary function is not in the executable code indicator or script, or the name of this function is not correct, then the call of this function is not performed.That is, if the source code of the script will not contain the function OnStart, then this code will be compiled as an adviser.

If the code is not an indicator function OnCalculate, the compilation of this indicator is not possible.

Predefined Variables

In MQL5 no predefined variables such as Ask, Bid, Bars. Variables and Point Digits little changed in writing, as shown in the table.

MQL4 | MQL5
Digits | _Digits
Point | _Point
 | _LastError
 | _Period
 | _Symbol
 | _StopFlag
 | _UninitReason

Access to Timeseries

In MQL5 no predefined taymsery Open [], High [], Low [], Close [], Volume [] and Time []. Necessary depth taymserii can now be set independently with appropriate functions to access taymseriyam.

Advisers (experts)

Experts in MQL5 not necessarily have to have a function handler events receipt of the new teak OnTick, as it was in MQL4 (function start in MQL4 is executed when you receive a new tick), because now experts in MQL5 may contain pre-defined handler functions are several types of events:

· OnTick- Receipt of a new tick;
· OnTimer- Timer event;
· OnChartEvent- Input events from the keyboard and mouse events moving a graphic object, the event finished editing the text in the box object LabelEdit;
· OnBookEvent- Event status change cup prices (Depth of Market).

Custom Indicators

In MQL4 number of indicator buffers is limited and can not be more than 8.In MQL5 no such limitation, but remember that each indicator buffer allocation requires a certain amount of memory for its location in the terminal, so the abuse that opens a new opportunity we should not.

In addition, in MQL4 was only 6 types of rendering custom indicator in MQL5 now 18 drawing style. And although the name of drawing has not changed, the very ideology of the graphical display of indicators has changed significantly.

It differs also indexed in the direction of indicator buffers.In MQL5 all the default buffer behave like normal arrays, ie the element with index 0 is the oldest in history, with an increase in the index, we are moving from the oldest to the most recent data.

The only function for work with custom indicators which is preserved from MQL4 - it SetIndexBuffer. But its call has changed, now you want to specify type of data to be stored in an array, Which is associated with the indicator buffer.

In addition, the properties have changed and expanded custom indicators, several new features access to timeseries , So you need a complete rethinking of the entire algorithm.

Graphic objects

The number of graphic objects in MQL5 increased significantly, but it appeared only one limitation - you can not use functions to work with graphic objects in custom indicators.

In addition, the positioning of graphic objects over time it became possible to within a second on the chart any time - now is not rounded points bindings graphics up to the time of opening the bar at the current price chart.

For objects, Arrow, Text Label and the opportunity to indicate way binding and for objects Label, Button, Chart, Bitmap Label and Edit have the opportunity to ask corner of the graph, which is attached object.