0% found this document useful (0 votes)
3 views

mql5

The MQL5 Language Reference is a comprehensive guide for the MetaTrader 5 client terminal, detailing the syntax, data types, operations, and functions necessary for creating technical indicators, algorithmic trading systems, and analytical tools. It covers language basics, object-oriented programming, constants, and various programming structures, providing a thorough understanding of MQL5 for users. This reference is essential for developers looking to automate trading strategies and develop custom indicators in financial markets.

Uploaded by

i.paint.this.way
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

mql5

The MQL5 Language Reference is a comprehensive guide for the MetaTrader 5 client terminal, detailing the syntax, data types, operations, and functions necessary for creating technical indicators, algorithmic trading systems, and analytical tools. It covers language basics, object-oriented programming, constants, and various programming structures, providing a thorough understanding of MQL5 for users. This reference is essential for developers looking to automate trading strategies and develop custom indicators in financial markets.

Uploaded by

i.paint.this.way
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6917

MQL5 Language REFERENCE

for the MetaTrader 5 client terminal

STUDY MQL5 and


SOLVE any tasks:
• Create your own technical indicators of any
complexity level

• Use algorithmic trading — automate strategies


to work on various financial markets

• Develop your own analytical tools based on


mathematical achievements and traditional
methods

• Write automated trading systems for solving


a wide range of tasks (trading, monitoring,
alerting, etc.)

© 2000-2025, MetaQuotes Ltd


2 Content

Content
MQL5 Reference 71
1 Language Basics................................................................................................. 74
Syntax ............................................................................................................................75
Comments......................................................................................................................... 76
I dentifiers......................................................................................................................... 77
Reserved Words
......................................................................................................................... 78
Data Types ............................................................................................................................80
I nteger Types
......................................................................................................................... 81
Char, Short, I................................................................................................................
nt and Long Types 82
Character Constants
................................................................................................................ 86
Datetime Type
................................................................................................................ 89
Color Type ................................................................................................................ 90
Bool Type ................................................................................................................ 91
Enumerations................................................................................................................ 92
Real Types.........................................................................................................................
(double, float) 94
Complex .........................................................................................................................
number (complex) 100
String Type
......................................................................................................................... 101
Structures,
.........................................................................................................................
Classes and I nterfaces 104
Dynamic .........................................................................................................................
Array Object 131
Matrices.........................................................................................................................
and vectors 132
Typecasting
......................................................................................................................... 139
Void Type
.........................................................................................................................
and NULL Constant 144
User-defined
.........................................................................................................................
Types 145
Object Pointers
......................................................................................................................... 155
References:
.........................................................................................................................
Modifier & and Keyword this 159
Operations............................................................................................................................161
and Expressions
Expressions
......................................................................................................................... 162
Arithmetic
.........................................................................................................................
Operations 163
Assignment
.........................................................................................................................
Operations 164
Operations
.........................................................................................................................
of Relation 165
Boolean Operations
......................................................................................................................... 166
Bitwise Operations
......................................................................................................................... 168
Other Operations
......................................................................................................................... 171
Precedence
.........................................................................................................................
Rules 175
Operators ............................................................................................................................177
Compound
.........................................................................................................................
Operator 178
Expression
.........................................................................................................................
Operator 179
Return Operator
......................................................................................................................... 180
Conditional
.........................................................................................................................
Operator if-else 181
Ternary Operator
.........................................................................................................................
?: 182
Switch Operator
......................................................................................................................... 184
Loop Operator
.........................................................................................................................
while 186
Loop Operator
.........................................................................................................................
for 187
Loop Operator
.........................................................................................................................
do while 188
Break Operator
......................................................................................................................... 189
Continue.........................................................................................................................
Operator 190
Object Create
.........................................................................................................................
Operator new 191
Object Delete
.........................................................................................................................
Operator delete 192
Functions ............................................................................................................................193
Function.........................................................................................................................
Call 195
Passing Parameters
......................................................................................................................... 196
Function.........................................................................................................................
Overloading 199
Operation
.........................................................................................................................
Overloading 202

© 2000-2025, MetaQuotes Ltd.


3 Content

Description
.........................................................................................................................
of External Functions 215
Exporting
.........................................................................................................................
Functions 217
Event Handling
.........................................................................................................................
Functions 218
Variables ............................................................................................................................230
Local Variables
......................................................................................................................... 234
Formal Parameters
......................................................................................................................... 236
Static Variables
......................................................................................................................... 238
Global Variables
......................................................................................................................... 240
I nput Variables
......................................................................................................................... 241
Extern Variables
......................................................................................................................... 247
z
I nitiali ation
.........................................................................................................................
of Variables 248
Visibility .........................................................................................................................
Scope and Lifetime of Variables 250
Creating.........................................................................................................................
and Deleting Objects 252
............................................................................................................................255
Preprocessor
Macro substitution #
.........................................................................................................................
( define) 257
#
Program.........................................................................................................................
Properties ( property) 260
#
I ncluding.........................................................................................................................
Files ( include) 266
I mporting #
.........................................................................................................................
Functions ( import) 267
Conditional # # # #
.........................................................................................................................
Compilation ( ifdef, ifndef, else, endif) 270
............................................................................................................................272
Object-Oriented Programming
Encapsulation
.........................................................................................................................
and Extensibility of Types 274
I nheritance
......................................................................................................................... 277
Polymorphism
......................................................................................................................... 282
Overload......................................................................................................................... 286
Virtual Functions
......................................................................................................................... 287
Static Members
.........................................................................................................................
of a Class 291
Function.........................................................................................................................
templates 295
Class templates
......................................................................................................................... 299
Abstract.........................................................................................................................
Classes 304
Namespaces............................................................................................................................306
2 Constants, Enumerations
.................................................................................................
and Structures 309
............................................................................................................................310
Chart Constants
Types of .........................................................................................................................
Chart Events 311
Chart Timeframes
......................................................................................................................... 318
Chart Properties
......................................................................................................................... 320
Positioning
.........................................................................................................................
Constants 328
Chart Representation
......................................................................................................................... 329
Examples.........................................................................................................................
of Working with the Chart 331
............................................................................................................................389
Objects Constants
Object Types
......................................................................................................................... 390
OBJ_VLI NE ................................................................................................................ 392
OBJ_HLI NE ................................................................................................................ 397
OBJ_TREND ................................................................................................................ 402
OBJ_TRENDB................................................................................................................
Y ANGLE 409
OBJ_C Y CLES................................................................................................................ 415
OBJ_ARROWED _LI NE
................................................................................................................ 421
OBJ_CHANNEL ................................................................................................................ 427
OBJ_STDDEVCHANNEL
................................................................................................................ 434
OBJ_REGRESSI................................................................................................................
ON 441
OBJ_PI TCHFORK
................................................................................................................ 447
OBJ_GANNLI................................................................................................................
NE 455
OBJ_GANNFAN ................................................................................................................ 462
OBJ_GANNGRI ................................................................................................................
D 469
OBJ_FI BO ................................................................................................................ 476
OBJ_FI BOTI MES
................................................................................................................ 483
OBJ_FI BOFAN................................................................................................................ 490
OBJ_FI BOARC................................................................................................................ 497
OBJ_FI BOCHANNEL
................................................................................................................ 504

© 2000-2025, MetaQuotes Ltd.


4 Content

OBJ_EX PANSI................................................................................................................
ON 512
OBJ_ELLI OTWAVE5
................................................................................................................ 520
OBJ_ELLI OTWAVE3
................................................................................................................ 528
OBJ_RECTAN................................................................................................................
GLE 535
OBJ_TRI ANG................................................................................................................
LE 541
OBJ_ELLI PSE................................................................................................................ 548
OBJ_ARROW................................................................................................................
_THUMB_UP 554
OBJ_ARROW................................................................................................................
_THUMB_DOWN 560
OBJ_ARROW................................................................................................................
_UP 566
OBJ_ARROW................................................................................................................
_DOWN 572
OBJ_ARROW................................................................................................................
_STOP 578
OBJ_ARROW................................................................................................................
_CHECK 584
OBJ_ARROW................................................................................................................
_LEFT_PRI CE 590
OBJ_ARROW................................................................................................................
_RI GHT_PRI CE 595
OBJ_ARROW................................................................................................................
_BUY 600
OBJ_ARROW................................................................................................................
_SELL 605
OBJ_ARROW................................................................................................................ 610
OBJ_TEX T ................................................................................................................ 616
OBJ_LABEL ................................................................................................................ 622
OBJ_BUTTON ................................................................................................................ 630
OBJ_CHART ................................................................................................................ 637
OBJ_BI TMAP................................................................................................................ 644
OBJ_BI TMAP................................................................................................................
_LABEL 651
OBJ_EDI T ................................................................................................................ 658
OBJ_EVENT ................................................................................................................ 665
OBJ_RECTAN................................................................................................................
GLE_LABEL 670
Object Properties
......................................................................................................................... 676
Methods .........................................................................................................................
of Object Binding 703
Chart Corner
......................................................................................................................... 708
Visibility .........................................................................................................................
of Objects 711
Levels of.........................................................................................................................
Elliott Wave 714
Gann Objects
......................................................................................................................... 715
Web Colors
......................................................................................................................... 717
Wingdings
......................................................................................................................... 719
............................................................................................................................720
Indicator Constants
Price Constants
......................................................................................................................... 721
Smoothing
.........................................................................................................................
Methods 724
I ndicators
.........................................................................................................................
Lines 725
Drawing .........................................................................................................................
Styles 727
Custom I.........................................................................................................................
ndicator Properties 732
I ndicator.........................................................................................................................
Types 738
Data Type
.........................................................................................................................
I dentifiers 740
............................................................................................................................741
Environment State
Client Terminal
.........................................................................................................................
Properties 742
Running MQL5
.........................................................................................................................
Program Properties 748
Symbol Properties
......................................................................................................................... 752
Account .........................................................................................................................
Properties 865
Testing Statistics
......................................................................................................................... 875
............................................................................................................................880
Trade Constants
History Database
.........................................................................................................................
Properties 881
Order Properties
......................................................................................................................... 882
Position Properties
......................................................................................................................... 900
Deal Properties
......................................................................................................................... 904
Trade Operation
.........................................................................................................................
Types 908
Trade Transaction
.........................................................................................................................
Types 920
Trade Orders
.........................................................................................................................
in DOM 922
Signal Properties
......................................................................................................................... 923
............................................................................................................................925
Named Constants

© 2000-2025, MetaQuotes Ltd.


5 Content

Predefined
.........................................................................................................................
Macro Substitutions 926
Mathematical
.........................................................................................................................
Constants 932
Numerical
.........................................................................................................................
Type Constants 934
z
Uninitiali.........................................................................................................................
ation Reason Codes 937
Checking.........................................................................................................................
Object Pointer 939
Other Constants
......................................................................................................................... 940
............................................................................................................................944
Data Structures
Date Type
.........................................................................................................................
Structure 945
I ndicator.........................................................................................................................
Parameter Structure 946
History Data
.........................................................................................................................
Structure 947
Order Book
.........................................................................................................................
Structure 948
q
Trade Re.........................................................................................................................
uest Structure 949
q
Re uest Check
.........................................................................................................................
Result Structure 962
q
Trade Re.........................................................................................................................
uest Result Structure 963
Trade Transaction
.........................................................................................................................
Structure 966
Price Data
.........................................................................................................................
Structure 974
Economic.........................................................................................................................
Сalendar structures 976
............................................................................................................................985
Codes of Errors and Warnings
Trade Server
.........................................................................................................................
Return Codes 986
Compiler .........................................................................................................................
Warnings 989
Compilation
.........................................................................................................................
Errors 992
Runtime.........................................................................................................................
Errors 1003
............................................................................................................................1016
Input/Output Constants
File Opening
.........................................................................................................................
Flags 1017
File Properties
......................................................................................................................... 1019
I n-File Position
......................................................................................................................... 1020
Use of a.........................................................................................................................
Codepage 1021
MessageBox
......................................................................................................................... 1022

3 MQL5 programs
................................................................................................. 1024
............................................................................................................................1025
Program Running
............................................................................................................................1032
Trade Permission
............................................................................................................................1036
Client Terminal Events
Resources............................................................................................................................1039
............................................................................................................................1051
Call of Imported Functions
............................................................................................................................1053
Runtime Errors
............................................................................................................................1054
Testing Trading Strategies
4 Predefined Variables
................................................................................................. 1080
_AppliedTo............................................................................................................................1081
_Digits ............................................................................................................................1083
_Point ............................................................................................................................1084
_LastError............................................................................................................................1085
_Period ............................................................................................................................1086
............................................................................................................................1087
_RandomSeed
_StopFlag ............................................................................................................................1088
_Symbol ............................................................................................................................1089
............................................................................................................................1090
_UninitReason
_IsX64 ............................................................................................................................1091
5 Common Functions
................................................................................................. 1092
Alert ............................................................................................................................1094
............................................................................................................................1099
CheckPointer
Comment ............................................................................................................................1101
............................................................................................................................1102
CryptEncode
............................................................................................................................1104
CryptDecode
DebugBreak............................................................................................................................1106
............................................................................................................................1107
ExpertRemove
GetPointer............................................................................................................................1109
............................................................................................................................1113
GetTickCount

© 2000-2025, MetaQuotes Ltd.


6 Content

............................................................................................................................1114
GetTickCount64
............................................................................................................................1116
GetMicrosecondCount
MessageBox............................................................................................................................1118
............................................................................................................................1123
PeriodSeconds
PlaySound............................................................................................................................1125
Print ............................................................................................................................1128
............................................................................................................................1130
PrintFormat
............................................................................................................................1136
ResetLastError
............................................................................................................................1137
ResourceCreate
............................................................................................................................1141
ResourceFree
............................................................................................................................1144
ResourceReadImage
............................................................................................................................1148
ResourceSave
............................................................................................................................1153
SetReturnError
............................................................................................................................1155
SetUserError
Sleep ............................................................................................................................1156
............................................................................................................................1158
TerminalClose
............................................................................................................................1160
TesterHideIndicators
............................................................................................................................1162
TesterStatistics
TesterStop............................................................................................................................1164
............................................................................................................................1166
TesterDeposit
............................................................................................................................1169
TesterWithdrawal
............................................................................................................................1172
TranslateKey
ZeroMemory............................................................................................................................1173
6 Array Functions
................................................................................................. 1176
............................................................................................................................1178
ArrayBsearch
ArrayCopy............................................................................................................................1182
............................................................................................................................1187
ArrayCompare
ArrayFree............................................................................................................................1190
............................................................................................................................1199
ArrayGetAsSeries
............................................................................................................................1202
ArrayInitialize
ArrayFill ............................................................................................................................1204
............................................................................................................................1206
ArrayIsDynamic
............................................................................................................................1208
ArrayIsSeries
............................................................................................................................1210
ArrayMaximum
............................................................................................................................1221
ArrayMinimum
ArrayPrint............................................................................................................................1232
ArrayRange............................................................................................................................1235
ArrayResiz............................................................................................................................1236
e
............................................................................................................................1239
ArrayInsert
............................................................................................................................1242
ArrayRemove
............................................................................................................................1244
ArrayReverse
............................................................................................................................1246
ArraySetAsSeries
ArraySize ............................................................................................................................1249
ArraySort............................................................................................................................1251
ArraySwap............................................................................................................................1256
............................................................................................................................1258
ArrayToFP16
ArrayToFP8............................................................................................................................1261
............................................................................................................................1264
ArrayFromFP16
............................................................................................................................1267
ArrayFromFP8
7 Matrix and Vector
.................................................................................................
Methods 1270
Matrix and............................................................................................................................1277
Vector Types
Enumerations
......................................................................................................................... 1278
............................................................................................................................1283
Initialization
Assign ......................................................................................................................... 1286
CopyI ndicatorBuffer
......................................................................................................................... 1288
CopyRates
......................................................................................................................... 1290
CopyTicks
......................................................................................................................... 1295
CopyTicksRange
......................................................................................................................... 1298

© 2000-2025, MetaQuotes Ltd.


7 Content

Eye ......................................................................................................................... 1300


I dentity......................................................................................................................... 1302
Ones ......................................................................................................................... 1304
Zeros ......................................................................................................................... 1305
Full ......................................................................................................................... 1306
Tri ......................................................................................................................... 1307
I nit ......................................................................................................................... 1308
Fill ......................................................................................................................... 1310
............................................................................................................................1311
Manipulations
HasNan......................................................................................................................... 1313
Transpose
......................................................................................................................... 1314
TransposeConjugate
......................................................................................................................... 1316
TriL ......................................................................................................................... 1317
TriU ......................................................................................................................... 1318
Diag ......................................................................................................................... 1319
Row ......................................................................................................................... 1321
Col ......................................................................................................................... 1323
Copy ......................................................................................................................... 1325
Compare
......................................................................................................................... 1327
CompareByDigits
......................................................................................................................... 1329
CompareE q
.........................................................................................................................
ual 1331
Flat ......................................................................................................................... 1334
Clip ......................................................................................................................... 1336
Reshape......................................................................................................................... 1337
z
Resi e ......................................................................................................................... 1339
Set ......................................................................................................................... 1341
SwapRows
......................................................................................................................... 1343
SwapCols
......................................................................................................................... 1344
Split ......................................................................................................................... 1345
Hsplit ......................................................................................................................... 1347
Vsplit ......................................................................................................................... 1349
ArgSort......................................................................................................................... 1351
Sort ......................................................................................................................... 1352
Operations............................................................................................................................1354
Mathematical
.........................................................................................................................
operations 1356
Mathematical
.........................................................................................................................
functions 1357
Products ............................................................................................................................1358
MatMul ......................................................................................................................... 1359
GeMM ......................................................................................................................... 1364
Power ......................................................................................................................... 1368
Dot ......................................................................................................................... 1371
Kron ......................................................................................................................... 1373
I nner ......................................................................................................................... 1375
Outer ......................................................................................................................... 1377
CorrCoef
......................................................................................................................... 1380
Cov ......................................................................................................................... 1384
Correlate
......................................................................................................................... 1387
Convolve
......................................................................................................................... 1390
............................................................................................................................1393
Transformations
Cholesky
......................................................................................................................... 1394
Eig ......................................................................................................................... 1395
EigVals ......................................................................................................................... 1398
LU ......................................................................................................................... 1399
LUP ......................................................................................................................... 1401
QR ......................................................................................................................... 1403
SVD ......................................................................................................................... 1405
Statistics ............................................................................................................................1408
ArgMax ......................................................................................................................... 1409

© 2000-2025, MetaQuotes Ltd.


8 Content

ArgMin ......................................................................................................................... 1410


Max ......................................................................................................................... 1411
Min ......................................................................................................................... 1412
Ptp ......................................................................................................................... 1413
Sum ......................................................................................................................... 1414
Prod ......................................................................................................................... 1415
CumSum......................................................................................................................... 1417
CumProd
......................................................................................................................... 1419
Percentile
......................................................................................................................... 1421
Quantile
......................................................................................................................... 1423
Median ......................................................................................................................... 1425
Mean ......................................................................................................................... 1427
Average......................................................................................................................... 1428
Std ......................................................................................................................... 1430
Var ......................................................................................................................... 1432
LinearRegression
......................................................................................................................... 1434
Features ............................................................................................................................1437
Rows ......................................................................................................................... 1438
Cols ......................................................................................................................... 1439
z
Si e ......................................................................................................................... 1440
Norm ......................................................................................................................... 1441
Cond ......................................................................................................................... 1444
Det ......................................................................................................................... 1447
SLogDet......................................................................................................................... 1449
Rank ......................................................................................................................... 1450
Trace ......................................................................................................................... 1453
Spectrum
......................................................................................................................... 1454
Solutions ............................................................................................................................1455
Solve ......................................................................................................................... 1456
LstS q ......................................................................................................................... 1457
I nv ......................................................................................................................... 1458
PI nv ......................................................................................................................... 1460
............................................................................................................................1461
Machine learning
Activation
......................................................................................................................... 1466
Derivative
......................................................................................................................... 1470
Loss ......................................................................................................................... 1472
G
Loss radient
......................................................................................................................... 1474
RegressionMetric
......................................................................................................................... 1476
ConfusionMatrix
......................................................................................................................... 1478
ConfusionMatrixMultilabel
......................................................................................................................... 1480
ClassificationMetric
......................................................................................................................... 1482
ClassificationScore
......................................................................................................................... 1486
PrecisionRecall
......................................................................................................................... 1490
ReceiverOperatingCharacteristic
......................................................................................................................... 1494
OpenBLAS............................................................................................................................1498
Singular.........................................................................................................................
Value Decomposition 1501
SingularValueDecompositionDC
................................................................................................................ 1502
SingularValueDecompositionQR
................................................................................................................ 1504
SingularValueDecompositionQRPivot
................................................................................................................ 1506
SingularValueDecompositionBisect
................................................................................................................ 1509
SingularValueDecomposition J
................................................................................................................
acobiHigh 1512
SingularValueDecomposition J
................................................................................................................
acobiLow 1517
SingularValueDecompositionBidiagDC
................................................................................................................ 1520
SingularValueDecompositionBidiagBisect
................................................................................................................ 1523
Eigen Values
......................................................................................................................... 1526
General Matrices
................................................................................................................ 1528
EigenSolver........................................................................................................... 1529
X
EigenSolver........................................................................................................... 1531

© 2000-2025, MetaQuotes Ltd.


9 Content

EigenSolverShur
........................................................................................................... 1535
EigenSolver2
........................................................................................................... 1537
EigenSolver2 X
........................................................................................................... 1540
EigenSolver2Shur
........................................................................................................... 1544
EigenSolver2Blocked
........................................................................................................... 1546
EigenSolver2ShurBlocked
........................................................................................................... 1549
Symmetric ................................................................................................................
Matrices 1552
EigenSymmetricDC
........................................................................................................... 1553
EigenSymmetricQR
........................................................................................................... 1555
EigenSymmetricRobust
........................................................................................................... 1557
EigenSymmetricBisect
........................................................................................................... 1560
Singular.........................................................................................................................
Spectrum Analysis 1563
SingularSpectrumAnalysisSpectrum
................................................................................................................ 1564
SingularSpectrumAnalysisForecast
................................................................................................................ 1565
SingularSpectrumAnalysisReconstructComponents
................................................................................................................ 1566
SingularSpectrumAnalysisReconstructSeries
................................................................................................................ 1567

8 Conversion Functions
................................................................................................. 1568
............................................................................................................................1570
CharToString
............................................................................................................................1572
CharArrayToString
............................................................................................................................1574
CharArrayToStruct
............................................................................................................................1578
StructToCharArray
............................................................................................................................1581
ColorToARGB
............................................................................................................................1583
ColorToString
............................................................................................................................1584
DoubleToString
............................................................................................................................1585
EnumToString
............................................................................................................................1587
IntegerToString
............................................................................................................................1589
ShortToString
............................................................................................................................1591
ShortArrayToString
............................................................................................................................1593
TimeToString
............................................................................................................................1596
NormalizeDouble
............................................................................................................................1598
StringToCharArray
............................................................................................................................1600
StringToColor
............................................................................................................................1601
StringToDouble
............................................................................................................................1602
StringToInteger
............................................................................................................................1603
StringToShortArray
............................................................................................................................1605
StringToTime
............................................................................................................................1608
StringFormat
9 Math Functions
................................................................................................. 1612
MathAbs ............................................................................................................................1614
MathArccos............................................................................................................................1615
MathArcsin............................................................................................................................1618
MathArctan............................................................................................................................1621
............................................................................................................................1624
MathArctan2
............................................................................................................................1628
MathClassify
MathCeil ............................................................................................................................1630
MathCos ............................................................................................................................1632
MathExp ............................................................................................................................1635
MathFloor............................................................................................................................1638
MathLog ............................................................................................................................1640
MathLog10............................................................................................................................1644
MathMax ............................................................................................................................1648
MathMin ............................................................................................................................1650
MathMod ............................................................................................................................1652
MathPow ............................................................................................................................1653
MathRand ............................................................................................................................1657
MathRound............................................................................................................................1658
MathSin ............................................................................................................................1660
MathSq rt ............................................................................................................................1663
© 2000-2025, MetaQuotes Ltd.
10 Content

MathSrand............................................................................................................................1667
MathTan ............................................................................................................................1670
............................................................................................................................1673
MathIsValidNumber
MathExpm1............................................................................................................................1674
MathLog1p............................................................................................................................1677
............................................................................................................................1681
MathArccosh
............................................................................................................................1684
MathArcsinh
............................................................................................................................1687
MathArctanh
MathCosh ............................................................................................................................1690
MathSinh ............................................................................................................................1693
MathTanh ............................................................................................................................1696
MathSwap............................................................................................................................1699
10 String Functions
................................................................................................. 1702
StringAdd ............................................................................................................................1703
............................................................................................................................1705
StringBufferLen
............................................................................................................................1706
StringCompare
............................................................................................................................1708
StringConcatenate
StringFill ............................................................................................................................1710
StringFind............................................................................................................................1711
............................................................................................................................1714
StringGetCharacter
StringInit ............................................................................................................................1716
StringLen ............................................................................................................................1717
............................................................................................................................1718
StringSetLength
............................................................................................................................1719
StringReplace
............................................................................................................................1720
StringReserve
............................................................................................................................1722
StringSetCharacter
StringSplit............................................................................................................................1724
............................................................................................................................1726
StringSubstr
............................................................................................................................1727
StringToLower
............................................................................................................................1728
StringToUpper
............................................................................................................................1729
StringTrimLeft
............................................................................................................................1730
StringTrimRight
11 Date and Time
................................................................................................. 1731
............................................................................................................................1732
TimeCurrent
............................................................................................................................1734
TimeTradeServer
TimeLocal............................................................................................................................1736
TimeGMT ............................................................................................................................1738
............................................................................................................................1740
TimeDaylightSavings
............................................................................................................................1741
TimeGMTOffset
............................................................................................................................1742
TimeToStruct
............................................................................................................................1743
StructToTime
12 Account Information
................................................................................................. 1745
............................................................................................................................1746
AccountInfoDouble
............................................................................................................................1747
AccountInfoInteger
............................................................................................................................1749
AccountInfoString
13 Checkup ................................................................................................. 1750
............................................................................................................................1751
GetLastError
IsStopped ............................................................................................................................1752
............................................................................................................................1753
UninitializeReason
............................................................................................................................1755
TerminalInfoInteger
............................................................................................................................1756
TerminalInfoDouble
............................................................................................................................1757
TerminalInfoString
............................................................................................................................1758
MQLInfoInteger
............................................................................................................................1759
MQLInfoString
Symbol ............................................................................................................................1760
Period ............................................................................................................................1761
Digits ............................................................................................................................1762
© 2000-2025, MetaQuotes Ltd.
11 Content

Point ............................................................................................................................1763
14 Event Handling
................................................................................................. 1764
OnStart ............................................................................................................................1766
OnInit ............................................................................................................................1769
OnDeinit ............................................................................................................................1772
OnTick ............................................................................................................................1775
............................................................................................................................1781
OnCalculate
OnTimer ............................................................................................................................1785
OnTrade ............................................................................................................................1788
............................................................................................................................1793
OnTradeTransaction
............................................................................................................................1799
OnBookEvent
............................................................................................................................1802
OnChartEvent
OnTester ............................................................................................................................1809
............................................................................................................................1816
OnTesterInit
............................................................................................................................1823
OnTesterDeinit
............................................................................................................................1824
OnTesterPass
15 Market Info ................................................................................................. 1825
............................................................................................................................1826
SymbolsTotal
............................................................................................................................1827
SymbolExist
............................................................................................................................1829
SymbolName
............................................................................................................................1831
SymbolSelect
............................................................................................................................1833
SymbolIsSynchroni zed
............................................................................................................................1834
SymbolInfoDouble
............................................................................................................................1836
SymbolInfoInteger
............................................................................................................................1838
SymbolInfoString
............................................................................................................................1840
SymbolInfoMarginRate
............................................................................................................................1842
SymbolInfoTick
............................................................................................................................1843
SymbolInfoSessionQuote
............................................................................................................................1845
SymbolInfoSessionTrade
............................................................................................................................1847
MarketBookAdd
............................................................................................................................1849
MarketBookRelease
............................................................................................................................1851
MarketBookGet
16 Economic Calendar
................................................................................................. 1852
............................................................................................................................1853
CalendarCountryById
............................................................................................................................1855
CalendarEventById
............................................................................................................................1858
CalendarValueById
............................................................................................................................1861
CalendarCountries
............................................................................................................................1863
CalendarEventByCountry
............................................................................................................................1865
CalendarEventByCurrency
............................................................................................................................1867
CalendarValueHistoryByEvent
............................................................................................................................1870
CalendarValueHistory
............................................................................................................................1873
CalendarValueLastByEvent
............................................................................................................................1878
CalendarValueLast
17 Timeseries and
.................................................................................................
Indicators Access 1883
............................................................................................................................1888
Indexing Direction in Arrays, Buffers and Timeseries
Organizing............................................................................................................................1891
Data Access
............................................................................................................................1900
SeriesInfoInteger
Bars ............................................................................................................................1902
............................................................................................................................1905
BarsCalculated
............................................................................................................................1907
IndicatorCreate
............................................................................................................................1909
IndicatorParameters
............................................................................................................................1911
IndicatorRelease
CopyBuffer............................................................................................................................1913
CopyRates............................................................................................................................1918
CopySeries............................................................................................................................1922
CopyTime............................................................................................................................1926
CopyOpen............................................................................................................................1929
© 2000-2025, MetaQuotes Ltd.
12 Content

CopyHigh ............................................................................................................................1932
CopyLow ............................................................................................................................1936
CopyClose............................................................................................................................1939
............................................................................................................................1942
CopyTickVolume
............................................................................................................................1946
CopyRealVolume
CopySpread............................................................................................................................1949
CopyTicks............................................................................................................................1953
............................................................................................................................1959
CopyTicksRange
iBars ............................................................................................................................1961
iBarShift ............................................................................................................................1962
iClose ............................................................................................................................1965
iHigh ............................................................................................................................1967
iHighest ............................................................................................................................1969
iLow ............................................................................................................................1970
iLowest ............................................................................................................................1972
iOpen ............................................................................................................................1973
iTime ............................................................................................................................1975
............................................................................................................................1977
iTickVolume
............................................................................................................................1979
iRealVolume
iVolume ............................................................................................................................1981
iSpread ............................................................................................................................1983
18 Custom Symbols
................................................................................................. 1985
............................................................................................................................1986
CustomSymbolCreate
............................................................................................................................1989
CustomSymbolDelete
............................................................................................................................1991
CustomSymbolSetInteger
............................................................................................................................1995
CustomSymbolSetDouble
............................................................................................................................1999
CustomSymbolSetString
............................................................................................................................2003
CustomSymbolSetMarginRate
............................................................................................................................2008
CustomSymbolSetSessionQuote
............................................................................................................................2013
CustomSymbolSetSessionTrade
............................................................................................................................2018
CustomRatesDelete
............................................................................................................................2023
CustomRatesReplace
............................................................................................................................2028
CustomRatesUpdate
............................................................................................................................2033
CustomTicksAdd
............................................................................................................................2041
CustomTicksDelete
............................................................................................................................2049
CustomTicksReplace
............................................................................................................................2058
CustomBookAdd
19 Chart Operations
................................................................................................. 2061
............................................................................................................................2063
ChartApplyTemplate
............................................................................................................................2066
ChartSaveTemplate
............................................................................................................................2071
ChartWindowFind
............................................................................................................................2073
ChartTimePriceToXY
............................................................................................................................2075
ChartXYToTimePrice
ChartOpen............................................................................................................................2077
ChartFirst ............................................................................................................................2079
ChartNext............................................................................................................................2080
ChartClose............................................................................................................................2081
ChartSymbol............................................................................................................................2083
ChartPeriod............................................................................................................................2084
ChartRedraw............................................................................................................................2085
............................................................................................................................2088
ChartSetDouble
............................................................................................................................2090
ChartSetInteger
............................................................................................................................2092
ChartSetString
............................................................................................................................2094
ChartGetDouble
............................................................................................................................2096
ChartGetInteger
............................................................................................................................2098
ChartGetString
............................................................................................................................2100
ChartNavigate
ChartID ............................................................................................................................2103
© 2000-2025, MetaQuotes Ltd.
13 Content

............................................................................................................................2105
ChartIndicatorAdd
............................................................................................................................2109
ChartIndicatorDelete
............................................................................................................................2112
ChartIndicatorGet
............................................................................................................................2114
ChartIndicatorName
............................................................................................................................2116
ChartIndicatorsTotal
............................................................................................................................2118
ChartWindowOnDropped
............................................................................................................................2119
ChartPriceOnDropped
............................................................................................................................2120
ChartTimeOnDropped
............................................................................................................................2121
ChartXOnDropped
............................................................................................................................2122
ChartYOnDropped
............................................................................................................................2123
ChartSetSymbolPeriod
............................................................................................................................2125
ChartScreenShot
20 Trade Functions
................................................................................................. 2128
............................................................................................................................2130
OrderCalcMargin
............................................................................................................................2134
OrderCalcProfit
OrderCheck............................................................................................................................2137
OrderSend............................................................................................................................2141
............................................................................................................................2146
OrderSendAsync
............................................................................................................................2157
PositionsTotal
............................................................................................................................2158
PositionGetSymbol
............................................................................................................................2160
PositionSelect
............................................................................................................................2162
PositionSelectByTicket
............................................................................................................................2164
PositionGetDouble
............................................................................................................................2167
PositionGetInteger
............................................................................................................................2169
PositionGetString
............................................................................................................................2172
PositionGetTicket
............................................................................................................................2174
OrdersTotal
............................................................................................................................2175
OrderGetTicket
............................................................................................................................2177
OrderSelect
............................................................................................................................2181
OrderGetDouble
............................................................................................................................2185
OrderGetInteger
............................................................................................................................2191
OrderGetString
............................................................................................................................2194
HistorySelect
............................................................................................................................2196
HistorySelectByPosition
............................................................................................................................2200
HistoryOrderSelect
............................................................................................................................2203
HistoryOrdersTotal
............................................................................................................................2204
HistoryOrderGetTicket
............................................................................................................................2206
HistoryOrderGetDouble
............................................................................................................................2210
HistoryOrderGetInteger
............................................................................................................................2213
HistoryOrderGetString
............................................................................................................................2216
HistoryDealSelect
............................................................................................................................2219
HistoryDealsTotal
............................................................................................................................2220
HistoryDealGetTicket
............................................................................................................................2222
HistoryDealGetDouble
............................................................................................................................2227
HistoryDealGetInteger
............................................................................................................................2230
HistoryDealGetString
21 Trade Signals................................................................................................. 2234
............................................................................................................................2235
SignalBaseGetDouble
............................................................................................................................2236
SignalBaseGetInteger
............................................................................................................................2237
SignalBaseGetString
............................................................................................................................2238
SignalBaseSelect
............................................................................................................................2239
SignalBaseTotal
............................................................................................................................2240
SignalInfoGetDouble
............................................................................................................................2241
SignalInfoGetInteger
............................................................................................................................2242
SignalInfoGetString
............................................................................................................................2243
SignalInfoSetDouble
............................................................................................................................2244
SignalInfoSetInteger
............................................................................................................................2245
SignalSubscribe
© 2000-2025, MetaQuotes Ltd.
14 Content

............................................................................................................................2246
SignalUnSubscribe
22 Network Functions
................................................................................................. 2247
............................................................................................................................2249
SocketCreate
............................................................................................................................2252
SocketClose
............................................................................................................................2255
SocketConnect
............................................................................................................................2259
SocketIsConnected
............................................................................................................................2263
SocketIsReadable
............................................................................................................................2266
SocketIsWritable
............................................................................................................................2270
SocketTimeouts
............................................................................................................................2272
SocketRead
............................................................................................................................2276
SocketSend
............................................................................................................................2280
SocketTlsHandshake
............................................................................................................................2285
SocketTlsCertificate
............................................................................................................................2289
SocketTlsRead
............................................................................................................................2293
SocketTlsReadAvailable
............................................................................................................................2298
SocketTlsSend
............................................................................................................................2302
WebRe q uest
SendFTP ............................................................................................................................2305
SendMail ............................................................................................................................2307
............................................................................................................................2309
SendNotification
23 Global Variables
.................................................................................................
of the Terminal 2311
............................................................................................................................2312
GlobalVariableCheck
............................................................................................................................2313
GlobalVariableTime
............................................................................................................................2314
GlobalVariableDel
............................................................................................................................2315
GlobalVariableGet
............................................................................................................................2316
GlobalVariableName
............................................................................................................................2317
GlobalVariableSet
............................................................................................................................2318
GlobalVariablesFlush
............................................................................................................................2319
GlobalVariableTemp
............................................................................................................................2320
GlobalVariableSetOnCondition
............................................................................................................................2321
GlobalVariablesDeleteAll
............................................................................................................................2322
GlobalVariablesTotal
24 File Functions................................................................................................. 2323
............................................................................................................................2326
FileSelectDialog
............................................................................................................................2328
FileFindFirst
FileFindNext............................................................................................................................2330
............................................................................................................................2332
FileFindClose
FileIsExist ............................................................................................................................2334
FileOpen ............................................................................................................................2337
FileClose ............................................................................................................................2340
FileCopy ............................................................................................................................2341
FileDelete............................................................................................................................2344
FileMove ............................................................................................................................2346
FileFlush ............................................................................................................................2348
............................................................................................................................2350
FileGetInteger
FileIsEnding............................................................................................................................2353
............................................................................................................................2355
FileIsLineEnding
............................................................................................................................2360
FileReadArray
FileReadBool............................................................................................................................2362
............................................................................................................................2365
FileReadDatetime
............................................................................................................................2368
FileReadDouble
............................................................................................................................2371
FileReadFloat
............................................................................................................................2374
FileReadInteger
FileReadLong............................................................................................................................2378
............................................................................................................................2381
FileReadNumber
............................................................................................................................2386
FileReadString
............................................................................................................................2388
FileReadStruct

© 2000-2025, MetaQuotes Ltd.


15 Content

FileSeek ............................................................................................................................2392
FileSize ............................................................................................................................2395
FileTell ............................................................................................................................2397
FileWrite ............................................................................................................................2400
............................................................................................................................2403
FileWriteArray
............................................................................................................................2406
FileWriteDouble
............................................................................................................................2409
FileWriteFloat
............................................................................................................................2411
FileWriteInteger
............................................................................................................................2414
FileWriteLong
............................................................................................................................2416
FileWriteString
............................................................................................................................2419
FileWriteStruct
FileLoad ............................................................................................................................2422
FileSave ............................................................................................................................2424
............................................................................................................................2426
FolderCreate
............................................................................................................................2429
FolderDelete
............................................................................................................................2432
FolderClean
25 Custom Indicators
................................................................................................. 2435
............................................................................................................................2438
Indicator Styles in Examples
_
DRAW NONE
......................................................................................................................... 2449
_
DRAW LI
.........................................................................................................................
NE 2452
DRAW _SECTI
.........................................................................................................................
ON 2456
DRAW _HI STO GRAM
......................................................................................................................... 2460
DRAW _HI STO GRAM2
......................................................................................................................... 2464
DRAW _ARROW
......................................................................................................................... 2468
DRAW _Z.........................................................................................................................
I GZAG 2473
DRAW _FI LLI NG
......................................................................................................................... 2478
DRAW _BARS
......................................................................................................................... 2483
DRAW _CANDLES
......................................................................................................................... 2489
DRAW _COLOR _LI NE
......................................................................................................................... 2495
DRAW _COLOR _SECTI ON
......................................................................................................................... 2500
DRAW _COLOR _HI STO GRAM
......................................................................................................................... 2506
DRAW _COLOR _HI STO GRAM2
......................................................................................................................... 2511
DRAW _COLOR _ARROW
......................................................................................................................... 2516
DRAW _COLOR _ZI GZAG
......................................................................................................................... 2522
DRAW _COLOR _BARS
......................................................................................................................... 2527
DRAW _COLOR _CANDLES
......................................................................................................................... 2534
Connection............................................................................................................................2541
between Indicator Properties and Functions
............................................................................................................................2544
SetIndexBuffer
............................................................................................................................2547
IndicatorSetDouble
............................................................................................................................2551
IndicatorSetInteger
............................................................................................................................2555
IndicatorSetString
............................................................................................................................2558
PlotIndexSetDouble
............................................................................................................................2559
PlotIndexSetInteger
............................................................................................................................2563
PlotIndexSetString
............................................................................................................................2564
PlotIndexGetInteger
26 Object Functions
................................................................................................. 2567
............................................................................................................................2569
ObjectCreate
ObjectName............................................................................................................................2573
............................................................................................................................2574
ObjectDelete
............................................................................................................................2575
ObjectsDeleteAll
ObjectFind............................................................................................................................2576
............................................................................................................................2577
ObjectGetTimeByValue
............................................................................................................................2578
ObjectGetValueByTime
ObjectMove............................................................................................................................2579
............................................................................................................................2580
ObjectsTotal
............................................................................................................................2581
ObjectSetDouble
............................................................................................................................2585
ObjectSetInteger
............................................................................................................................2588
ObjectSetString
© 2000-2025, MetaQuotes Ltd.
16 Content

............................................................................................................................2590
ObjectGetDouble
............................................................................................................................2592
ObjectGetInteger
............................................................................................................................2594
ObjectGetString
............................................................................................................................2596
TextSetFont
TextOut ............................................................................................................................2598
TextGetSiz............................................................................................................................2602
e
27 Technical Indicators
................................................................................................. 2603
iAC ............................................................................................................................2606
iAD ............................................................................................................................2611
iADX ............................................................................................................................2616
iADXWilder ............................................................................................................................2621
iAlligator ............................................................................................................................2626
iAMA ............................................................................................................................2633
iAO ............................................................................................................................2638
iATR ............................................................................................................................2643
iBearsPower............................................................................................................................2648
iBands ............................................................................................................................2653
iBullsPower............................................................................................................................2659
iCCI ............................................................................................................................2664
iChaikin ............................................................................................................................2669
iCustom ............................................................................................................................2674
iDEMA ............................................................................................................................2678
iDeMarker............................................................................................................................2683
iEnvelopes............................................................................................................................2688
iForce ............................................................................................................................2694
iFractals ............................................................................................................................2699
iFrAMA ............................................................................................................................2704
iGator ............................................................................................................................2709
iIchimoku ............................................................................................................................2716
iBWMFI ............................................................................................................................2723
iMomentum ............................................................................................................................2728
iMFI ............................................................................................................................2733
iMA ............................................................................................................................2738
iOsMA ............................................................................................................................2743
iMACD ............................................................................................................................2748
iOBV ............................................................................................................................2754
iSAR ............................................................................................................................2759
iRSI ............................................................................................................................2764
iRVI ............................................................................................................................2769
iStdDev ............................................................................................................................2774
iStochastic............................................................................................................................2779
iTEMA ............................................................................................................................2785
iTriX ............................................................................................................................2790
iWPR ............................................................................................................................2795
iVIDyA ............................................................................................................................2800
iVolumes ............................................................................................................................2805
28 Working with.................................................................................................
Optimization Results 2810
FrameFirst............................................................................................................................2812
FrameFilter............................................................................................................................2813
FrameNext............................................................................................................................2814
............................................................................................................................2815
FrameInputs
FrameAdd............................................................................................................................2816
............................................................................................................................2817
ParameterGetRange
............................................................................................................................2820
ParameterSetRange
29 Working with.................................................................................................
Events 2822
............................................................................................................................2823
EventSetMillisecondTimer
............................................................................................................................2824
EventSetTimer

© 2000-2025, MetaQuotes Ltd.


17 Content

............................................................................................................................2825
EventKillTimer
............................................................................................................................2826
EventChartCustom
30 Working with.................................................................................................
OpenCL 2832
............................................................................................................................2834
CLHandleType
............................................................................................................................2835
CLGetInfoInteger
............................................................................................................................2838
CLGetInfoString
............................................................................................................................2841
CLContextCreate
............................................................................................................................2842
CLContextFree
............................................................................................................................2843
CLGetDeviceInfo
............................................................................................................................2848
CLProgramCreate
............................................................................................................................2853
CLProgramFree
............................................................................................................................2854
CLKernelCreate
............................................................................................................................2855
CLKernelFree
............................................................................................................................2856
CLSetKernelArg
............................................................................................................................2857
CLSetKernelArgMem
............................................................................................................................2858
CLSetKernelArgMemLocal
............................................................................................................................2859
CLBufferCreate
............................................................................................................................2860
CLBufferFree
............................................................................................................................2861
CLBufferWrite
............................................................................................................................2866
CLBufferRead
CLExecute............................................................................................................................2870
............................................................................................................................2872
CLExecutionStatus
31 Working with.................................................................................................
databases 2873
............................................................................................................................2876
DatabaseOpen
............................................................................................................................2878
DatabaseClose
............................................................................................................................2879
DatabaseImport
............................................................................................................................2882
DatabaseExport
............................................................................................................................2888
DatabasePrint
............................................................................................................................2893
DatabaseTableExists
............................................................................................................................2894
DatabaseExecute
............................................................................................................................2906
DatabasePrepare
............................................................................................................................2915
DatabaseReset
............................................................................................................................2921
DatabaseBind
............................................................................................................................2926
DatabaseBindArray
............................................................................................................................2931
DatabaseRead
............................................................................................................................2932
DatabaseReadBind
............................................................................................................................2936
DatabaseFinali ze
............................................................................................................................2937
DatabaseTransactionBegin
............................................................................................................................2942
DatabaseTransactionCommit
............................................................................................................................2943
DatabaseTransactionRollback
............................................................................................................................2944
DatabaseColumnsCount
............................................................................................................................2945
DatabaseColumnName
............................................................................................................................2946
DatabaseColumnType
............................................................................................................................2947
DatabaseColumnSi ze
............................................................................................................................2948
DatabaseColumnText
............................................................................................................................2949
DatabaseColumnInteger
............................................................................................................................2950
DatabaseColumnLong
............................................................................................................................2951
DatabaseColumnDouble
............................................................................................................................2952
DatabaseColumnBlob
32 Working with.................................................................................................
DirectX 2953
............................................................................................................................2955
DXContextCreate
............................................................................................................................2956
DXContextSetSi ze
............................................................................................................................2957
DXContextGetSi ze
............................................................................................................................2958
DXContextClearColors
............................................................................................................................2959
DXContextClearDepth
............................................................................................................................2960
DXContextGetColors
............................................................................................................................2961
DXContextGetDepth

© 2000-2025, MetaQuotes Ltd.


18 Content

............................................................................................................................2962
DXBufferCreate
............................................................................................................................2963
DXTextureCreate
............................................................................................................................2969
DXInputCreate
DXInputSet............................................................................................................................2970
............................................................................................................................2971
DXShaderCreate
............................................................................................................................2972
DXShaderSetLayout
............................................................................................................................2973
DXShaderInputsSet
............................................................................................................................2974
DXShaderTexturesSet
DXDraw ............................................................................................................................2975
............................................................................................................................2976
DXDrawIndexed
............................................................................................................................2977
DXPrimiveTopologySet
............................................................................................................................2978
DXBufferSet
............................................................................................................................2979
DXShaderSet
............................................................................................................................2980
DXHandleType
DXRelease............................................................................................................................2981
33 Python Integration
................................................................................................. 2982
initialize ............................................................................................................................2988
login ............................................................................................................................2990
shutdown............................................................................................................................2993
version ............................................................................................................................2994
last_error............................................................................................................................2996
............................................................................................................................2998
account_info
............................................................................................................................3001
terminal_info
............................................................................................................................3004
symbols_total
symbols_get............................................................................................................................3005
symbol_info............................................................................................................................3008
............................................................................................................................3012
symbol_info_tick
............................................................................................................................3014
symbol_select
............................................................................................................................3018
market_book_add
............................................................................................................................3019
market_book_get
............................................................................................................................3022
market_book_release
............................................................................................................................3023
copy_rates_from
............................................................................................................................3027
copy_rates_from_pos
............................................................................................................................3030
copy_rates_range
............................................................................................................................3033
copy_ticks_from
............................................................................................................................3036
copy_ticks_range
............................................................................................................................3039
orders_total
orders_get............................................................................................................................3040
............................................................................................................................3043
order_calc_margin
............................................................................................................................3046
order_calc_profit
order_check............................................................................................................................3049
order_send ............................................................................................................................3053
............................................................................................................................3058
positions_total
............................................................................................................................3059
positions_get
............................................................................................................................3062
history_orders_total
............................................................................................................................3064
history_orders_get
............................................................................................................................3067
history_deals_total
............................................................................................................................3069
history_deals_get
34 ONNX models................................................................................................. 3073
............................................................................................................................3074
ONNX Support
............................................................................................................................3076
Format Conversion
Automatic............................................................................................................................3077
data type conversion
Creating a............................................................................................................................3081
Model
Running a............................................................................................................................3088
model
Validation............................................................................................................................3094
in the Strategy Tester
OnnxCreate............................................................................................................................3099
............................................................................................................................3100
OnnxCreateFromBuffer
............................................................................................................................3101
OnnxRelease
© 2000-2025, MetaQuotes Ltd.
19 Content

OnnxRun ............................................................................................................................3102
............................................................................................................................3105
OnnxGetInputCount
............................................................................................................................3106
OnnxGetOutputCount
............................................................................................................................3107
OnnxGetInputName
............................................................................................................................3108
OnnxGetOutputName
............................................................................................................................3109
OnnxGetInputTypeInfo
............................................................................................................................3110
OnnxGetOutputTypeInfo
............................................................................................................................3111
OnnxSetInputShape
............................................................................................................................3112
OnnxSetOutputShape
............................................................................................................................3113
Data structures
35 Standard Library
................................................................................................. 3117
............................................................................................................................3118
Mathematics
Statistics
......................................................................................................................... 3119
Statistical Characteristics
................................................................................................................ 3122
MathMean ........................................................................................................... 3123
MathVariance
........................................................................................................... 3124
MathSkewness
........................................................................................................... 3125
MathKurtosis
........................................................................................................... 3126
MathMoments
........................................................................................................... 3127
MathMedian
........................................................................................................... 3128
MathStandardDeviation
........................................................................................................... 3129
MathAverageDeviation
........................................................................................................... 3130
Normal Distribution
................................................................................................................ 3131
MathProbabilityDensityNormal
........................................................................................................... 3135
MathCumulativeDistributionNormal
........................................................................................................... 3137
MathQuantileNormal
........................................................................................................... 3139
MathRandomNormal
........................................................................................................... 3141
MathMomentsNormal
........................................................................................................... 3142
Log-normal................................................................................................................
distribution 3143
MathProbabilityDensityLognormal
........................................................................................................... 3147
MathCumulativeDistributionLognormal
........................................................................................................... 3149
MathQuantileLognormal
........................................................................................................... 3151
MathRandomLognormal
........................................................................................................... 3153
MathMomentsLognormal
........................................................................................................... 3154
Beta distribution
................................................................................................................ 3155
MathProbabilityDensityBeta
........................................................................................................... 3159
MathCumulativeDistributionBeta
........................................................................................................... 3161
MathQuantileBeta
........................................................................................................... 3163
MathRandomBeta
........................................................................................................... 3165
MathMomentsBeta
........................................................................................................... 3166
Noncentral................................................................................................................
beta distribution 3167
MathProbabilityDensityNoncentralBeta
........................................................................................................... 3171
MathCumulativeDistributionNoncentralBeta
........................................................................................................... 3173
MathQuantileNoncentralBeta
........................................................................................................... 3175
MathRandomNoncentralBeta
........................................................................................................... 3177
MathMomentsNoncentralBeta
........................................................................................................... 3178
Gamma distribution
................................................................................................................ 3179
MathProbabilityDensity Gamma
........................................................................................................... 3183
MathCumulativeDistribution Gamma
........................................................................................................... 3185
MathQuantile Gamma
........................................................................................................... 3187
MathRandom Gamma
........................................................................................................... 3189
MathMoments Gamma
........................................................................................................... 3190
Chi-s quared
................................................................................................................
distribution 3191
MathProbabilityDensityChiS quare
........................................................................................................... 3195
MathCumulativeDistributionChiS quare
........................................................................................................... 3197
MathQuantileChiS quare
........................................................................................................... 3199
MathRandomChiS quare
........................................................................................................... 3201
MathMomentsChiS quare
........................................................................................................... 3202

© 2000-2025, MetaQuotes Ltd.


20 Content

q
Noncentral................................................................................................................
chi-s uared distribution 3203
MathProbabilityDensityNoncentralChiS q
...........................................................................................................
uare 3207
MathCumulativeDistributionNoncentralChiS q
...........................................................................................................
uare 3209
MathQuantileNoncentralChiS q
...........................................................................................................
uare 3211
MathRandomNoncentralChiS quare
........................................................................................................... 3213
MathMomentsNoncentralChiS quare
........................................................................................................... 3214
Exponential
................................................................................................................
distribution 3215
MathProbabilityDensityExponential
........................................................................................................... 3219
MathCumulativeDistributionExponential
........................................................................................................... 3221
MathQuantileExponential
........................................................................................................... 3223
MathRandomExponential
........................................................................................................... 3225
MathMomentsExponential
........................................................................................................... 3226
F-distribution
................................................................................................................ 3227
MathProbabilityDensityF
........................................................................................................... 3231
MathCumulativeDistributionF
........................................................................................................... 3233
MathQuantileF
........................................................................................................... 3235
MathRandomF
........................................................................................................... 3237
MathMomentsF
........................................................................................................... 3238
Noncentral................................................................................................................
F-distribution 3239
MathProbabilityDensityNoncentralF
........................................................................................................... 3243
MathCumulativeDistributionNoncentralF
........................................................................................................... 3245
MathQuantileNoncentralF
........................................................................................................... 3247
MathRandomNoncentralF
........................................................................................................... 3249
MathMomentsNoncentralF
........................................................................................................... 3250
T-distribution
................................................................................................................ 3251
MathProbabilityDensityT
........................................................................................................... 3255
MathCumulativeDistributionT
........................................................................................................... 3257
MathQuantileT
........................................................................................................... 3259
MathRandomT
........................................................................................................... 3261
MathMomentsT
........................................................................................................... 3262
Noncentral................................................................................................................
t-distribution 3263
MathProbabilityDensityNoncentralT
........................................................................................................... 3267
MathCumulativeDistributionNoncentralT
........................................................................................................... 3269
MathQuantileNoncentralT
........................................................................................................... 3271
MathRandomNoncentralT
........................................................................................................... 3273
MathMomentsNoncentralT
........................................................................................................... 3274
Logistic distribution
................................................................................................................ 3275
MathProbabilityDensityLogistic
........................................................................................................... 3279
MathCumulativeDistributionLogistic
........................................................................................................... 3281
MathQuantileLogistic
........................................................................................................... 3283
MathRandomLogistic
........................................................................................................... 3285
MathMomentsLogistic
........................................................................................................... 3286
Cauchy distribution
................................................................................................................ 3287
MathProbabilityDensityCauchy
........................................................................................................... 3291
MathCumulativeDistributionCauchy
........................................................................................................... 3293
MathQuantileCauchy
........................................................................................................... 3295
MathRandomCauchy
........................................................................................................... 3297
MathMomentsCauchy
........................................................................................................... 3298
Uniform distribution
................................................................................................................ 3299
MathProbabilityDensityUniform
........................................................................................................... 3303
MathCumulativeDistributionUniform
........................................................................................................... 3305
MathQuantileUniform
........................................................................................................... 3307
MathRandomUniform
........................................................................................................... 3309
MathMomentsUniform
........................................................................................................... 3310
Weibull distribution
................................................................................................................ 3311
MathProbabilityDensityWeibull
........................................................................................................... 3315
MathCumulativeDistributionWeibull
........................................................................................................... 3317
MathQuantileWeibull
........................................................................................................... 3319

© 2000-2025, MetaQuotes Ltd.


21 Content

MathRandomWeibull
........................................................................................................... 3321
MathMomentsWeibull
........................................................................................................... 3322
Binomial distribution
................................................................................................................ 3323
MathProbabilityDensityBinomial
........................................................................................................... 3326
MathCumulativeDistributionBinomial
........................................................................................................... 3328
MathQuantileBinomial
........................................................................................................... 3330
MathRandomBinomial
........................................................................................................... 3332
MathMomentsBinomial
........................................................................................................... 3333
Negative binomial
................................................................................................................
distribution 3334
MathProbabilityDensityNegativeBinomial
........................................................................................................... 3337
MathCumulativeDistributionNegativeBinomial
........................................................................................................... 3339
MathQuantileNegativeBinomial
........................................................................................................... 3341
MathRandomNegativeBinomial
........................................................................................................... 3343
MathMomentsNegativeBinomial
........................................................................................................... 3344
Geometric ................................................................................................................
distribution 3345
MathProbabilityDensity Geometric
........................................................................................................... 3349
MathCumulativeDistribution Geometric
........................................................................................................... 3351
MathQuantile Geometric
........................................................................................................... 3353
MathRandom Geometric
........................................................................................................... 3355
MathMoments Geometric
........................................................................................................... 3356
Hypergeometric
................................................................................................................
distribution 3357
MathProbabilityDensityHypergeometric
........................................................................................................... 3361
MathCumulativeDistributionHypergeometric
........................................................................................................... 3363
MathQuantileHypergeometric
........................................................................................................... 3365
MathRandomHypergeometric
........................................................................................................... 3367
MathMomentsHypergeometric
........................................................................................................... 3368
Poisson distribution
................................................................................................................ 3369
MathProbabilityDensityPoisson
........................................................................................................... 3373
MathCumulativeDistributionPoisson
........................................................................................................... 3375
MathQuantilePoisson
........................................................................................................... 3377
MathRandomPoisson
........................................................................................................... 3379
MathMomentsPoisson
........................................................................................................... 3380
Subfunctions
................................................................................................................ 3381
MathRandomNon Z
...........................................................................................................
ero 3386
MathMoments
........................................................................................................... 3387
MathPowI nt
........................................................................................................... 3388
MathFactorial
........................................................................................................... 3389
MathTrunc........................................................................................................... 3390
MathRound........................................................................................................... 3391
MathArctan2
........................................................................................................... 3393
G
Math amma
........................................................................................................... 3395
G
Math ammaLog
........................................................................................................... 3396
MathBeta ........................................................................................................... 3397
MathBetaLog
........................................................................................................... 3398
MathBetaI ncomplete
........................................................................................................... 3399
G
Math ammaI
...........................................................................................................
ncomplete 3400
MathBinomialCoefficient
........................................................................................................... 3401
MathBinomialCoefficientLog
........................................................................................................... 3402
MathHypergeometric2F2
........................................................................................................... 3403
q
MathSe uence
........................................................................................................... 3404
q
MathSe uenceByCount
........................................................................................................... 3405
MathReplicate
........................................................................................................... 3406
MathReverse
........................................................................................................... 3407
MathI dentical
........................................................................................................... 3408
MathUni ueq
........................................................................................................... 3409
MathQuickSortAscending
........................................................................................................... 3410
MathQuickSortDescending
........................................................................................................... 3411
MathQuickSort
........................................................................................................... 3412

© 2000-2025, MetaQuotes Ltd.


22 Content

MathOrder........................................................................................................... 3413
MathBitwiseNot
........................................................................................................... 3414
MathBitwiseAnd
........................................................................................................... 3415
MathBitwiseOr
........................................................................................................... 3416
MathBitwise X
...........................................................................................................
or 3417
MathBitwiseShiftL
........................................................................................................... 3418
MathBitwiseShiftR
........................................................................................................... 3419
MathCumulativeSum
........................................................................................................... 3420
MathCumulativeProduct
........................................................................................................... 3421
MathCumulativeMin
........................................................................................................... 3422
MathCumulativeMax
........................................................................................................... 3423
MathSin ........................................................................................................... 3424
MathCos ........................................................................................................... 3425
MathTan ........................................................................................................... 3426
MathArcsin........................................................................................................... 3427
MathArccos
........................................................................................................... 3428
MathArctan
........................................................................................................... 3429
MathSinPi ........................................................................................................... 3430
MathCosPi ........................................................................................................... 3431
MathTanPi ........................................................................................................... 3432
MathAbs ........................................................................................................... 3433
MathCeil ........................................................................................................... 3434
MathFloor ........................................................................................................... 3435
q
MathS rt ........................................................................................................... 3436
MathExp ........................................................................................................... 3437
MathPow ........................................................................................................... 3438
MathLog ........................................................................................................... 3439
MathLog2 ........................................................................................................... 3440
MathLog10........................................................................................................... 3441
MathLog1p........................................................................................................... 3442
MathDifference
........................................................................................................... 3443
MathSample
........................................................................................................... 3445
MathTukeySummary
........................................................................................................... 3448
MathRange........................................................................................................... 3449
MathMin ........................................................................................................... 3450
MathMax ........................................................................................................... 3451
MathSum ........................................................................................................... 3452
MathProduct
........................................................................................................... 3453
MathStandardDeviation
........................................................................................................... 3454
MathAverageDeviation
........................................................................................................... 3455
MathMedian
........................................................................................................... 3456
MathMean ........................................................................................................... 3457
MathVariance
........................................................................................................... 3458
MathSkewness
........................................................................................................... 3459
MathKurtosis
........................................................................................................... 3460
MathExpm1........................................................................................................... 3461
MathSinh ........................................................................................................... 3462
MathCosh ........................................................................................................... 3463
MathTanh ........................................................................................................... 3464
MathArcsinh
........................................................................................................... 3465
MathArccosh
........................................................................................................... 3466
MathArctanh
........................................................................................................... 3467
MathSignif ........................................................................................................... 3468
MathRank ........................................................................................................... 3470
MathCorrelationPearson
........................................................................................................... 3471
MathCorrelationSpearman
........................................................................................................... 3472
MathCorrelationKendall
........................................................................................................... 3473
MathQuantile
........................................................................................................... 3474

© 2000-2025, MetaQuotes Ltd.


23 Content

MathProbabilityDensityEmpirical
........................................................................................................... 3475
MathCumulativeDistributionEmpirical
........................................................................................................... 3476
zz y Logic
Fu ......................................................................................................................... 3477
Membership
................................................................................................................
functions 3478
CConstantMembershipFunction
........................................................................................................... 3480
GetValue ........................................................................................................... 3482
CCompositeMembershipFunction
........................................................................................................... 3483
CompositionType
........................................................................................................... 3485
MembershipFunctions
........................................................................................................... 3485
GetValue ........................................................................................................... 3485
CDifferencTwoSigmoidalMembershipFunction
........................................................................................................... 3487
A1 ........................................................................................................... 3489
A2 ........................................................................................................... 3489
C1 ........................................................................................................... 3490
C2 ........................................................................................................... 3490
GetValue ........................................................................................................... 3491
C Generaliz...........................................................................................................
edBellShapedMembershipFunction 3492
A ........................................................................................................... 3494
B ........................................................................................................... 3494
C ........................................................................................................... 3495
GetValue ........................................................................................................... 3495
CNormalCombinationMembershipFunction
........................................................................................................... 3496
B1 ........................................................................................................... 3498
B2 ........................................................................................................... 3498
Sigma1 ........................................................................................................... 3499
Sigma2 ........................................................................................................... 3499
GetValue ........................................................................................................... 3500
CNormalMembershipFunction
........................................................................................................... 3501
B ........................................................................................................... 3503
Sigma ........................................................................................................... 3503
GetValue ........................................................................................................... 3504
CP_ShapedMembershipFunction
........................................................................................................... 3505
A ........................................................................................................... 3507
B ........................................................................................................... 3507
C ........................................................................................................... 3508
D ........................................................................................................... 3508
GetValue ........................................................................................................... 3508
CProductTwoSigmoidalMembershipFunctions
........................................................................................................... 3510
A1 ........................................................................................................... 3512
A2 ........................................................................................................... 3512
C1 ........................................................................................................... 3513
C2 ........................................................................................................... 3513
GetValue ........................................................................................................... 3514
CS_ShapedMembershipFunction
........................................................................................................... 3515
A ........................................................................................................... 3517
B ........................................................................................................... 3517
GetValue ........................................................................................................... 3518
CSigmoidalMembershipFunction
........................................................................................................... 3519
A ........................................................................................................... 3521
C ........................................................................................................... 3521
GetValue ........................................................................................................... 3522
CTrapez oidMembershipFunction
........................................................................................................... 3523
X1 ........................................................................................................... 3525
X2 ........................................................................................................... 3525
X3 ........................................................................................................... 3526
X4 ........................................................................................................... 3526
GetValue ........................................................................................................... 3527
CTriangularMembershipFunction
........................................................................................................... 3528

© 2000-2025, MetaQuotes Ltd.


24 Content

X1 ........................................................................................................... 3530
X2 ........................................................................................................... 3530
X3 ........................................................................................................... 3531
ToNormalMF
........................................................................................................... 3531
GetValue ........................................................................................................... 3531
C Z_ShapedMembershipFunction
........................................................................................................... 3533
A ........................................................................................................... 3535
B ........................................................................................................... 3535
GetValue ........................................................................................................... 3536
I MembershipFunction
........................................................................................................... 3537
GetValue ........................................................................................................... 3537
zz y systems
Fu ................................................................................................................
rules 3538
CMamdaniFu zz yRule
........................................................................................................... 3539
Conclusion........................................................................................................... 3539
Weight ........................................................................................................... 3540
zz
CSugenoFu...........................................................................................................
yRule 3541
Conclusion........................................................................................................... 3541
CSingleCondition
........................................................................................................... 3543
Not ........................................................................................................... 3543
Term ........................................................................................................... 3544
Var ........................................................................................................... 3544
CConditions
........................................................................................................... 3546
ConditionsList
........................................................................................................... 3546
Not ........................................................................................................... 3547
Op ........................................................................................................... 3547
G
C enericFu zz
...........................................................................................................
yRule 3548
Conclusion........................................................................................................... 3548
Condition ........................................................................................................... 3549
CreateCondition
........................................................................................................... 3549
zz y systems
Fu ................................................................................................................
variables 3551
CFuzz yVariable
........................................................................................................... 3552
AddTerm ........................................................................................................... 3553
GetTermByName
........................................................................................................... 3553
Max ........................................................................................................... 3553
Min ........................................................................................................... 3554
Terms ........................................................................................................... 3554
Values ........................................................................................................... 3554
CSugenoVariable
........................................................................................................... 3556
Functions ........................................................................................................... 3556
GetFuncByName
........................................................................................................... 3557
Values ........................................................................................................... 3557
zz y terms
Fu ................................................................................................................ 3558
MembershipFunction
........................................................................................................... 3559
zz y systems
Fu ................................................................................................................ 3560
Mamdani system
........................................................................................................... 3561
AggregationMethod
........................................................................................................... 3561
Calculate ........................................................................................................... 3562
Defu zz ificationMethod
........................................................................................................... 3562
EmptyRule ........................................................................................................... 3562
I mplicationMethod
........................................................................................................... 3562
Output ........................................................................................................... 3563
OutputByName
........................................................................................................... 3563
ParseRule ........................................................................................................... 3563
Rules ........................................................................................................... 3563
Sugeno system
........................................................................................................... 3565
Calculate ........................................................................................................... 3565
CreateSugenoFunction
........................................................................................................... 3566
EmptyRule ........................................................................................................... 3567

© 2000-2025, MetaQuotes Ltd.


25 Content

Output ........................................................................................................... 3567


OutputByName
........................................................................................................... 3567
ParseRule ........................................................................................................... 3567
Rules ........................................................................................................... 3568
OpenCL ............................................................................................................................3569
BufferCreate
......................................................................................................................... 3571
BufferFree
......................................................................................................................... 3572
BufferFromArray
......................................................................................................................... 3573
BufferRead
......................................................................................................................... 3574
BufferWrite
......................................................................................................................... 3575
Execute......................................................................................................................... 3576
GetContext......................................................................................................................... 3577
GetKernel ......................................................................................................................... 3578
GetKernelName
......................................................................................................................... 3579
GetProgram......................................................................................................................... 3580
I nitializ.........................................................................................................................
e 3581
KernelCreate
......................................................................................................................... 3582
KernelFree
......................................................................................................................... 3583
SetArgument
......................................................................................................................... 3584
SetArgumentBuffer
......................................................................................................................... 3585
SetArgumentLocalMemory
......................................................................................................................... 3586
SetBuffersCount
......................................................................................................................... 3587
SetKernelsCount
......................................................................................................................... 3588
Shutdown
......................................................................................................................... 3589
SupportDouble
......................................................................................................................... 3590
Basic Class............................................................................................................................3591
CObject
Prev ......................................................................................................................... 3592
Prev ......................................................................................................................... 3593
Next ......................................................................................................................... 3594
Next ......................................................................................................................... 3595
Compare
......................................................................................................................... 3596
Save ......................................................................................................................... 3598
Load ......................................................................................................................... 3600
Type ......................................................................................................................... 3602
............................................................................................................................3603
Data Collections
CArray ......................................................................................................................... 3604
Step ................................................................................................................ 3606
Step ................................................................................................................ 3607
Total ................................................................................................................ 3608
Available ................................................................................................................ 3609
Max ................................................................................................................ 3610
I sSorted ................................................................................................................ 3611
SortMode ................................................................................................................ 3612
Clear ................................................................................................................ 3613
Sort ................................................................................................................ 3614
Save ................................................................................................................ 3615
Load ................................................................................................................ 3616
CArrayChar
......................................................................................................................... 3617
Reserve ................................................................................................................ 3619
Resi ez ................................................................................................................ 3620
Shutdown ................................................................................................................ 3621
Add ................................................................................................................ 3622
AddArray ................................................................................................................ 3623
AddArray ................................................................................................................ 3624
I nsert ................................................................................................................ 3626
I nsertArray
................................................................................................................ 3627
I nsertArray
................................................................................................................ 3628
AssignArray
................................................................................................................ 3630

© 2000-2025, MetaQuotes Ltd.


26 Content

AssignArray
................................................................................................................ 3631
Update ................................................................................................................ 3633
Shift ................................................................................................................ 3634
Delete ................................................................................................................ 3635
DeleteRange
................................................................................................................ 3636
At ................................................................................................................ 3637
CompareArray
................................................................................................................ 3639
CompareArray
................................................................................................................ 3640
I nsertSort ................................................................................................................ 3641
Search ................................................................................................................ 3642
G
Search reat
................................................................................................................ 3643
SearchLess................................................................................................................ 3644
G
Search reatOrE q
................................................................................................................
ual 3645
SearchLessOrE q
................................................................................................................
ual 3646
SearchFirst................................................................................................................ 3647
SearchLast................................................................................................................ 3648
SearchLinear
................................................................................................................ 3649
Save ................................................................................................................ 3650
Load ................................................................................................................ 3651
Type ................................................................................................................ 3653
CArrayShort
......................................................................................................................... 3654
Reserve ................................................................................................................ 3657
Resi ez ................................................................................................................ 3658
Shutdown ................................................................................................................ 3659
Add ................................................................................................................ 3660
AddArray ................................................................................................................ 3661
AddArray ................................................................................................................ 3662
I nsert ................................................................................................................ 3664
I nsertArray
................................................................................................................ 3665
I nsertArray
................................................................................................................ 3666
AssignArray
................................................................................................................ 3668
AssignArray
................................................................................................................ 3669
Update ................................................................................................................ 3671
Shift ................................................................................................................ 3672
Delete ................................................................................................................ 3673
DeleteRange
................................................................................................................ 3674
At ................................................................................................................ 3675
CompareArray
................................................................................................................ 3677
CompareArray
................................................................................................................ 3678
I nsertSort ................................................................................................................ 3679
Search ................................................................................................................ 3680
G
Search reat
................................................................................................................ 3681
SearchLess................................................................................................................ 3682
G
Search reatOrE q
................................................................................................................
ual 3683
SearchLessOrE q
................................................................................................................
ual 3684
SearchFirst................................................................................................................ 3685
SearchLast................................................................................................................ 3686
SearchLinear
................................................................................................................ 3687
Save ................................................................................................................ 3688
Load ................................................................................................................ 3690
Type ................................................................................................................ 3692
CArrayI.........................................................................................................................
nt 3693
Reserve ................................................................................................................ 3696
Resi ez ................................................................................................................ 3697
Shutdown ................................................................................................................ 3698
Add ................................................................................................................ 3699
AddArray ................................................................................................................ 3700
AddArray ................................................................................................................ 3701

© 2000-2025, MetaQuotes Ltd.


27 Content

I nsert ................................................................................................................ 3703


I nsertArray
................................................................................................................ 3704
I nsertArray
................................................................................................................ 3705
AssignArray
................................................................................................................ 3707
AssignArray
................................................................................................................ 3708
Update ................................................................................................................ 3710
Shift ................................................................................................................ 3711
Delete ................................................................................................................ 3712
DeleteRange
................................................................................................................ 3713
At ................................................................................................................ 3714
CompareArray
................................................................................................................ 3716
CompareArray
................................................................................................................ 3717
I nsertSort ................................................................................................................ 3718
Search ................................................................................................................ 3719
G
Search reat
................................................................................................................ 3720
SearchLess................................................................................................................ 3721
G
Search reatOrE q
................................................................................................................
ual 3722
SearchLessOrE q
................................................................................................................
ual 3723
SearchFirst................................................................................................................ 3724
SearchLast................................................................................................................ 3725
SearchLinear
................................................................................................................ 3726
Save ................................................................................................................ 3727
Load ................................................................................................................ 3729
Type ................................................................................................................ 3731
CArrayLong
......................................................................................................................... 3732
Reserve ................................................................................................................ 3735
Resi ez ................................................................................................................ 3736
Shutdown ................................................................................................................ 3737
Add ................................................................................................................ 3738
AddArray ................................................................................................................ 3739
AddArray ................................................................................................................ 3740
I nsert ................................................................................................................ 3742
I nsertArray
................................................................................................................ 3743
I nsertArray
................................................................................................................ 3744
AssignArray
................................................................................................................ 3746
AssignArray
................................................................................................................ 3747
Update ................................................................................................................ 3749
Shift ................................................................................................................ 3750
Delete ................................................................................................................ 3751
DeleteRange
................................................................................................................ 3752
At ................................................................................................................ 3753
CompareArray
................................................................................................................ 3755
CompareArray
................................................................................................................ 3756
I nsertSort ................................................................................................................ 3757
Search ................................................................................................................ 3758
G
Search reat
................................................................................................................ 3759
SearchLess................................................................................................................ 3760
G
Search reatOrE q
................................................................................................................
ual 3761
SearchLessOrE q
................................................................................................................
ual 3762
SearchFirst................................................................................................................ 3763
SearchLast................................................................................................................ 3764
SearchLinear
................................................................................................................ 3765
Save ................................................................................................................ 3766
Load ................................................................................................................ 3768
Type ................................................................................................................ 3770
CArrayFloat
......................................................................................................................... 3771
Delta ................................................................................................................ 3774
Reserve ................................................................................................................ 3775

© 2000-2025, MetaQuotes Ltd.


28 Content

Resi ez ................................................................................................................ 3776


Shutdown ................................................................................................................ 3777
Add ................................................................................................................ 3778
AddArray ................................................................................................................ 3779
AddArray ................................................................................................................ 3780
I nsert ................................................................................................................ 3782
I nsertArray
................................................................................................................ 3783
I nsertArray
................................................................................................................ 3784
AssignArray
................................................................................................................ 3786
AssignArray
................................................................................................................ 3787
Update ................................................................................................................ 3789
Shift ................................................................................................................ 3790
Delete ................................................................................................................ 3791
DeleteRange
................................................................................................................ 3792
At ................................................................................................................ 3793
CompareArray
................................................................................................................ 3795
CompareArray
................................................................................................................ 3796
I nsertSort ................................................................................................................ 3797
Search ................................................................................................................ 3798
G
Search reat
................................................................................................................ 3799
SearchLess................................................................................................................ 3800
G
Search reatOrE q
................................................................................................................
ual 3801
SearchLessOrE q
................................................................................................................
ual 3802
SearchFirst................................................................................................................ 3803
SearchLast................................................................................................................ 3804
SearchLinear
................................................................................................................ 3805
Save ................................................................................................................ 3806
Load ................................................................................................................ 3808
Type ................................................................................................................ 3810
CArrayDouble
......................................................................................................................... 3811
Delta ................................................................................................................ 3814
Reserve ................................................................................................................ 3815
Resi ez ................................................................................................................ 3816
Shutdown ................................................................................................................ 3817
Add ................................................................................................................ 3818
AddArray ................................................................................................................ 3819
AddArray ................................................................................................................ 3820
I nsert ................................................................................................................ 3822
I nsertArray
................................................................................................................ 3823
I nsertArray
................................................................................................................ 3824
AssignArray
................................................................................................................ 3826
AssignArray
................................................................................................................ 3827
Update ................................................................................................................ 3829
Shift ................................................................................................................ 3830
Delete ................................................................................................................ 3831
DeleteRange
................................................................................................................ 3832
At ................................................................................................................ 3833
CompareArray
................................................................................................................ 3835
CompareArray
................................................................................................................ 3836
Minimum ................................................................................................................ 3837
Maximum ................................................................................................................ 3838
I nsertSort ................................................................................................................ 3839
Search ................................................................................................................ 3840
G
Search reat
................................................................................................................ 3841
SearchLess................................................................................................................ 3842
G
Search reatOrE q
................................................................................................................
ual 3843
SearchLessOrE q
................................................................................................................
ual 3844
SearchFirst................................................................................................................ 3845

© 2000-2025, MetaQuotes Ltd.


29 Content

SearchLast................................................................................................................ 3846
SearchLinear
................................................................................................................ 3847
Save ................................................................................................................ 3848
Load ................................................................................................................ 3850
Type ................................................................................................................ 3852
CArrayString
......................................................................................................................... 3853
Reserve ................................................................................................................ 3856
Resi ez ................................................................................................................ 3857
Shutdown ................................................................................................................ 3858
Add ................................................................................................................ 3859
AddArray ................................................................................................................ 3860
AddArray ................................................................................................................ 3861
I nsert ................................................................................................................ 3863
I nsertArray
................................................................................................................ 3864
I nsertArray
................................................................................................................ 3865
AssignArray
................................................................................................................ 3867
AssignArray
................................................................................................................ 3868
Update ................................................................................................................ 3870
Shift ................................................................................................................ 3871
Delete ................................................................................................................ 3872
DeleteRange
................................................................................................................ 3873
At ................................................................................................................ 3874
CompareArray
................................................................................................................ 3876
CompareArray
................................................................................................................ 3877
I nsertSort ................................................................................................................ 3878
Search ................................................................................................................ 3879
G
Search reat
................................................................................................................ 3880
SearchLess................................................................................................................ 3881
G
Search reatOrE q
................................................................................................................
ual 3882
SearchLessOrE q
................................................................................................................
ual 3883
SearchFirst................................................................................................................ 3884
SearchLast................................................................................................................ 3885
SearchLinear
................................................................................................................ 3886
Save ................................................................................................................ 3887
Load ................................................................................................................ 3889
Type ................................................................................................................ 3891
CArrayObj
......................................................................................................................... 3892
FreeMode ................................................................................................................ 3897
FreeMode ................................................................................................................ 3898
Reserve ................................................................................................................ 3900
Resi ez ................................................................................................................ 3901
Clear ................................................................................................................ 3902
Shutdown ................................................................................................................ 3903
CreateElement
................................................................................................................ 3904
Add ................................................................................................................ 3906
AddArray ................................................................................................................ 3907
I nsert ................................................................................................................ 3910
I nsertArray
................................................................................................................ 3912
AssignArray
................................................................................................................ 3914
Update ................................................................................................................ 3916
Shift ................................................................................................................ 3917
Detach ................................................................................................................ 3918
Delete ................................................................................................................ 3919
DeleteRange
................................................................................................................ 3920
At ................................................................................................................ 3921
CompareArray
................................................................................................................ 3922
I nsertSort ................................................................................................................ 3923
Search ................................................................................................................ 3924

© 2000-2025, MetaQuotes Ltd.


30 Content

G
Search reat
................................................................................................................ 3925
SearchLess................................................................................................................ 3926
G
Search reatOrE q
................................................................................................................
ual 3927
SearchLessOrE q
................................................................................................................
ual 3929
SearchFirst................................................................................................................ 3930
SearchLast................................................................................................................ 3931
Save ................................................................................................................ 3932
Load ................................................................................................................ 3933
Type ................................................................................................................ 3935
CList ......................................................................................................................... 3936
FreeMode ................................................................................................................ 3938
FreeMode ................................................................................................................ 3939
Total ................................................................................................................ 3941
I sSorted ................................................................................................................ 3942
SortMode ................................................................................................................ 3943
CreateElement
................................................................................................................ 3944
Add ................................................................................................................ 3945
I nsert ................................................................................................................ 3946
DetachCurrent
................................................................................................................ 3948
DeleteCurrent
................................................................................................................ 3949
Delete ................................................................................................................ 3950
Clear ................................................................................................................ 3951
I ndexOf ................................................................................................................ 3952
GetNodeAtI................................................................................................................
ndex 3953
GetFirstNode
................................................................................................................ 3954
GetPrevNode
................................................................................................................ 3955
GetCurrentNode
................................................................................................................ 3956
GetNextNode
................................................................................................................ 3957
GetLastNode
................................................................................................................ 3958
Sort ................................................................................................................ 3959
MoveToI ndex
................................................................................................................ 3960
Exchange ................................................................................................................ 3961
CompareList
................................................................................................................ 3962
Search ................................................................................................................ 3963
Save ................................................................................................................ 3964
Load ................................................................................................................ 3966
Type ................................................................................................................ 3968
CTreeNode
......................................................................................................................... 3969
Owner ................................................................................................................ 3974
Left ................................................................................................................ 3975
Right ................................................................................................................ 3976
Balance ................................................................................................................ 3977
BalanceL ................................................................................................................ 3978
BalanceR ................................................................................................................ 3979
CreateSample
................................................................................................................ 3980
RefreshBalance
................................................................................................................ 3981
GetNext ................................................................................................................ 3982
SaveNode ................................................................................................................ 3983
LoadNode ................................................................................................................ 3984
Type ................................................................................................................ 3985
CTree ......................................................................................................................... 3986
Root ................................................................................................................ 3992
CreateElement
................................................................................................................ 3993
I nsert ................................................................................................................ 3994
Detach ................................................................................................................ 3995
Delete ................................................................................................................ 3996
Clear ................................................................................................................ 3997
Find ................................................................................................................ 3998

© 2000-2025, MetaQuotes Ltd.


31 Content

Save ................................................................................................................ 3999


Load ................................................................................................................ 4000
Type ................................................................................................................ 4001
............................................................................................................................4002
Generic Data Collections
I Collection < >
.........................................................................................................................
T 4004
Add ................................................................................................................ 4005
Count ................................................................................................................ 4006
Contains ................................................................................................................ 4007
CopyTo ................................................................................................................ 4008
Clear ................................................................................................................ 4009
Remove ................................................................................................................ 4010
q
I E ualityComparable < >
.........................................................................................................................
T 4011
q
E uals ................................................................................................................ 4012
HashCode ................................................................................................................ 4013
I Comparable < >
.........................................................................................................................
T 4014
Compare ................................................................................................................ 4015
I Comparer < >
.........................................................................................................................
T 4016
Compare ................................................................................................................ 4017
q
I E ualityComparer < >
.........................................................................................................................
T 4018
q
E uals ................................................................................................................ 4019
HashCode ................................................................................................................ 4020
< >
I List T ......................................................................................................................... 4021
G
Try etValue
................................................................................................................ 4022
TrySetValue
................................................................................................................ 4023
I nsert ................................................................................................................ 4024
I ndexOf ................................................................................................................ 4025
LastI ndexOf
................................................................................................................ 4026
RemoveAt ................................................................................................................ 4027
<
I Map TKey,TValue >
......................................................................................................................... 4028
Add ................................................................................................................ 4029
Contains ................................................................................................................ 4030
Remove ................................................................................................................ 4031
G
Try etValue
................................................................................................................ 4032
TrySetValue
................................................................................................................ 4033
CopyTo ................................................................................................................ 4034
< >
I Set T ......................................................................................................................... 4035
ExceptWith
................................................................................................................ 4037
I ntersectWith
................................................................................................................ 4038
SymmetricExceptWith
................................................................................................................ 4039
UnionWith ................................................................................................................ 4040
I sProperSubsetOf
................................................................................................................ 4041
I sProperSupersetOf
................................................................................................................ 4042
I sSubsetOf................................................................................................................ 4043
I sSupersetOf
................................................................................................................ 4044
Overlaps ................................................................................................................ 4045
q
SetE uals ................................................................................................................ 4046
CDefaultComparer < >
.........................................................................................................................
T 4047
Compare ................................................................................................................ 4048
CDefaultE q < >
.........................................................................................................................
ualityComparer T 4049
q
E uals ................................................................................................................ 4050
HashCode ................................................................................................................ 4051
CRedBlackTreeNode < >
.........................................................................................................................
T 4052
Value ................................................................................................................ 4053
Parent ................................................................................................................ 4054
Left ................................................................................................................ 4055
Right ................................................................................................................ 4056
Color ................................................................................................................ 4057
I sLeaf ................................................................................................................ 4058

© 2000-2025, MetaQuotes Ltd.


32 Content

CreateEmptyNode
................................................................................................................ 4059
CLinkedListNode < >
.........................................................................................................................
T 4060
List ................................................................................................................ 4061
Next ................................................................................................................ 4062
Previous ................................................................................................................ 4063
Value ................................................................................................................ 4064
CKeyValuePair < >
.........................................................................................................................
TKey,TValue 4065
Key ................................................................................................................ 4066
Value ................................................................................................................ 4067
Clone ................................................................................................................ 4068
Compare ................................................................................................................ 4069
q
E uals ................................................................................................................ 4070
HashCode ................................................................................................................ 4071
CArrayList < >
.........................................................................................................................
T 4072
Capacity ................................................................................................................ 4074
Count ................................................................................................................ 4075
Contains ................................................................................................................ 4076
TrimExcess................................................................................................................ 4077
G
Try etValue
................................................................................................................ 4078
TrySetValue
................................................................................................................ 4079
Add ................................................................................................................ 4080
AddRange ................................................................................................................ 4081
I nsert ................................................................................................................ 4082
I nsertRange
................................................................................................................ 4083
CopyTo ................................................................................................................ 4084
BinarySearch
................................................................................................................ 4085
I ndexOf ................................................................................................................ 4086
LastI ndexOf
................................................................................................................ 4087
Clear ................................................................................................................ 4088
Remove ................................................................................................................ 4089
RemoveAt ................................................................................................................ 4090
RemoveRange
................................................................................................................ 4091
Reverse ................................................................................................................ 4092
Sort ................................................................................................................ 4093
CHashMap < >
.........................................................................................................................
TKey,TValue 4094
Add ................................................................................................................ 4096
Count ................................................................................................................ 4097
Comparer ................................................................................................................ 4098
Contains ................................................................................................................ 4099
ContainsKey
................................................................................................................ 4100
ContainsValue
................................................................................................................ 4101
CopyTo ................................................................................................................ 4102
Clear ................................................................................................................ 4103
Remove ................................................................................................................ 4104
G
Try etValue
................................................................................................................ 4105
TrySetValue
................................................................................................................ 4106
CHashSet < >
.........................................................................................................................
T 4107
Add ................................................................................................................ 4109
Count ................................................................................................................ 4110
Contains ................................................................................................................ 4111
Comparer ................................................................................................................ 4112
TrimExcess................................................................................................................ 4113
CopyTo ................................................................................................................ 4114
Clear ................................................................................................................ 4115
Remove ................................................................................................................ 4116
ExceptWith
................................................................................................................ 4117
I ntersectWith
................................................................................................................ 4118
SymmetricExceptWith
................................................................................................................ 4119

© 2000-2025, MetaQuotes Ltd.


33 Content

UnionWith ................................................................................................................ 4120


I sProperSubsetOf
................................................................................................................ 4121
I sProperSupersetOf
................................................................................................................ 4122
I sSubsetOf................................................................................................................ 4123
I sSupersetOf
................................................................................................................ 4124
Overlaps ................................................................................................................ 4125
q
SetE uals ................................................................................................................ 4126
CLinkedList < >
.........................................................................................................................
T 4127
Add ................................................................................................................ 4129
AddAfter ................................................................................................................ 4130
AddBefore ................................................................................................................ 4131
AddFirst ................................................................................................................ 4132
AddLast ................................................................................................................ 4133
Count ................................................................................................................ 4134
Head ................................................................................................................ 4135
First ................................................................................................................ 4136
Last ................................................................................................................ 4137
Contains ................................................................................................................ 4138
CopyTo ................................................................................................................ 4139
Clear ................................................................................................................ 4140
Remove ................................................................................................................ 4141
RemoveFirst
................................................................................................................ 4142
RemoveLast
................................................................................................................ 4143
Find ................................................................................................................ 4144
FindLast ................................................................................................................ 4145
T < >
CQueue......................................................................................................................... 4146
Add ................................................................................................................ 4147
q
En ueue ................................................................................................................ 4148
Count ................................................................................................................ 4149
Contains ................................................................................................................ 4150
TrimExcess................................................................................................................ 4151
CopyTo ................................................................................................................ 4152
Clear ................................................................................................................ 4153
Remove ................................................................................................................ 4154
q
De ueue ................................................................................................................ 4155
Peek ................................................................................................................ 4156
CRedBlackTree < >
.........................................................................................................................
T 4157
Add ................................................................................................................ 4159
Count ................................................................................................................ 4160
Root ................................................................................................................ 4161
Contains ................................................................................................................ 4162
Comparer ................................................................................................................ 4163
G
Try etMin ................................................................................................................ 4164
G
Try etMax................................................................................................................ 4165
CopyTo ................................................................................................................ 4166
Clear ................................................................................................................ 4167
Remove ................................................................................................................ 4168
RemoveMin................................................................................................................ 4169
RemoveMax................................................................................................................ 4170
Find ................................................................................................................ 4171
FindMin ................................................................................................................ 4172
FindMax ................................................................................................................ 4173
CSortedMap < >
.........................................................................................................................
TKey, TValue 4174
Add ................................................................................................................ 4176
Count ................................................................................................................ 4177
Comparer ................................................................................................................ 4178
Contains ................................................................................................................ 4179
ContainsKey
................................................................................................................ 4180

© 2000-2025, MetaQuotes Ltd.


34 Content

ContainsValue
................................................................................................................ 4181
CopyTo ................................................................................................................ 4182
Clear ................................................................................................................ 4183
Remove ................................................................................................................ 4184
G
Try etValue
................................................................................................................ 4185
TrySetValue
................................................................................................................ 4186
CSortedSet < >
.........................................................................................................................
T 4187
Add ................................................................................................................ 4189
Count ................................................................................................................ 4190
Contains ................................................................................................................ 4191
Comparer ................................................................................................................ 4192
G
Try etMin ................................................................................................................ 4193
G
Try etMax................................................................................................................ 4194
CopyTo ................................................................................................................ 4195
Clear ................................................................................................................ 4196
Remove ................................................................................................................ 4197
ExceptWith
................................................................................................................ 4198
I ntersectWith
................................................................................................................ 4199
SymmetricExceptWith
................................................................................................................ 4200
UnionWith ................................................................................................................ 4201
I sProperSubsetOf
................................................................................................................ 4202
I sProperSupersetOf
................................................................................................................ 4203
I sSubsetOf................................................................................................................ 4204
I sSupersetOf
................................................................................................................ 4205
Overlaps ................................................................................................................ 4206
q
SetE uals ................................................................................................................ 4207
GetViewBetween................................................................................................................ 4208
GetReverse................................................................................................................ 4209
CStack <.........................................................................................................................
T> 4210
Add ................................................................................................................ 4211
Count ................................................................................................................ 4212
Contains ................................................................................................................ 4213
TrimExcess................................................................................................................ 4214
CopyTo ................................................................................................................ 4215
Clear ................................................................................................................ 4216
Remove ................................................................................................................ 4217
Push ................................................................................................................ 4218
Peek ................................................................................................................ 4219
Pop ................................................................................................................ 4220
ArrayBinarySearch < >
.........................................................................................................................
T 4221
ArrayI ndexOf < >
.........................................................................................................................
T 4222
ArrayLastI < >
.........................................................................................................................
ndexOf T 4223
ArrayReverse < >
.........................................................................................................................
T 4224
Compare
......................................................................................................................... 4225
q < >
E uals T
......................................................................................................................... 4228
GetHashCode
......................................................................................................................... 4229
Files ............................................................................................................................4232
CFile ......................................................................................................................... 4233
Handle ................................................................................................................ 4235
Filename ................................................................................................................ 4236
Flags ................................................................................................................ 4237
SetUnicode................................................................................................................ 4238
SetCommon................................................................................................................ 4239
Open ................................................................................................................ 4240
Close ................................................................................................................ 4241
Delete ................................................................................................................ 4242
I sExist ................................................................................................................ 4243
Copy ................................................................................................................ 4244

© 2000-2025, MetaQuotes Ltd.


35 Content

Move ................................................................................................................ 4245


z
Si e ................................................................................................................ 4246
Tell ................................................................................................................ 4247
Seek ................................................................................................................ 4248
Flush ................................................................................................................ 4249
I sEnding ................................................................................................................ 4250
I sLineEnding
................................................................................................................ 4251
FolderCreate
................................................................................................................ 4252
FolderDelete
................................................................................................................ 4253
FolderClean................................................................................................................ 4254
FileFindFirst
................................................................................................................ 4255
FileFindNext
................................................................................................................ 4256
FileFindClose
................................................................................................................ 4257
CFileBin......................................................................................................................... 4258
Open ................................................................................................................ 4260
WriteChar ................................................................................................................ 4261
WriteShort................................................................................................................ 4262
WriteI nteger
................................................................................................................ 4263
WriteLong ................................................................................................................ 4264
WriteFloat ................................................................................................................ 4265
WriteDouble
................................................................................................................ 4266
WriteString
................................................................................................................ 4267
WriteCharArray
................................................................................................................ 4268
WriteShortArray
................................................................................................................ 4269
WriteI ntegerArray
................................................................................................................ 4270
WriteLongArray
................................................................................................................ 4271
WriteFloatArray
................................................................................................................ 4272
WriteDoubleArray
................................................................................................................ 4273
WriteObject
................................................................................................................ 4274
ReadChar ................................................................................................................ 4275
ReadShort ................................................................................................................ 4276
ReadI nteger
................................................................................................................ 4277
ReadLong ................................................................................................................ 4278
ReadFloat ................................................................................................................ 4279
ReadDouble................................................................................................................ 4280
ReadString ................................................................................................................ 4281
ReadCharArray
................................................................................................................ 4282
ReadShortArray
................................................................................................................ 4283
ReadI ntegerArray
................................................................................................................ 4284
ReadLongArray
................................................................................................................ 4285
ReadFloatArray
................................................................................................................ 4286
ReadDoubleArray
................................................................................................................ 4287
ReadObject
................................................................................................................ 4288
CFileTxt......................................................................................................................... 4289
Open ................................................................................................................ 4290
WriteString
................................................................................................................ 4291
ReadString ................................................................................................................ 4292
Strings ............................................................................................................................4293
CString ......................................................................................................................... 4294
Str ................................................................................................................ 4296
Len ................................................................................................................ 4297
Copy ................................................................................................................ 4298
Fill ................................................................................................................ 4299
Assign ................................................................................................................ 4300
Append ................................................................................................................ 4301
I nsert ................................................................................................................ 4302
Compare ................................................................................................................ 4303
CompareNoCase
................................................................................................................ 4304

© 2000-2025, MetaQuotes Ltd.


36 Content

Left ................................................................................................................ 4305


Right ................................................................................................................ 4306
Mid ................................................................................................................ 4307
Trim ................................................................................................................ 4308
TrimLeft ................................................................................................................ 4309
TrimRight ................................................................................................................ 4310
Clear ................................................................................................................ 4311
ToUpper ................................................................................................................ 4312
ToLower ................................................................................................................ 4313
Reverse ................................................................................................................ 4314
Find ................................................................................................................ 4315
FindRev ................................................................................................................ 4316
Remove ................................................................................................................ 4317
Replace ................................................................................................................ 4318
............................................................................................................................4319
Graphic Objects
CChartObject
......................................................................................................................... 4320
ChartI d ................................................................................................................ 4323
Window ................................................................................................................ 4324
Name ................................................................................................................ 4325
NumPoints ................................................................................................................ 4326
Attach ................................................................................................................ 4327
SetPoint ................................................................................................................ 4328
Delete ................................................................................................................ 4329
Detach ................................................................................................................ 4330
ShiftObject................................................................................................................ 4331
ShiftPoint ................................................................................................................ 4332
Time ................................................................................................................ 4333
Price ................................................................................................................ 4335
Color ................................................................................................................ 4337
Style ................................................................................................................ 4338
Width ................................................................................................................ 4339
Background
................................................................................................................ 4340
Selected ................................................................................................................ 4341
Selectable ................................................................................................................ 4342
Description................................................................................................................ 4343
Tooltip ................................................................................................................ 4344
Timeframes................................................................................................................ 4345
Z_Order ................................................................................................................ 4346
CreateTime................................................................................................................ 4347
LevelsCount
................................................................................................................ 4348
LevelColor ................................................................................................................ 4349
LevelStyle ................................................................................................................ 4351
LevelWidth................................................................................................................ 4353
LevelValue ................................................................................................................ 4355
LevelDescription
................................................................................................................ 4357
GetI nteger................................................................................................................ 4359
SetI nteger ................................................................................................................ 4361
GetDouble ................................................................................................................ 4363
SetDouble ................................................................................................................ 4365
GetString ................................................................................................................ 4367
SetString ................................................................................................................ 4369
Save ................................................................................................................ 4371
Load ................................................................................................................ 4372
Type ................................................................................................................ 4373
Line Objects
......................................................................................................................... 4374
CChartObjectVLine
................................................................................................................ 4375
Create ........................................................................................................... 4376
Type ........................................................................................................... 4377

© 2000-2025, MetaQuotes Ltd.


37 Content

CChartObjectHLine
................................................................................................................ 4378
Create ........................................................................................................... 4379
Type ........................................................................................................... 4380
CChartObjectTrend
................................................................................................................ 4381
Create ........................................................................................................... 4383
RayLeft ........................................................................................................... 4384
RayRight ........................................................................................................... 4385
Save ........................................................................................................... 4386
Load ........................................................................................................... 4387
Type ........................................................................................................... 4388
CChartObjectTrendByAngle
................................................................................................................ 4389
Create ........................................................................................................... 4391
Angle ........................................................................................................... 4392
Type ........................................................................................................... 4393
CChartObjectCycles
................................................................................................................ 4394
Create ........................................................................................................... 4395
Type ........................................................................................................... 4396
Channel.........................................................................................................................
Objects 4397
CChartObjectChannel
................................................................................................................ 4398
Create ........................................................................................................... 4400
Type ........................................................................................................... 4401
CChartObjectRegression
................................................................................................................ 4402
Create ........................................................................................................... 4404
Type ........................................................................................................... 4405
CChartObjectStdDevChannel
................................................................................................................ 4406
Create ........................................................................................................... 4408
Deviations ........................................................................................................... 4409
Save ........................................................................................................... 4410
Load ........................................................................................................... 4411
Type ........................................................................................................... 4412
CChartObjectPitchfork
................................................................................................................ 4413
Create ........................................................................................................... 4415
Type ........................................................................................................... 4416
Gann Tools
......................................................................................................................... 4417
CChartObject GannLine
................................................................................................................ 4418
Create ........................................................................................................... 4420
PipsPerBar........................................................................................................... 4421
Save ........................................................................................................... 4422
Load ........................................................................................................... 4423
Type ........................................................................................................... 4424
CChartObject G
................................................................................................................
annFan 4425
Create ........................................................................................................... 4427
PipsPerBar........................................................................................................... 4428
Downtrend........................................................................................................... 4429
Save ........................................................................................................... 4430
Load ........................................................................................................... 4431
Type ........................................................................................................... 4432
CChartObject G G
................................................................................................................
ann rid 4433
Create ........................................................................................................... 4435
PipsPerBar........................................................................................................... 4436
Downtrend........................................................................................................... 4437
Save ........................................................................................................... 4438
Load ........................................................................................................... 4439
Type ........................................................................................................... 4440
Fibonacci
.........................................................................................................................
Tools 4441
CChartObjectFibo
................................................................................................................ 4442
Create ........................................................................................................... 4444
Type ........................................................................................................... 4445

© 2000-2025, MetaQuotes Ltd.


38 Content

CChartObjectFiboTimes
................................................................................................................ 4446
Create ........................................................................................................... 4447
Type ........................................................................................................... 4448
CChartObjectFiboFan
................................................................................................................ 4449
Create ........................................................................................................... 4450
Type ........................................................................................................... 4451
CChartObjectFiboArc
................................................................................................................ 4452
Create ........................................................................................................... 4454
Scale ........................................................................................................... 4455
Ellipse ........................................................................................................... 4456
Save ........................................................................................................... 4457
Load ........................................................................................................... 4458
Type ........................................................................................................... 4459
CChartObjectFiboChannel
................................................................................................................ 4460
Create ........................................................................................................... 4462
Type ........................................................................................................... 4463
CChartObjectFiboExpansion
................................................................................................................ 4464
Create ........................................................................................................... 4466
Type ........................................................................................................... 4467
Elliott Tools
......................................................................................................................... 4468
CChartObjectElliottWave3
................................................................................................................ 4469
Create ........................................................................................................... 4471
Degree ........................................................................................................... 4472
Lines ........................................................................................................... 4473
Save ........................................................................................................... 4474
Load ........................................................................................................... 4475
Type ........................................................................................................... 4476
CChartObjectElliottWave5
................................................................................................................ 4477
Create ........................................................................................................... 4479
Type ........................................................................................................... 4481
Shape Objects
......................................................................................................................... 4482
CChartObjectRectangle
................................................................................................................ 4483
Create ........................................................................................................... 4484
Type ........................................................................................................... 4485
CChartObjectTriangle
................................................................................................................ 4486
Create ........................................................................................................... 4487
Type ........................................................................................................... 4488
CChartObjectEllipse
................................................................................................................ 4489
Create ........................................................................................................... 4490
Type ........................................................................................................... 4491
Arrow Objects
......................................................................................................................... 4492
CChartObjectArrow
................................................................................................................ 4493
Create ........................................................................................................... 4495
ArrowCode........................................................................................................... 4497
Anchor ........................................................................................................... 4499
Save ........................................................................................................... 4501
Load ........................................................................................................... 4502
Type ........................................................................................................... 4503
Arrows with
................................................................................................................
fixed code 4504
Create ........................................................................................................... 4506
ArrowCode........................................................................................................... 4508
Type ........................................................................................................... 4509
Control.........................................................................................................................
Objects 4510
CChartObjectText
................................................................................................................ 4511
Create ........................................................................................................... 4513
Angle ........................................................................................................... 4514
Font ........................................................................................................... 4515
FontSi e z ........................................................................................................... 4516

© 2000-2025, MetaQuotes Ltd.


39 Content

Anchor ........................................................................................................... 4517


Save ........................................................................................................... 4518
Load ........................................................................................................... 4519
Type ........................................................................................................... 4520
CChartObjectLabel
................................................................................................................ 4521
Create ........................................................................................................... 4523
X_Distance........................................................................................................... 4524
Y_Distance........................................................................................................... 4525
X_Siz e ........................................................................................................... 4526
Y_Siz e ........................................................................................................... 4527
Corner ........................................................................................................... 4528
Time ........................................................................................................... 4529
Price ........................................................................................................... 4530
Save ........................................................................................................... 4531
Load ........................................................................................................... 4532
Type ........................................................................................................... 4533
CChartObjectEdit
................................................................................................................ 4534
Create ........................................................................................................... 4536
TextAlign ........................................................................................................... 4537
X_Siz e ........................................................................................................... 4538
Y_Siz e ........................................................................................................... 4539
BackColor ........................................................................................................... 4540
BorderColor
........................................................................................................... 4541
ReadOnly ........................................................................................................... 4542
Angle ........................................................................................................... 4543
Save ........................................................................................................... 4544
Load ........................................................................................................... 4545
Type ........................................................................................................... 4546
CChartObjectButton
................................................................................................................ 4547
State ........................................................................................................... 4549
Save ........................................................................................................... 4550
Load ........................................................................................................... 4551
Type ........................................................................................................... 4552
CChartObjectSubChart
................................................................................................................ 4553
Create ........................................................................................................... 4555
X_Distance........................................................................................................... 4556
Y_Distance........................................................................................................... 4557
Corner ........................................................................................................... 4558
X_Siz e ........................................................................................................... 4559
Y_Siz e ........................................................................................................... 4560
Symbol ........................................................................................................... 4561
Period ........................................................................................................... 4562
Scale ........................................................................................................... 4563
DateScale ........................................................................................................... 4564
PriceScale ........................................................................................................... 4565
Time ........................................................................................................... 4566
Price ........................................................................................................... 4567
Save ........................................................................................................... 4568
Load ........................................................................................................... 4569
Type ........................................................................................................... 4570
CChartObjectBitmap
................................................................................................................ 4571
Create ........................................................................................................... 4573
BmpFile ........................................................................................................... 4574
X_Offset ........................................................................................................... 4575
Y_Offset ........................................................................................................... 4576
Save ........................................................................................................... 4577
Load ........................................................................................................... 4578
Type ........................................................................................................... 4579

© 2000-2025, MetaQuotes Ltd.


40 Content

CChartObjectBmpLabel
................................................................................................................ 4580
Create ........................................................................................................... 4582
X_Distance........................................................................................................... 4583
Y_Distance........................................................................................................... 4584
X_Offset ........................................................................................................... 4585
Y_Offset ........................................................................................................... 4586
Corner ........................................................................................................... 4587
X_Siz e ........................................................................................................... 4588
Y_Siz e ........................................................................................................... 4589
BmpFileOn ........................................................................................................... 4590
BmpFileOff........................................................................................................... 4591
State ........................................................................................................... 4592
Time ........................................................................................................... 4593
Price ........................................................................................................... 4594
Save ........................................................................................................... 4595
Load ........................................................................................................... 4596
Type ........................................................................................................... 4597
CChartObjectRectLabel
................................................................................................................ 4598
Create ........................................................................................................... 4600
X_Siz e ........................................................................................................... 4601
Y_Siz e ........................................................................................................... 4602
BackColor ........................................................................................................... 4603
Angle ........................................................................................................... 4604
BorderType
........................................................................................................... 4605
Save ........................................................................................................... 4606
Load ........................................................................................................... 4607
Type ........................................................................................................... 4608
............................................................................................................................4609
Custom Graphics
CCanvas
......................................................................................................................... 4610
Attach ................................................................................................................ 4614
Arc ................................................................................................................ 4615
Pie ................................................................................................................ 4619
FillPolygon ................................................................................................................ 4623
FillEllipse ................................................................................................................ 4624
GetDefaultColor
................................................................................................................ 4625
ChartObjectName
................................................................................................................ 4626
Circle ................................................................................................................ 4627
CircleAA ................................................................................................................ 4628
CircleWu ................................................................................................................ 4629
Create ................................................................................................................ 4630
CreateBitmap
................................................................................................................ 4631
CreateBitmapLabel
................................................................................................................ 4633
Destroy ................................................................................................................ 4635
Ellipse ................................................................................................................ 4636
EllipseAA ................................................................................................................ 4637
EllipseWu ................................................................................................................ 4638
Erase ................................................................................................................ 4639
Fill ................................................................................................................ 4640
FillCircle ................................................................................................................ 4641
FillRectangle
................................................................................................................ 4642
FillTriangle ................................................................................................................ 4643
et G
FontAngle ................................................................................................................ 4644
FontAngleSet
................................................................................................................ 4645
et G
FontFlags ................................................................................................................ 4646
FontFlagsSet
................................................................................................................ 4647
Font etG ................................................................................................................ 4648
et G
FontName ................................................................................................................ 4649
FontNameSet
................................................................................................................ 4650

© 2000-2025, MetaQuotes Ltd.


41 Content

FontSet ................................................................................................................ 4651


z G
FontSi e et
................................................................................................................ 4652
FontSiz eSet
................................................................................................................ 4653
Height ................................................................................................................ 4654
Line ................................................................................................................ 4655
LineAA ................................................................................................................ 4656
LineWu ................................................................................................................ 4657
LineHori ontal z
................................................................................................................ 4658
LineVertical
................................................................................................................ 4659
LineStyleSet
................................................................................................................ 4660
LineThick ................................................................................................................ 4661
LineThickVertical
................................................................................................................ 4662
LineThickHori z
................................................................................................................
ontal 4663
LoadFromFile
................................................................................................................ 4664
G
Pixel et ................................................................................................................ 4665
PixelSet ................................................................................................................ 4666
PixelSetAA ................................................................................................................ 4667
Polygon ................................................................................................................ 4668
PolygonAA ................................................................................................................ 4669
PolygonWu................................................................................................................ 4670
PolygonThick
................................................................................................................ 4671
PolygonSmooth
................................................................................................................ 4672
Polyline ................................................................................................................ 4673
PolylineSmooth
................................................................................................................ 4674
PolylineThick
................................................................................................................ 4675
PolylineWu ................................................................................................................ 4676
PolylineAA ................................................................................................................ 4677
Rectangle ................................................................................................................ 4678
z
Resi e ................................................................................................................ 4679
ResourceName
................................................................................................................ 4680
TextHeight................................................................................................................ 4681
TextOut ................................................................................................................ 4682
TextSi e z ................................................................................................................ 4683
TextWidth ................................................................................................................ 4684
TransparentLevelSet
................................................................................................................ 4685
Triangle ................................................................................................................ 4686
TriangleAA ................................................................................................................ 4687
TriangleWu................................................................................................................ 4688
Update ................................................................................................................ 4689
Width ................................................................................................................ 4690
CChartCanvas
......................................................................................................................... 4691
ColorBackground
................................................................................................................ 4695
ColorBorder
................................................................................................................ 4696
ColorText ................................................................................................................ 4697
G
Color rid ................................................................................................................ 4698
MaxData ................................................................................................................ 4699
MaxDescrLen
................................................................................................................ 4700
ShowFlags ................................................................................................................ 4701
I sShowLegend
................................................................................................................ 4702
I sShowScaleLeft
................................................................................................................ 4703
I sShowScaleRight
................................................................................................................ 4704
I sShowScaleTop
................................................................................................................ 4705
I sShowScaleBottom
................................................................................................................ 4706
G
I sShow rid................................................................................................................ 4707
I sShowDescriptors
................................................................................................................ 4708
I sShowPercent
................................................................................................................ 4709
VScaleMin ................................................................................................................ 4710
VScaleMax ................................................................................................................ 4711

© 2000-2025, MetaQuotes Ltd.


42 Content

G
Num rid ................................................................................................................ 4712
DataOffset................................................................................................................ 4713
DataTotal ................................................................................................................ 4714
DrawDescriptors
................................................................................................................ 4715
DrawData ................................................................................................................ 4716
Create ................................................................................................................ 4717
AllowedShowFlags
................................................................................................................ 4718
ShowLegend
................................................................................................................ 4719
ShowScaleLeft
................................................................................................................ 4720
ShowScaleRight
................................................................................................................ 4721
ShowScaleTop
................................................................................................................ 4722
ShowScaleBottom
................................................................................................................ 4723
G
Show rid ................................................................................................................ 4724
ShowDescriptors
................................................................................................................ 4725
ShowValue ................................................................................................................ 4726
ShowPercent
................................................................................................................ 4727
LegendAlignment
................................................................................................................ 4728
Accumulative
................................................................................................................ 4729
VScaleParams
................................................................................................................ 4730
DescriptorUpdate
................................................................................................................ 4731
ColorUpdate
................................................................................................................ 4732
ValuesCheck
................................................................................................................ 4733
Redraw ................................................................................................................ 4734
DrawBackground
................................................................................................................ 4735
DrawLegend
................................................................................................................ 4736
DrawLegendVertical
................................................................................................................ 4737
DrawLegendHori z
................................................................................................................
ontal 4738
CalcScales ................................................................................................................ 4739
DrawScales................................................................................................................ 4740
DrawScaleLeft
................................................................................................................ 4741
DrawScaleRight
................................................................................................................ 4742
DrawScaleTop
................................................................................................................ 4743
DrawScaleBottom
................................................................................................................ 4744
G
Draw rid ................................................................................................................ 4745
DrawChart................................................................................................................ 4746
CHistogramChart
......................................................................................................................... 4747
Gradient ................................................................................................................ 4752
Bar Gap ................................................................................................................ 4753
BarMinSiz e................................................................................................................ 4754
BarBorder ................................................................................................................ 4755
Create ................................................................................................................ 4756
SeriesAdd ................................................................................................................ 4757
SeriesI nsert
................................................................................................................ 4758
SeriesUpdate
................................................................................................................ 4759
SeriesDelete
................................................................................................................ 4760
ValueUpdate
................................................................................................................ 4761
DrawData ................................................................................................................ 4762
DrawBar ................................................................................................................ 4763
GradientBrush
................................................................................................................ 4764
CLineChart
......................................................................................................................... 4765
Filled ................................................................................................................ 4769
Create ................................................................................................................ 4770
SeriesAdd ................................................................................................................ 4771
SeriesI nsert
................................................................................................................ 4772
SeriesUpdate
................................................................................................................ 4773
SeriesDelete
................................................................................................................ 4774
ValueUpdate
................................................................................................................ 4775
DrawChart................................................................................................................ 4776

© 2000-2025, MetaQuotes Ltd.


43 Content

DrawData ................................................................................................................ 4777


CalcArea ................................................................................................................ 4778
CPieChart
......................................................................................................................... 4779
Create ................................................................................................................ 4783
SeriesSet ................................................................................................................ 4784
ValueAdd ................................................................................................................ 4785
ValueI nsert................................................................................................................ 4786
ValueUpdate
................................................................................................................ 4787
ValueDelete
................................................................................................................ 4788
DrawChart................................................................................................................ 4789
DrawPie ................................................................................................................ 4790
LabelMake ................................................................................................................ 4791
............................................................................................................................4792
3D Graphics
CCanvas3D
......................................................................................................................... 4793
AmbientColor G
................................................................................................................
et 4795
AmbientColorSet
................................................................................................................ 4796
Attach ................................................................................................................ 4797
Create ................................................................................................................ 4798
Destroy ................................................................................................................ 4799
X
D Context................................................................................................................ 4800
D X Dispatcher
................................................................................................................ 4801
I nputScene................................................................................................................ 4802
et G
LightColor ................................................................................................................ 4803
LightColorSet
................................................................................................................ 4804
LightDirection G
................................................................................................................
et 4805
LightDirectionSet
................................................................................................................ 4806
ObjectAdd ................................................................................................................ 4807
ProjectionMatrix G
................................................................................................................
et 4808
ProjectionMatrixSet
................................................................................................................ 4809
Render ................................................................................................................ 4810
RenderBegin
................................................................................................................ 4811
RenderEnd ................................................................................................................ 4812
et G
ViewMatrix................................................................................................................ 4813
ViewMatrixSet
................................................................................................................ 4814
ViewPositionSet
................................................................................................................ 4815
ViewRotationSet
................................................................................................................ 4816
ViewTargetSet
................................................................................................................ 4817
ViewUpDirectionSet
................................................................................................................ 4818
............................................................................................................................4819
Price Charts
ChartI D......................................................................................................................... 4824
Mode ......................................................................................................................... 4825
Foreground
......................................................................................................................... 4826
Shift ......................................................................................................................... 4827
z
ShiftSi e
......................................................................................................................... 4828
AutoScroll
......................................................................................................................... 4829
Scale ......................................................................................................................... 4830
ScaleFix......................................................................................................................... 4831
11_
ScaleFix......................................................................................................................... 4832
FixedMax
......................................................................................................................... 4833
FixedMin
......................................................................................................................... 4834
PointsPerBar
......................................................................................................................... 4835
ScalePPB
......................................................................................................................... 4836
ShowOHLC
......................................................................................................................... 4837
ShowLineBid
......................................................................................................................... 4838
ShowLineAsk
......................................................................................................................... 4839
ShowLastLine
......................................................................................................................... 4840
ShowPeriodSep
......................................................................................................................... 4841
Show ridG
......................................................................................................................... 4842

© 2000-2025, MetaQuotes Ltd.


44 Content

ShowVolumes
......................................................................................................................... 4843
ShowObjectDescr
......................................................................................................................... 4844
ShowDateScale
......................................................................................................................... 4845
ShowPriceScale
......................................................................................................................... 4846
ColorBackground
......................................................................................................................... 4847
ColorForeground
......................................................................................................................... 4848
G
Color rid
......................................................................................................................... 4849
ColorBarUp
......................................................................................................................... 4850
ColorBarDown
......................................................................................................................... 4851
ColorCandleBull
......................................................................................................................... 4852
ColorCandleBear
......................................................................................................................... 4853
ColorChartLine
......................................................................................................................... 4854
ColorVolumes
......................................................................................................................... 4855
ColorLineBid
......................................................................................................................... 4856
ColorLineAsk
......................................................................................................................... 4857
ColorLineLast
......................................................................................................................... 4858
ColorStopLevels
......................................................................................................................... 4859
VisibleBars
......................................................................................................................... 4860
WindowsTotal
......................................................................................................................... 4861
WindowI
.........................................................................................................................
sVisible 4862
WindowHandle
......................................................................................................................... 4863
FirstVisibleBar
......................................................................................................................... 4864
WidthI nBars
......................................................................................................................... 4865
WidthI nPixels
......................................................................................................................... 4866
HeightI nPixels
......................................................................................................................... 4867
PriceMin
......................................................................................................................... 4868
PriceMax
......................................................................................................................... 4869
Attach ......................................................................................................................... 4870
FirstChart
......................................................................................................................... 4871
NextChart
......................................................................................................................... 4872
Open ......................................................................................................................... 4873
Detach ......................................................................................................................... 4874
Close ......................................................................................................................... 4875
BringToTop
......................................................................................................................... 4876
EventObjectCreate
......................................................................................................................... 4877
EventObjectDelete
......................................................................................................................... 4878
I ndicatorAdd
......................................................................................................................... 4879
I ndicatorDelete
......................................................................................................................... 4880
I ndicatorsTotal
......................................................................................................................... 4881
I ndicatorName
......................................................................................................................... 4882
Navigate
......................................................................................................................... 4883
Symbol ......................................................................................................................... 4884
Period ......................................................................................................................... 4885
Redraw......................................................................................................................... 4886
GetI nteger
......................................................................................................................... 4887
SetI nteger
......................................................................................................................... 4888
GetDouble
......................................................................................................................... 4889
SetDouble
......................................................................................................................... 4890
GetString
......................................................................................................................... 4891
SetString
......................................................................................................................... 4892
SetSymbolPeriod
......................................................................................................................... 4893
ApplyTemplate
......................................................................................................................... 4894
ScreenShot
......................................................................................................................... 4895
WindowOnDropped
......................................................................................................................... 4896
PriceOnDropped
......................................................................................................................... 4897
TimeOnDropped
......................................................................................................................... 4898
X OnDropped
......................................................................................................................... 4899
Y OnDropped
......................................................................................................................... 4900

© 2000-2025, MetaQuotes Ltd.


45 Content

Save ......................................................................................................................... 4901


Load ......................................................................................................................... 4902
Type ......................................................................................................................... 4903
Scientific ............................................................................................................................4904
Charts
GraphPlot
......................................................................................................................... 4905
CAxis ......................................................................................................................... 4909
AutoScale ................................................................................................................ 4911
Min ................................................................................................................ 4912
Max ................................................................................................................ 4913
Step ................................................................................................................ 4914
Name ................................................................................................................ 4915
Color ................................................................................................................ 4916
z
ValuesSi e ................................................................................................................ 4917
ValuesWidth
................................................................................................................ 4918
ValuesFormat
................................................................................................................ 4919
ValuesDateTimeMode
................................................................................................................ 4920
ValuesFunctionFormat
................................................................................................................ 4921
ValuesFunctionFormatCBData
................................................................................................................ 4923
z
NameSi e ................................................................................................................ 4924
ZeroLever ................................................................................................................ 4925
DefaultStep
................................................................................................................ 4926
MaxLabels ................................................................................................................ 4927
G
Min race ................................................................................................................ 4928
G
Max race ................................................................................................................ 4929
SelectAxisScale
................................................................................................................ 4930
G
CColor .........................................................................................................................
enerator 4931
Next ................................................................................................................ 4932
Reset ................................................................................................................ 4933
CCurve......................................................................................................................... 4934
Type ................................................................................................................ 4936
Name ................................................................................................................ 4937
Color ................................................................................................................ 4938
X Max ................................................................................................................ 4939
X Min ................................................................................................................ 4940
Y Max ................................................................................................................ 4941
Y Min ................................................................................................................ 4942
Siz e ................................................................................................................ 4943
z
PointsSi e ................................................................................................................ 4944
PointsFill ................................................................................................................ 4945
PointsColor................................................................................................................ 4946
Get X ................................................................................................................ 4947
Get Y ................................................................................................................ 4948
LinesStyle ................................................................................................................ 4949
LinesI sSmooth
................................................................................................................ 4950
LinesSmoothTension
................................................................................................................ 4951
LinesSmoothStep
................................................................................................................ 4952
LinesEndStyle
................................................................................................................ 4953
LinesWidth................................................................................................................ 4954
HistogramWidth
................................................................................................................ 4956
CustomPlotCBData
................................................................................................................ 4957
CustomPlotFunction
................................................................................................................ 4958
PointsType................................................................................................................ 4962
StepsDimension
................................................................................................................ 4963
TrendLineCoefficients
................................................................................................................ 4964
TrendLineColor
................................................................................................................ 4965
TrendLineVisible
................................................................................................................ 4966
Update ................................................................................................................ 4968
Visible ................................................................................................................ 4970

© 2000-2025, MetaQuotes Ltd.


46 Content

G
C raphic
......................................................................................................................... 4971
Create ................................................................................................................ 4974
Destroy ................................................................................................................ 4975
Update ................................................................................................................ 4976
ChartObjectName
................................................................................................................ 4977
ResourceName
................................................................................................................ 4978
X Axis ................................................................................................................ 4979
Y Axis ................................................................................................................ 4980
GapSiz e ................................................................................................................ 4981
BackgroundColor
................................................................................................................ 4982
BackgroundMain
................................................................................................................ 4983
BackgroundMainSi z
................................................................................................................
e 4984
BackgroundMainColor
................................................................................................................ 4985
BackgroundSub
................................................................................................................ 4986
BackgroundSubSi z
................................................................................................................
e 4987
BackgroundSubColor
................................................................................................................ 4988
GridLineColor
................................................................................................................ 4989
GridBackgroundColor
................................................................................................................ 4990
GridCircleRadius
................................................................................................................ 4991
GridCircleColor
................................................................................................................ 4992
GridHasCircle
................................................................................................................ 4993
GridAxisLineColor
................................................................................................................ 4994
HistoryNameWidth
................................................................................................................ 4995
HistoryNameSi z
................................................................................................................
e 4996
HistorySymbolSi z
................................................................................................................
e 4997
TextAdd ................................................................................................................ 4998
LineAdd ................................................................................................................ 4999
CurveAdd ................................................................................................................ 5000
CurvePlot ................................................................................................................ 5003
CurvePlotAll
................................................................................................................ 5004
G
Curve etByI
................................................................................................................
ndex 5005
G
Curve etByName
................................................................................................................ 5006
CurveRemoveByI
................................................................................................................
ndex 5007
CurveRemoveByName
................................................................................................................ 5008
CurvesTotal
................................................................................................................ 5009
MarksToAxisAdd
................................................................................................................ 5010
MajorMarkSi z
................................................................................................................
e 5011
FontSet ................................................................................................................ 5012
G
Font et ................................................................................................................ 5013
Attach ................................................................................................................ 5014
CalculateMaxMinValues
................................................................................................................ 5015
Height ................................................................................................................ 5016
I ndentDown
................................................................................................................ 5017
I ndentLeft ................................................................................................................ 5018
I ndentRight
................................................................................................................ 5019
I ndentUp ................................................................................................................ 5020
Redraw ................................................................................................................ 5021
ResetParameters
................................................................................................................ 5022
Scale X ................................................................................................................ 5023
Scale Y ................................................................................................................ 5024
SetDefaultParameters
................................................................................................................ 5025
Width ................................................................................................................ 5026
Indicators............................................................................................................................5027
Base classes
......................................................................................................................... 5028
CSpreadBuffer
................................................................................................................ 5029
z
Si e ........................................................................................................... 5031
SetSymbolPeriod
........................................................................................................... 5032
At ........................................................................................................... 5033

© 2000-2025, MetaQuotes Ltd.


47 Content

Refresh ........................................................................................................... 5034


RefreshCurrent
........................................................................................................... 5035
CTimeBuffer
................................................................................................................ 5036
z
Si e ........................................................................................................... 5038
SetSymbolPeriod
........................................................................................................... 5039
At ........................................................................................................... 5040
Refresh ........................................................................................................... 5041
RefreshCurrent
........................................................................................................... 5042
CTickVolumeBuffer
................................................................................................................ 5043
z
Si e ........................................................................................................... 5045
SetSymbolPeriod
........................................................................................................... 5046
At ........................................................................................................... 5047
Refresh ........................................................................................................... 5048
RefreshCurrent
........................................................................................................... 5049
CRealVolumeBuffer
................................................................................................................ 5050
z
Si e ........................................................................................................... 5052
SetSymbolPeriod
........................................................................................................... 5053
At ........................................................................................................... 5054
Refresh ........................................................................................................... 5055
RefreshCurrent
........................................................................................................... 5056
CDoubleBuffer
................................................................................................................ 5057
z
Si e ........................................................................................................... 5059
SetSymbolPeriod
........................................................................................................... 5060
At ........................................................................................................... 5061
Refresh ........................................................................................................... 5062
RefreshCurrent
........................................................................................................... 5063
COpenBuffer
................................................................................................................ 5064
Refresh ........................................................................................................... 5065
RefreshCurrent
........................................................................................................... 5066
CHighBuffer
................................................................................................................ 5067
Refresh ........................................................................................................... 5068
RefreshCurrent
........................................................................................................... 5069
CLowBuffer................................................................................................................ 5070
Refresh ........................................................................................................... 5071
RefreshCurrent
........................................................................................................... 5072
CCloseBuffer
................................................................................................................ 5073
Refresh ........................................................................................................... 5074
RefreshCurrent
........................................................................................................... 5075
CI ndicatorBuffer
................................................................................................................ 5076
Offset ........................................................................................................... 5078
Name ........................................................................................................... 5079
At ........................................................................................................... 5080
Refresh ........................................................................................................... 5081
RefreshCurrent
........................................................................................................... 5082
CSeries ................................................................................................................ 5083
Name ........................................................................................................... 5085
BuffersTotal
........................................................................................................... 5086
Timeframe ........................................................................................................... 5087
Symbol ........................................................................................................... 5088
Period ........................................................................................................... 5089
RefreshCurrent
........................................................................................................... 5090
z
BufferSi e ........................................................................................................... 5091
e z
BufferResi ........................................................................................................... 5092
Refresh ........................................................................................................... 5093
PeriodDescription
........................................................................................................... 5094
CPriceSeries
................................................................................................................ 5095
e z
BufferResi ........................................................................................................... 5097
GetData ........................................................................................................... 5098

© 2000-2025, MetaQuotes Ltd.


48 Content

Refresh ........................................................................................................... 5099


MinI ndex ........................................................................................................... 5100
MinValue ........................................................................................................... 5101
MaxI ndex ........................................................................................................... 5102
MaxValue ........................................................................................................... 5103
CI ndicator ................................................................................................................ 5104
Handle ........................................................................................................... 5106
Status ........................................................................................................... 5107
FullRelease........................................................................................................... 5108
Create ........................................................................................................... 5109
ez
BufferResi ........................................................................................................... 5110
BarsCalculated
........................................................................................................... 5111
GetData ........................................................................................................... 5112
Refresh ........................................................................................................... 5115
Minimum ........................................................................................................... 5116
MinValue ........................................................................................................... 5117
Maximum ........................................................................................................... 5118
MaxValue ........................................................................................................... 5119
MethodDescription
........................................................................................................... 5120
PriceDescription
........................................................................................................... 5121
VolumeDescription
........................................................................................................... 5122
AddToChart
........................................................................................................... 5123
DeleteFromChart
........................................................................................................... 5124
CI ndicators
................................................................................................................ 5125
Create ........................................................................................................... 5126
Refresh ........................................................................................................... 5127
Timeseries
.........................................................................................................................
classes 5128
CiSpread ................................................................................................................ 5129
Create ........................................................................................................... 5131
ez
BufferResi ........................................................................................................... 5132
GetData ........................................................................................................... 5133
Refresh ........................................................................................................... 5135
CiTime ................................................................................................................ 5136
Create ........................................................................................................... 5138
ez
BufferResi ........................................................................................................... 5139
GetData ........................................................................................................... 5140
Refresh ........................................................................................................... 5142
CiTickVolume
................................................................................................................ 5143
Create ........................................................................................................... 5145
ez
BufferResi ........................................................................................................... 5146
GetData ........................................................................................................... 5147
Refresh ........................................................................................................... 5149
CiRealVolume
................................................................................................................ 5150
Create ........................................................................................................... 5152
ez
BufferResi ........................................................................................................... 5153
GetData ........................................................................................................... 5154
Refresh ........................................................................................................... 5156
CiOpen ................................................................................................................ 5157
Create ........................................................................................................... 5159
GetData ........................................................................................................... 5160
CiHigh ................................................................................................................ 5162
Create ........................................................................................................... 5164
GetData ........................................................................................................... 5165
CiLow ................................................................................................................ 5167
Create ........................................................................................................... 5169
GetData ........................................................................................................... 5170
CiClose ................................................................................................................ 5172
Create ........................................................................................................... 5174

© 2000-2025, MetaQuotes Ltd.


49 Content

GetData ........................................................................................................... 5175


Trend I ndicators
......................................................................................................................... 5177
CiAD X ................................................................................................................ 5178
MaPeriod ........................................................................................................... 5180
Create ........................................................................................................... 5181
Main ........................................................................................................... 5182
Plus ........................................................................................................... 5183
Minus ........................................................................................................... 5184
Type ........................................................................................................... 5185
X
CiAD Wilder
................................................................................................................ 5186
MaPeriod ........................................................................................................... 5188
Create ........................................................................................................... 5189
Main ........................................................................................................... 5190
Plus ........................................................................................................... 5191
Minus ........................................................................................................... 5192
Type ........................................................................................................... 5193
CiBands ................................................................................................................ 5194
MaPeriod ........................................................................................................... 5196
MaShift ........................................................................................................... 5197
Deviation ........................................................................................................... 5198
Applied ........................................................................................................... 5199
Create ........................................................................................................... 5200
Base ........................................................................................................... 5201
Upper ........................................................................................................... 5202
Lower ........................................................................................................... 5203
Type ........................................................................................................... 5204
CiEnvelopes
................................................................................................................ 5205
MaPeriod ........................................................................................................... 5207
MaShift ........................................................................................................... 5208
MaMethod ........................................................................................................... 5209
Deviation ........................................................................................................... 5210
Applied ........................................................................................................... 5211
Create ........................................................................................................... 5212
Upper ........................................................................................................... 5213
Lower ........................................................................................................... 5214
Type ........................................................................................................... 5215
CiI chimoku................................................................................................................ 5216
TenkanSenPeriod
........................................................................................................... 5218
KijunSenPeriod
........................................................................................................... 5219
SenkouSpanBPeriod
........................................................................................................... 5220
Create ........................................................................................................... 5221
TenkanSen........................................................................................................... 5222
KijunSen ........................................................................................................... 5223
SenkouSpanA
........................................................................................................... 5224
SenkouSpanB
........................................................................................................... 5225
ChinkouSpan
........................................................................................................... 5226
Type ........................................................................................................... 5227
CiMA ................................................................................................................ 5228
MaPeriod ........................................................................................................... 5230
MaShift ........................................................................................................... 5231
MaMethod ........................................................................................................... 5232
Applied ........................................................................................................... 5233
Create ........................................................................................................... 5234
Main ........................................................................................................... 5235
Type ........................................................................................................... 5236
CiSAR ................................................................................................................ 5237
SarStep ........................................................................................................... 5239
Maximum ........................................................................................................... 5240

© 2000-2025, MetaQuotes Ltd.


50 Content

Create ........................................................................................................... 5241


Main ........................................................................................................... 5242
Type ........................................................................................................... 5243
CiStdDev ................................................................................................................ 5244
MaPeriod ........................................................................................................... 5246
MaShift ........................................................................................................... 5247
MaMethod ........................................................................................................... 5248
Applied ........................................................................................................... 5249
Create ........................................................................................................... 5250
Main ........................................................................................................... 5251
Type ........................................................................................................... 5252
CiDEMA ................................................................................................................ 5253
MaPeriod ........................................................................................................... 5255
I ndShift ........................................................................................................... 5256
Applied ........................................................................................................... 5257
Create ........................................................................................................... 5258
Main ........................................................................................................... 5259
Type ........................................................................................................... 5260
CiTEMA ................................................................................................................ 5261
MaPeriod ........................................................................................................... 5263
I ndShift ........................................................................................................... 5264
Applied ........................................................................................................... 5265
Create ........................................................................................................... 5266
Main ........................................................................................................... 5267
Type ........................................................................................................... 5268
CiFrAMA ................................................................................................................ 5269
MaPeriod ........................................................................................................... 5271
I ndShift ........................................................................................................... 5272
Applied ........................................................................................................... 5273
Create ........................................................................................................... 5274
Main ........................................................................................................... 5275
Type ........................................................................................................... 5276
CiAMA ................................................................................................................ 5277
MaPeriod ........................................................................................................... 5279
FastEmaPeriod
........................................................................................................... 5280
SlowEmaPeriod
........................................................................................................... 5281
I ndShift ........................................................................................................... 5282
Applied ........................................................................................................... 5283
Create ........................................................................................................... 5284
Main ........................................................................................................... 5285
Type ........................................................................................................... 5286
CiVI DyA ................................................................................................................ 5287
CmoPeriod........................................................................................................... 5289
EmaPeriod ........................................................................................................... 5290
I ndShift ........................................................................................................... 5291
Applied ........................................................................................................... 5292
Create ........................................................................................................... 5293
Main ........................................................................................................... 5294
Type ........................................................................................................... 5295
Oscillators
......................................................................................................................... 5296
CiATR ................................................................................................................ 5297
MaPeriod ........................................................................................................... 5299
Create ........................................................................................................... 5300
Main ........................................................................................................... 5301
Type ........................................................................................................... 5302
CiBearsPower
................................................................................................................ 5303
MaPeriod ........................................................................................................... 5305
Create ........................................................................................................... 5306

© 2000-2025, MetaQuotes Ltd.


51 Content

Main ........................................................................................................... 5307


Type ........................................................................................................... 5308
CiBullsPower
................................................................................................................ 5309
MaPeriod ........................................................................................................... 5311
Create ........................................................................................................... 5312
Main ........................................................................................................... 5313
Type ........................................................................................................... 5314
CiCCI ................................................................................................................ 5315
MaPeriod ........................................................................................................... 5317
Applied ........................................................................................................... 5318
Create ........................................................................................................... 5319
Main ........................................................................................................... 5320
Type ........................................................................................................... 5321
CiChaikin ................................................................................................................ 5322
FastMaPeriod
........................................................................................................... 5324
SlowMaPeriod
........................................................................................................... 5325
MaMethod ........................................................................................................... 5326
Applied ........................................................................................................... 5327
Create ........................................................................................................... 5328
Main ........................................................................................................... 5329
Type ........................................................................................................... 5330
CiDeMarker
................................................................................................................ 5331
MaPeriod ........................................................................................................... 5333
Create ........................................................................................................... 5334
Main ........................................................................................................... 5335
Type ........................................................................................................... 5336
CiForce ................................................................................................................ 5337
MaPeriod ........................................................................................................... 5339
MaMethod ........................................................................................................... 5340
Applied ........................................................................................................... 5341
Create ........................................................................................................... 5342
Main ........................................................................................................... 5343
Type ........................................................................................................... 5344
CiMACD ................................................................................................................ 5345
FastEmaPeriod
........................................................................................................... 5347
SlowEmaPeriod
........................................................................................................... 5348
SignalPeriod
........................................................................................................... 5349
Applied ........................................................................................................... 5350
Create ........................................................................................................... 5351
Main ........................................................................................................... 5352
Signal ........................................................................................................... 5353
Type ........................................................................................................... 5354
CiMomentum
................................................................................................................ 5355
MaPeriod ........................................................................................................... 5357
Applied ........................................................................................................... 5358
Create ........................................................................................................... 5359
Main ........................................................................................................... 5360
Type ........................................................................................................... 5361
CiOsMA ................................................................................................................ 5362
FastEmaPeriod
........................................................................................................... 5364
SlowEmaPeriod
........................................................................................................... 5365
SignalPeriod
........................................................................................................... 5366
Applied ........................................................................................................... 5367
Create ........................................................................................................... 5368
Main ........................................................................................................... 5369
Type ........................................................................................................... 5370
CiRSI ................................................................................................................ 5371
MaPeriod ........................................................................................................... 5373

© 2000-2025, MetaQuotes Ltd.


52 Content

Applied ........................................................................................................... 5374


Create ........................................................................................................... 5375
Main ........................................................................................................... 5376
Type ........................................................................................................... 5377
CiRVI ................................................................................................................ 5378
MaPeriod ........................................................................................................... 5380
Create ........................................................................................................... 5381
Main ........................................................................................................... 5382
Signal ........................................................................................................... 5383
Type ........................................................................................................... 5384
CiStochastic
................................................................................................................ 5385
Kperiod ........................................................................................................... 5387
Dperiod ........................................................................................................... 5388
Slowing ........................................................................................................... 5389
MaMethod ........................................................................................................... 5390
PriceField ........................................................................................................... 5391
Create ........................................................................................................... 5392
Main ........................................................................................................... 5393
Signal ........................................................................................................... 5394
Type ........................................................................................................... 5395
CiTri X ................................................................................................................ 5396
MaPeriod ........................................................................................................... 5398
Applied ........................................................................................................... 5399
Create ........................................................................................................... 5400
Main ........................................................................................................... 5401
Type ........................................................................................................... 5402
CiWPR ................................................................................................................ 5403
CalcPeriod........................................................................................................... 5405
Create ........................................................................................................... 5406
Main ........................................................................................................... 5407
Type ........................................................................................................... 5408
Volume .........................................................................................................................
I ndicators 5409
CiAD ................................................................................................................ 5410
Applied ........................................................................................................... 5412
Create ........................................................................................................... 5413
Main ........................................................................................................... 5414
Type ........................................................................................................... 5415
CiMFI ................................................................................................................ 5416
MaPeriod ........................................................................................................... 5418
Applied ........................................................................................................... 5419
Create ........................................................................................................... 5420
Main ........................................................................................................... 5421
Type ........................................................................................................... 5422
CiOBV ................................................................................................................ 5423
Applied ........................................................................................................... 5425
Create ........................................................................................................... 5426
Main ........................................................................................................... 5427
Type ........................................................................................................... 5428
CiVolumes ................................................................................................................ 5429
Applied ........................................................................................................... 5431
Create ........................................................................................................... 5432
Main ........................................................................................................... 5433
Type ........................................................................................................... 5434
Bill Williams
.........................................................................................................................
I ndicators 5435
CiAC ................................................................................................................ 5436
Create ........................................................................................................... 5438
Main ........................................................................................................... 5439
Type ........................................................................................................... 5440

© 2000-2025, MetaQuotes Ltd.


53 Content

CiAlligator ................................................................................................................ 5441


JawPeriod ........................................................................................................... 5443
JawShift ........................................................................................................... 5444
TeethPeriod
........................................................................................................... 5445
TeethShift ........................................................................................................... 5446
LipsPeriod ........................................................................................................... 5447
LipsShift ........................................................................................................... 5448
MaMethod ........................................................................................................... 5449
Applied ........................................................................................................... 5450
Create ........................................................................................................... 5451
Jaw ........................................................................................................... 5452
Teeth ........................................................................................................... 5453
Lips ........................................................................................................... 5454
Type ........................................................................................................... 5455
CiAO ................................................................................................................ 5456
Create ........................................................................................................... 5458
Main ........................................................................................................... 5459
Type ........................................................................................................... 5460
CiFractals ................................................................................................................ 5461
Create ........................................................................................................... 5463
Upper ........................................................................................................... 5464
Lower ........................................................................................................... 5465
Type ........................................................................................................... 5466
G
Ci ator ................................................................................................................ 5467
JawPeriod ........................................................................................................... 5469
JawShift ........................................................................................................... 5470
TeethPeriod
........................................................................................................... 5471
TeethShift ........................................................................................................... 5472
LipsPeriod ........................................................................................................... 5473
LipsShift ........................................................................................................... 5474
MaMethod ........................................................................................................... 5475
Applied ........................................................................................................... 5476
Create ........................................................................................................... 5477
Upper ........................................................................................................... 5478
Lower ........................................................................................................... 5479
Type ........................................................................................................... 5480
CiBWMFI ................................................................................................................ 5481
Applied ........................................................................................................... 5483
Create ........................................................................................................... 5484
Main ........................................................................................................... 5485
Type ........................................................................................................... 5486
Custom.........................................................................................................................
indicators 5487
NumBuffers................................................................................................................ 5488
NumParams................................................................................................................ 5489
ParamType................................................................................................................ 5490
ParamLong................................................................................................................ 5491
ParamDouble
................................................................................................................ 5492
ParamString
................................................................................................................ 5493
Type ................................................................................................................ 5494
............................................................................................................................5495
Trade Classes
CAccountI
.........................................................................................................................
nfo 5496
Login ................................................................................................................ 5498
TradeMode................................................................................................................ 5499
TradeModeDescription
................................................................................................................ 5500
Leverage ................................................................................................................ 5501
StopoutMode
................................................................................................................ 5502
StopoutModeDescription
................................................................................................................ 5503
MarginMode
................................................................................................................ 5504

© 2000-2025, MetaQuotes Ltd.


54 Content

MarginModeDescription
................................................................................................................ 5505
TradeAllowed
................................................................................................................ 5506
TradeExpert
................................................................................................................ 5507
LimitOrders
................................................................................................................ 5508
Balance ................................................................................................................ 5509
Credit ................................................................................................................ 5510
Profit ................................................................................................................ 5511
q
E uity ................................................................................................................ 5512
Margin ................................................................................................................ 5513
FreeMargin................................................................................................................ 5514
MarginLevel
................................................................................................................ 5515
MarginCall ................................................................................................................ 5516
MarginStopOut
................................................................................................................ 5517
Name ................................................................................................................ 5518
Server ................................................................................................................ 5519
Currency ................................................................................................................ 5520
Company ................................................................................................................ 5521
I nfoI nteger................................................................................................................ 5522
I nfoDouble ................................................................................................................ 5523
I nfoString ................................................................................................................ 5524
OrderProfitCheck
................................................................................................................ 5525
MarginCheck
................................................................................................................ 5526
FreeMarginCheck
................................................................................................................ 5527
MaxLotCheck
................................................................................................................ 5528
CSymbolI
.........................................................................................................................
nfo 5529
Refresh ................................................................................................................ 5533
RefreshRates
................................................................................................................ 5534
Name ................................................................................................................ 5535
Select ................................................................................................................ 5536
I sSynchroni z
................................................................................................................
ed 5537
Volume ................................................................................................................ 5538
VolumeHigh................................................................................................................ 5539
VolumeLow................................................................................................................ 5540
Time ................................................................................................................ 5541
Spread ................................................................................................................ 5542
SpreadFloat
................................................................................................................ 5543
TicksBookDepth
................................................................................................................ 5544
StopsLevel................................................................................................................ 5545
z
Free eLevel
................................................................................................................ 5546
Bid ................................................................................................................ 5547
BidHigh ................................................................................................................ 5548
BidLow ................................................................................................................ 5549
Ask ................................................................................................................ 5550
AskHigh ................................................................................................................ 5551
AskLow ................................................................................................................ 5552
Last ................................................................................................................ 5553
LastHigh ................................................................................................................ 5554
LastLow ................................................................................................................ 5555
TradeCalcMode
................................................................................................................ 5556
TradeCalcModeDescription
................................................................................................................ 5557
TradeMode................................................................................................................ 5558
TradeModeDescription
................................................................................................................ 5559
TradeExecution
................................................................................................................ 5560
TradeExecutionDescription
................................................................................................................ 5561
SwapMode ................................................................................................................ 5562
SwapModeDescription
................................................................................................................ 5563
SwapRollover3days
................................................................................................................ 5564
SwapRollover3daysDescription
................................................................................................................ 5565

© 2000-2025, MetaQuotes Ltd.


55 Content

MarginI nitial
................................................................................................................ 5566
MarginMaintenance
................................................................................................................ 5567
MarginLong................................................................................................................ 5568
MarginShort
................................................................................................................ 5569
MarginLimit
................................................................................................................ 5570
MarginStop................................................................................................................ 5571
MarginStopLimit
................................................................................................................ 5572
TradeTimeFlags
................................................................................................................ 5573
TradeFillFlags
................................................................................................................ 5574
Digits ................................................................................................................ 5575
Point ................................................................................................................ 5576
TickValue ................................................................................................................ 5577
TickValueProfit
................................................................................................................ 5578
TickValueLoss
................................................................................................................ 5579
TickSi e z ................................................................................................................ 5580
e z
ContractSi................................................................................................................ 5581
LotsMin ................................................................................................................ 5582
LotsMax ................................................................................................................ 5583
LotsStep ................................................................................................................ 5584
LotsLimit ................................................................................................................ 5585
SwapLong ................................................................................................................ 5586
SwapShort ................................................................................................................ 5587
CurrencyBase
................................................................................................................ 5588
CurrencyProfit
................................................................................................................ 5589
CurrencyMargin
................................................................................................................ 5590
Bank ................................................................................................................ 5591
Description................................................................................................................ 5592
Path ................................................................................................................ 5593
SessionDeals
................................................................................................................ 5594
SessionBuyOrders
................................................................................................................ 5595
SessionSellOrders
................................................................................................................ 5596
SessionTurnover
................................................................................................................ 5597
SessionI nterest
................................................................................................................ 5598
SessionBuyOrdersVolume
................................................................................................................ 5599
SessionSellOrdersVolume
................................................................................................................ 5600
SessionOpen
................................................................................................................ 5601
SessionClose
................................................................................................................ 5602
SessionAW ................................................................................................................ 5603
SessionPriceSettlement
................................................................................................................ 5604
SessionPriceLimitMin
................................................................................................................ 5605
SessionPriceLimitMax
................................................................................................................ 5606
I nfoI nteger................................................................................................................ 5607
I nfoDouble ................................................................................................................ 5608
I nfoString ................................................................................................................ 5609
z
Normali ePrice
................................................................................................................ 5610
COrderI.........................................................................................................................
nfo 5611
Ticket ................................................................................................................ 5613
TimeSetup ................................................................................................................ 5614
TimeSetupMsc
................................................................................................................ 5615
OrderType................................................................................................................ 5616
TypeDescription
................................................................................................................ 5617
State ................................................................................................................ 5618
StateDescription
................................................................................................................ 5619
TimeExpiration
................................................................................................................ 5620
TimeDone ................................................................................................................ 5621
TimeDoneMsc
................................................................................................................ 5622
TypeFilling ................................................................................................................ 5623
TypeFillingDescription
................................................................................................................ 5624

© 2000-2025, MetaQuotes Ltd.


56 Content

TypeTime ................................................................................................................ 5625


TypeTimeDescription
................................................................................................................ 5626
Magic ................................................................................................................ 5627
PositionI d ................................................................................................................ 5628
VolumeI nitial
................................................................................................................ 5629
VolumeCurrent
................................................................................................................ 5630
PriceOpen ................................................................................................................ 5631
StopLoss ................................................................................................................ 5632
TakeProfit ................................................................................................................ 5633
PriceCurrent
................................................................................................................ 5634
PriceStopLimit
................................................................................................................ 5635
Symbol ................................................................................................................ 5636
Comment ................................................................................................................ 5637
I nfoI nteger................................................................................................................ 5638
I nfoDouble ................................................................................................................ 5639
I nfoString ................................................................................................................ 5640
StoreState................................................................................................................ 5641
CheckState................................................................................................................ 5642
Select ................................................................................................................ 5643
SelectByI ndex
................................................................................................................ 5644
CHistoryOrderI
.........................................................................................................................
nfo 5645
TimeSetup ................................................................................................................ 5647
TimeSetupMsc
................................................................................................................ 5648
OrderType................................................................................................................ 5649
TypeDescription
................................................................................................................ 5650
State ................................................................................................................ 5651
StateDescription
................................................................................................................ 5652
TimeExpiration
................................................................................................................ 5653
TimeDone ................................................................................................................ 5654
TimeDoneMsc
................................................................................................................ 5655
TypeFilling ................................................................................................................ 5656
TypeFillingDescription
................................................................................................................ 5657
TypeTime ................................................................................................................ 5658
TypeTimeDescription
................................................................................................................ 5659
Magic ................................................................................................................ 5660
PositionI d ................................................................................................................ 5661
VolumeI nitial
................................................................................................................ 5662
VolumeCurrent
................................................................................................................ 5663
PriceOpen ................................................................................................................ 5664
StopLoss ................................................................................................................ 5665
TakeProfit ................................................................................................................ 5666
PriceCurrent
................................................................................................................ 5667
PriceStopLimit
................................................................................................................ 5668
Symbol ................................................................................................................ 5669
Comment ................................................................................................................ 5670
I nfoI nteger................................................................................................................ 5671
I nfoDouble ................................................................................................................ 5672
I nfoString ................................................................................................................ 5673
Ticket ................................................................................................................ 5674
SelectByI ndex
................................................................................................................ 5675
CPositionI
.........................................................................................................................
nfo 5676
Time ................................................................................................................ 5678
TimeMsc ................................................................................................................ 5679
TimeUpdate
................................................................................................................ 5680
TimeUpdateMsc
................................................................................................................ 5681
PositionType
................................................................................................................ 5682
TypeDescription
................................................................................................................ 5683
Magic ................................................................................................................ 5684

© 2000-2025, MetaQuotes Ltd.


57 Content

I dentifier ................................................................................................................ 5685


Volume ................................................................................................................ 5686
PriceOpen ................................................................................................................ 5687
StopLoss ................................................................................................................ 5688
TakeProfit ................................................................................................................ 5689
PriceCurrent
................................................................................................................ 5690
Commission................................................................................................................ 5691
Swap ................................................................................................................ 5692
Profit ................................................................................................................ 5693
Symbol ................................................................................................................ 5694
Comment ................................................................................................................ 5695
I nfoI nteger................................................................................................................ 5696
I nfoDouble ................................................................................................................ 5697
I nfoString ................................................................................................................ 5698
Select ................................................................................................................ 5699
SelectByI ndex
................................................................................................................ 5700
SelectByMagic
................................................................................................................ 5701
SelectByTicket
................................................................................................................ 5702
StoreState................................................................................................................ 5703
CheckState................................................................................................................ 5704
CDealI nfo
......................................................................................................................... 5705
Order ................................................................................................................ 5707
Time ................................................................................................................ 5708
TimeMsc ................................................................................................................ 5709
DealType ................................................................................................................ 5710
TypeDescription
................................................................................................................ 5711
Entry ................................................................................................................ 5712
EntryDescription
................................................................................................................ 5713
Magic ................................................................................................................ 5714
PositionI d ................................................................................................................ 5715
Volume ................................................................................................................ 5716
Price ................................................................................................................ 5717
Commision ................................................................................................................ 5718
Swap ................................................................................................................ 5719
Profit ................................................................................................................ 5720
Symbol ................................................................................................................ 5721
Comment ................................................................................................................ 5722
I nfoI nteger................................................................................................................ 5723
I nfoDouble ................................................................................................................ 5724
I nfoString ................................................................................................................ 5725
Ticket ................................................................................................................ 5726
SelectByI ndex
................................................................................................................ 5727
CTrade ......................................................................................................................... 5728
LogLevel ................................................................................................................ 5732
SetExpertMagicNumber
................................................................................................................ 5733
SetDeviationI
................................................................................................................
nPoints 5734
SetTypeFilling
................................................................................................................ 5735
SetTypeFillingBySymbol
................................................................................................................ 5736
SetAsyncMode
................................................................................................................ 5737
SetMarginMode
................................................................................................................ 5738
OrderOpen................................................................................................................ 5739
OrderModify
................................................................................................................ 5741
OrderDelete
................................................................................................................ 5742
PositionOpen
................................................................................................................ 5743
PositionModify
................................................................................................................ 5744
PositionClose
................................................................................................................ 5745
PositionClosePartial
................................................................................................................ 5746
PositionCloseBy
................................................................................................................ 5748

© 2000-2025, MetaQuotes Ltd.


58 Content

Buy ................................................................................................................ 5749


Sell ................................................................................................................ 5750
BuyLimit ................................................................................................................ 5751
BuyStop ................................................................................................................ 5752
SellLimit ................................................................................................................ 5753
SellStop ................................................................................................................ 5754
q
Re uest ................................................................................................................ 5755
RequestAction
................................................................................................................ 5756
RequestActionDescription
................................................................................................................ 5757
RequestMagic
................................................................................................................ 5758
RequestOrder
................................................................................................................ 5759
RequestSymbol
................................................................................................................ 5760
RequestVolume
................................................................................................................ 5761
RequestPrice
................................................................................................................ 5762
RequestStopLimit
................................................................................................................ 5763
RequestSL ................................................................................................................ 5764
RequestTP ................................................................................................................ 5765
RequestDeviation
................................................................................................................ 5766
RequestType
................................................................................................................ 5767
RequestTypeDescription
................................................................................................................ 5768
RequestTypeFilling
................................................................................................................ 5769
RequestTypeFillingDescription
................................................................................................................ 5770
RequestTypeTime
................................................................................................................ 5771
RequestTypeTimeDescription
................................................................................................................ 5772
RequestExpiration
................................................................................................................ 5773
RequestComment
................................................................................................................ 5774
RequestPosition
................................................................................................................ 5775
RequestPositionBy
................................................................................................................ 5776
Result ................................................................................................................ 5777
ResultRetcode
................................................................................................................ 5778
ResultRetcodeDescription
................................................................................................................ 5779
ResultDeal ................................................................................................................ 5780
ResultOrder
................................................................................................................ 5781
ResultVolume
................................................................................................................ 5782
ResultPrice................................................................................................................ 5783
ResultBid ................................................................................................................ 5784
ResultAsk ................................................................................................................ 5785
ResultComment
................................................................................................................ 5786
CheckResult
................................................................................................................ 5787
CheckResultRetcode
................................................................................................................ 5788
CheckResultRetcodeDescription
................................................................................................................ 5789
CheckResultBalance
................................................................................................................ 5790
CheckResultE q
................................................................................................................
uity 5791
CheckResultProfit
................................................................................................................ 5792
CheckResultMargin
................................................................................................................ 5793
CheckResultMarginFree
................................................................................................................ 5794
CheckResultMarginLevel
................................................................................................................ 5795
CheckResultComment
................................................................................................................ 5796
q
PrintRe uest
................................................................................................................ 5797
PrintResult................................................................................................................ 5798
FormatRe uestq
................................................................................................................ 5799
q
FormatRe uestResult
................................................................................................................ 5800
CTerminalI
.........................................................................................................................
nfo 5801
Build ................................................................................................................ 5803
I sConnected
................................................................................................................ 5804
I sDLLsAllowed
................................................................................................................ 5805
I sTradeAllowed
................................................................................................................ 5806
I sEmailEnabled
................................................................................................................ 5807

© 2000-2025, MetaQuotes Ltd.


59 Content

I sFtpEnabled
................................................................................................................ 5808
MaxBars ................................................................................................................ 5809
CodePage ................................................................................................................ 5810
CPUCores ................................................................................................................ 5811
MemoryPhysical
................................................................................................................ 5812
MemoryTotal
................................................................................................................ 5813
MemoryAvailable
................................................................................................................ 5814
MemoryUsed
................................................................................................................ 5815
X
I s 64 ................................................................................................................ 5816
OpenCLSupport
................................................................................................................ 5817
DiskSpace ................................................................................................................ 5818
Language ................................................................................................................ 5819
Name ................................................................................................................ 5820
Company ................................................................................................................ 5821
Path ................................................................................................................ 5822
DataPath ................................................................................................................ 5823
CommonDataPath
................................................................................................................ 5824
I nfoI nteger................................................................................................................ 5825
I nfoString ................................................................................................................ 5826
............................................................................................................................5827
Strategy Modules
Base classes
.........................................................................................................................
for Expert Advisors 5830
CExpertBase
................................................................................................................ 5831
I nitPhase ........................................................................................................... 5833
TrendType........................................................................................................... 5834
UsedSeries........................................................................................................... 5835
EveryTick ........................................................................................................... 5836
Open ........................................................................................................... 5837
High ........................................................................................................... 5838
Low ........................................................................................................... 5839
Close ........................................................................................................... 5840
Spread ........................................................................................................... 5841
Time ........................................................................................................... 5842
TickVolume........................................................................................................... 5843
RealVolume........................................................................................................... 5844
I nit ........................................................................................................... 5845
Symbol ........................................................................................................... 5846
Period ........................................................................................................... 5847
Magic ........................................................................................................... 5848
ValidationSettings
........................................................................................................... 5849
SetPriceSeries
........................................................................................................... 5850
SetOtherSeries
........................................................................................................... 5851
I nitI ndicators
........................................................................................................... 5852
I nitOpen ........................................................................................................... 5853
I nitHigh ........................................................................................................... 5854
I nitLow ........................................................................................................... 5855
I nitClose ........................................................................................................... 5856
I nitSpread ........................................................................................................... 5857
I nitTime ........................................................................................................... 5858
I nitTickVolume
........................................................................................................... 5859
I nitRealVolume
........................................................................................................... 5860
PriceLevelUnit
........................................................................................................... 5861
StartI ndex........................................................................................................... 5862
CompareMagic
........................................................................................................... 5863
CExpert ................................................................................................................ 5864
I nit ........................................................................................................... 5869
Magic ........................................................................................................... 5870
I nitSignal ........................................................................................................... 5871
I nitTrailing........................................................................................................... 5872

© 2000-2025, MetaQuotes Ltd.


60 Content

I nitMoney ........................................................................................................... 5873


I nitTrade ........................................................................................................... 5874
Deinit ........................................................................................................... 5875
OnTickProcess
........................................................................................................... 5876
OnTradeProcess
........................................................................................................... 5877
OnTimerProcess
........................................................................................................... 5878
OnChartEventProcess
........................................................................................................... 5879
OnBookEventProcess
........................................................................................................... 5880
MaxOrders........................................................................................................... 5881
Signal ........................................................................................................... 5882
ValidationSettings
........................................................................................................... 5883
I nitI ndicators
........................................................................................................... 5884
OnTick ........................................................................................................... 5885
OnTrade ........................................................................................................... 5886
OnTimer ........................................................................................................... 5887
OnChartEvent
........................................................................................................... 5888
OnBookEvent
........................................................................................................... 5889
I nitParameters
........................................................................................................... 5890
DeinitTrade
........................................................................................................... 5891
DeinitSignal
........................................................................................................... 5892
DeinitTrailing
........................................................................................................... 5893
DeinitMoney
........................................................................................................... 5894
DeinitI ndicators
........................................................................................................... 5895
Refresh ........................................................................................................... 5896
Processing........................................................................................................... 5897
SelectPosition
........................................................................................................... 5899
CheckOpen........................................................................................................... 5900
CheckOpenLong
........................................................................................................... 5901
CheckOpenShort
........................................................................................................... 5902
OpenLong ........................................................................................................... 5903
OpenShort ........................................................................................................... 5904
CheckReverse
........................................................................................................... 5905
CheckReverseLong
........................................................................................................... 5906
CheckReverseShort
........................................................................................................... 5907
ReverseLong
........................................................................................................... 5908
ReverseShort
........................................................................................................... 5910
CheckClose........................................................................................................... 5912
CheckCloseLong
........................................................................................................... 5913
CheckCloseShort
........................................................................................................... 5914
CloseAll ........................................................................................................... 5915
Close ........................................................................................................... 5916
CloseLong ........................................................................................................... 5917
CloseShort ........................................................................................................... 5918
CheckTrailingStop
........................................................................................................... 5919
CheckTrailingStopLong
........................................................................................................... 5920
CheckTrailingStopShort
........................................................................................................... 5921
TrailingStopLong
........................................................................................................... 5922
TrailingStopShort
........................................................................................................... 5923
CheckTrailingOrderLong
........................................................................................................... 5924
CheckTrailingOrderShort
........................................................................................................... 5925
TrailingOrderLong
........................................................................................................... 5926
TrailingOrderShort
........................................................................................................... 5927
CheckDeleteOrderLong
........................................................................................................... 5928
CheckDeleteOrderShort
........................................................................................................... 5929
DeleteOrders
........................................................................................................... 5930
DeleteOrder
........................................................................................................... 5931
DeleteOrderLong
........................................................................................................... 5932
DeleteOrderShort
........................................................................................................... 5933

© 2000-2025, MetaQuotes Ltd.


61 Content

LotOpenLong
........................................................................................................... 5934
LotOpenShort
........................................................................................................... 5935
LotReverse........................................................................................................... 5936
PrepareHistoryDate
........................................................................................................... 5937
HistoryPoint
........................................................................................................... 5938
CheckTradeState
........................................................................................................... 5939
WaitEvent ........................................................................................................... 5940
NoWaitEvent
........................................................................................................... 5941
TradeEventPositionStopTake
........................................................................................................... 5942
TradeEventOrderTriggered
........................................................................................................... 5943
TradeEventPositionOpened
........................................................................................................... 5944
TradeEventPositionVolumeChanged
........................................................................................................... 5945
TradeEventPositionModified
........................................................................................................... 5946
TradeEventPositionClosed
........................................................................................................... 5947
TradeEventOrderPlaced
........................................................................................................... 5948
TradeEventOrderModified
........................................................................................................... 5949
TradeEventOrderDeleted
........................................................................................................... 5950
TradeEventNotI
...........................................................................................................
dentified 5951
TimeframeAdd
........................................................................................................... 5952
TimeframesFlags
........................................................................................................... 5953
CExpertSignal
................................................................................................................ 5954
BasePrice ........................................................................................................... 5957
UsedSeries........................................................................................................... 5958
Weight ........................................................................................................... 5959
PatternsUsage
........................................................................................................... 5960
General ........................................................................................................... 5961
I gnore ........................................................................................................... 5962
I nvert ........................................................................................................... 5963
ThresholdOpen
........................................................................................................... 5964
ThresholdClose
........................................................................................................... 5965
PriceLevel........................................................................................................... 5966
StopLevel ........................................................................................................... 5967
TakeLevel ........................................................................................................... 5968
Expiration ........................................................................................................... 5969
Magic ........................................................................................................... 5970
ValidationSettings
........................................................................................................... 5971
I nitI ndicators
........................................................................................................... 5972
AddFilter ........................................................................................................... 5973
CheckOpenLong
........................................................................................................... 5974
CheckOpenShort
........................................................................................................... 5975
OpenLongParams
........................................................................................................... 5976
OpenShortParams
........................................................................................................... 5977
CheckCloseLong
........................................................................................................... 5978
CheckCloseShort
........................................................................................................... 5979
CloseLongParams
........................................................................................................... 5980
CloseShortParams
........................................................................................................... 5981
CheckReverseLong
........................................................................................................... 5982
CheckReverseShort
........................................................................................................... 5983
CheckTrailingOrderLong
........................................................................................................... 5984
CheckTrailingOrderShort
........................................................................................................... 5985
LongCondition
........................................................................................................... 5986
ShortCondition
........................................................................................................... 5987
Direction ........................................................................................................... 5988
CExpertTrailing
................................................................................................................ 5989
CheckTrailingStopLong
........................................................................................................... 5991
CheckTrailingStopShort
........................................................................................................... 5992
CExpertMoney
................................................................................................................ 5993
Percent ........................................................................................................... 5994

© 2000-2025, MetaQuotes Ltd.


62 Content

ValidationSettings
........................................................................................................... 5995
CheckOpenLong
........................................................................................................... 5996
CheckOpenShort
........................................................................................................... 5997
CheckReverse
........................................................................................................... 5998
CheckClose........................................................................................................... 5999
Modules.........................................................................................................................
of Trade Signals 6000
Signals of the
................................................................................................................
I ndicator Accelerator Oscillator 6003
Signals of the
................................................................................................................
I ndicator Adaptive Moving Average 6006
Signals of the
................................................................................................................
I ndicator Awesome Oscillator 6010
Signals of the
................................................................................................................
Oscillator Bears Power 6014
Signals of the
................................................................................................................
Oscillator Bulls Power 6016
Signals of the
................................................................................................................
Oscillator Commodity Channel I ndex 6018
Signals of the
................................................................................................................
Oscillator DeMarker 6022
Signals of the
................................................................................................................
I ndicator Double Exponential Moving Average 6026
Signals of the
................................................................................................................
I ndicator Envelopes 6030
Signals of the
................................................................................................................
I ndicator Fractal Adaptive Moving Average 6033
Signals of the
................................................................................................................
I ntraday Time Filter 6037
Signals of the
................................................................................................................
Oscillator MACD 6039
Signals of the
................................................................................................................
I ndicator Moving Average 6045
Signals of the
................................................................................................................
I ndicator Parabolic SAR 6049
Signals of the
................................................................................................................
Oscillator Relative Strength I ndex 6051
Signals of the
................................................................................................................
Oscillator Relative Vigor I ndex 6057
Signals of the
................................................................................................................
Oscillator Stochastic 6059
Signals of the
................................................................................................................
Oscillator Triple Exponential Average 6064
Signals of the
................................................................................................................
I ndicator Triple Exponential Moving Average 6068
Signals of the
................................................................................................................
Oscillator Williams Percent Range 6072
Trailing .........................................................................................................................
Stop Classes 6075
CTrailingFixedPips
................................................................................................................ 6076
StopLevel ........................................................................................................... 6078
ProfitLevel........................................................................................................... 6079
ValidationSettings
........................................................................................................... 6080
CheckTrailingStopLong
........................................................................................................... 6081
CheckTrailingStopShort
........................................................................................................... 6082
CTrailingMA
................................................................................................................ 6083
Period ........................................................................................................... 6085
Shift ........................................................................................................... 6086
Method ........................................................................................................... 6087
Applied ........................................................................................................... 6088
I nitI ndicators
........................................................................................................... 6089
ValidationSettings
........................................................................................................... 6090
CheckTrailingStopLong
........................................................................................................... 6091
CheckTrailingStopShort
........................................................................................................... 6092
CTrailingNone
................................................................................................................ 6093
CheckTrailingStopLong
........................................................................................................... 6094
CheckTrailingStopShort
........................................................................................................... 6095
CTrailingPSAR
................................................................................................................ 6096
Step ........................................................................................................... 6098
Maximum ........................................................................................................... 6099
I nitI ndicators
........................................................................................................... 6100
CheckTrailingStopLong
........................................................................................................... 6101
CheckTrailingStopShort
........................................................................................................... 6102
Money Management
.........................................................................................................................
Classes 6103
CMoneyFixedLot
................................................................................................................ 6104
Lots ........................................................................................................... 6106
ValidationSettings
........................................................................................................... 6107
CheckOpenLong
........................................................................................................... 6108
CheckOpenShort
........................................................................................................... 6109
CMoneyFixedMargin
................................................................................................................ 6110

© 2000-2025, MetaQuotes Ltd.


63 Content

CheckOpenLong
........................................................................................................... 6111
CheckOpenShort
........................................................................................................... 6112
CMoneyFixedRisk
................................................................................................................ 6113
CheckOpenLong
........................................................................................................... 6114
CheckOpenShort
........................................................................................................... 6115
CMoneyNone
................................................................................................................ 6116
ValidationSettings
........................................................................................................... 6117
CheckOpenLong
........................................................................................................... 6118
CheckOpenShort
........................................................................................................... 6119
z
CMoneySi eOptimi z
................................................................................................................
ed 6120
DecreaseFactor
........................................................................................................... 6122
ValidationSettings
........................................................................................................... 6123
CheckOpenLong
........................................................................................................... 6124
CheckOpenShort
........................................................................................................... 6125
Panels and............................................................................................................................6126
Dialogs
CRect ......................................................................................................................... 6128
Left ................................................................................................................ 6129
Top ................................................................................................................ 6130
Right ................................................................................................................ 6131
Bottom ................................................................................................................ 6132
Width ................................................................................................................ 6133
Height ................................................................................................................ 6134
SetBound ................................................................................................................ 6135
Move ................................................................................................................ 6136
Shift ................................................................................................................ 6137
Contains ................................................................................................................ 6138
Format ................................................................................................................ 6139
CDateTime
......................................................................................................................... 6140
MonthName................................................................................................................ 6142
ShortMonthName
................................................................................................................ 6143
DayName ................................................................................................................ 6144
ShortDayName
................................................................................................................ 6145
DaysI nMonth
................................................................................................................ 6146
DateTime ................................................................................................................ 6147
Date ................................................................................................................ 6148
Time ................................................................................................................ 6149
Sec ................................................................................................................ 6150
Min ................................................................................................................ 6151
Hour ................................................................................................................ 6152
Day ................................................................................................................ 6153
Mon ................................................................................................................ 6154
Y ear ................................................................................................................ 6155
SecDec ................................................................................................................ 6156
SecI nc ................................................................................................................ 6157
MinDec ................................................................................................................ 6158
MinI nc ................................................................................................................ 6159
HourDec ................................................................................................................ 6160
HourI nc ................................................................................................................ 6161
DayDec ................................................................................................................ 6162
DayI nc ................................................................................................................ 6163
MonDec ................................................................................................................ 6164
MonI nc ................................................................................................................ 6165
Y earDec ................................................................................................................ 6166
Y earI nc ................................................................................................................ 6167
CWnd ......................................................................................................................... 6168
Create ................................................................................................................ 6172
Destroy ................................................................................................................ 6173
OnEvent ................................................................................................................ 6174

© 2000-2025, MetaQuotes Ltd.


64 Content

OnMouseEvent
................................................................................................................ 6175
Name ................................................................................................................ 6176
ControlsTotal
................................................................................................................ 6177
Control ................................................................................................................ 6178
ControlFind
................................................................................................................ 6179
Rect ................................................................................................................ 6180
Left ................................................................................................................ 6181
Top ................................................................................................................ 6182
Right ................................................................................................................ 6183
Bottom ................................................................................................................ 6184
Width ................................................................................................................ 6185
Height ................................................................................................................ 6186
Move ................................................................................................................ 6187
Shift ................................................................................................................ 6188
Resi ez ................................................................................................................ 6189
Contains ................................................................................................................ 6190
Alignment ................................................................................................................ 6191
Align ................................................................................................................ 6192
Id ................................................................................................................ 6193
I sEnabled ................................................................................................................ 6194
Enable ................................................................................................................ 6195
Disable ................................................................................................................ 6196
I sVisible ................................................................................................................ 6197
Visible ................................................................................................................ 6198
Show ................................................................................................................ 6199
Hide ................................................................................................................ 6200
I sActive ................................................................................................................ 6201
Activate ................................................................................................................ 6202
Deactivate................................................................................................................ 6203
StateFlags ................................................................................................................ 6204
StateFlagsSet
................................................................................................................ 6205
StateFlagsReset
................................................................................................................ 6206
PropFlags ................................................................................................................ 6207
PropFlagsSet
................................................................................................................ 6208
PropFlagsReset
................................................................................................................ 6209
Mouse X ................................................................................................................ 6210
Mouse Y ................................................................................................................ 6211
MouseFlags................................................................................................................ 6212
MouseFocusKill
................................................................................................................ 6213
OnCreate ................................................................................................................ 6214
OnDestroy ................................................................................................................ 6215
OnMove ................................................................................................................ 6216
z
OnResi e ................................................................................................................ 6217
OnEnable ................................................................................................................ 6218
OnDisable ................................................................................................................ 6219
OnShow ................................................................................................................ 6220
OnHide ................................................................................................................ 6221
OnActivate................................................................................................................ 6222
OnDeactivate
................................................................................................................ 6223
OnClick ................................................................................................................ 6224
OnChange ................................................................................................................ 6225
OnMouseDown
................................................................................................................ 6226
OnMouseUp
................................................................................................................ 6227
OnDragStart
................................................................................................................ 6228
OnDragProcess
................................................................................................................ 6229
OnDragEnd................................................................................................................ 6230
DragObjectCreate
................................................................................................................ 6231
DragObjectDestroy
................................................................................................................ 6232

© 2000-2025, MetaQuotes Ltd.


65 Content

CWndObj
......................................................................................................................... 6233
OnEvent ................................................................................................................ 6235
Text ................................................................................................................ 6236
Color ................................................................................................................ 6237
ColorBackground
................................................................................................................ 6238
ColorBorder
................................................................................................................ 6239
Font ................................................................................................................ 6240
FontSi ez ................................................................................................................ 6241
ZOrder ................................................................................................................ 6242
OnObjectCreate
................................................................................................................ 6243
OnObjectChange
................................................................................................................ 6244
OnObjectDelete
................................................................................................................ 6245
OnObjectDrag
................................................................................................................ 6246
OnSetText ................................................................................................................ 6247
OnSetColor................................................................................................................ 6248
OnSetColorBackground
................................................................................................................ 6249
OnSetFont ................................................................................................................ 6250
OnSetFontSi z
................................................................................................................
e 6251
Z
OnSet Order
................................................................................................................ 6252
OnDestroy ................................................................................................................ 6253
OnChange ................................................................................................................ 6254
CWndContainer
......................................................................................................................... 6255
Destroy ................................................................................................................ 6257
OnEvent ................................................................................................................ 6258
OnMouseEvent
................................................................................................................ 6259
ControlsTotal
................................................................................................................ 6260
Control ................................................................................................................ 6261
ControlFind
................................................................................................................ 6262
Add ................................................................................................................ 6263
Delete ................................................................................................................ 6264
Move ................................................................................................................ 6265
Shift ................................................................................................................ 6266
Id ................................................................................................................ 6267
Enable ................................................................................................................ 6268
Disable ................................................................................................................ 6269
Show ................................................................................................................ 6270
Hide ................................................................................................................ 6271
MouseFocusKill
................................................................................................................ 6272
Save ................................................................................................................ 6273
Load ................................................................................................................ 6274
z
OnResi e ................................................................................................................ 6275
OnActivate................................................................................................................ 6276
OnDeactivate
................................................................................................................ 6277
CLabel ......................................................................................................................... 6278
Create ................................................................................................................ 6283
OnSetText ................................................................................................................ 6284
OnSetColor................................................................................................................ 6285
OnSetFont ................................................................................................................ 6286
OnSetFontSi z
................................................................................................................
e 6287
OnCreate ................................................................................................................ 6288
OnShow ................................................................................................................ 6289
OnHide ................................................................................................................ 6290
OnMove ................................................................................................................ 6291
CBmpButton
......................................................................................................................... 6292
Create ................................................................................................................ 6299
Border ................................................................................................................ 6300
BmpNames ................................................................................................................ 6301
BmpOffName
................................................................................................................ 6302

© 2000-2025, MetaQuotes Ltd.


66 Content

BmpOnName
................................................................................................................ 6303
BmpPassiveName
................................................................................................................ 6304
BmpActiveName
................................................................................................................ 6305
Pressed ................................................................................................................ 6306
Locking ................................................................................................................ 6307
Z
OnSet Order
................................................................................................................ 6308
OnCreate ................................................................................................................ 6309
OnShow ................................................................................................................ 6310
OnHide ................................................................................................................ 6311
OnMove ................................................................................................................ 6312
OnChange ................................................................................................................ 6313
OnActivate................................................................................................................ 6314
OnDeactivate
................................................................................................................ 6315
OnMouseDown
................................................................................................................ 6316
OnMouseUp
................................................................................................................ 6317
CButton......................................................................................................................... 6318
Create ................................................................................................................ 6325
Pressed ................................................................................................................ 6326
Locking ................................................................................................................ 6327
OnSetText ................................................................................................................ 6328
OnSetColor................................................................................................................ 6329
OnSetColorBackground
................................................................................................................ 6330
OnSetColorBorder
................................................................................................................ 6331
OnSetFont ................................................................................................................ 6332
OnSetFontSi z
................................................................................................................
e 6333
OnCreate ................................................................................................................ 6334
OnShow ................................................................................................................ 6335
OnHide ................................................................................................................ 6336
OnMove ................................................................................................................ 6337
z
OnResi e ................................................................................................................ 6338
OnMouseDown
................................................................................................................ 6339
OnMouseUp
................................................................................................................ 6340
CEdit ......................................................................................................................... 6341
Create ................................................................................................................ 6346
ReadOnly ................................................................................................................ 6347
TextAlign ................................................................................................................ 6348
OnObjectEndEdit
................................................................................................................ 6349
OnSetText ................................................................................................................ 6350
OnSetColor................................................................................................................ 6351
OnSetColorBackground
................................................................................................................ 6352
OnSetColorBorder
................................................................................................................ 6353
OnSetFont ................................................................................................................ 6354
OnSetFontSi z
................................................................................................................
e 6355
Z
OnSet Order
................................................................................................................ 6356
OnCreate ................................................................................................................ 6357
OnShow ................................................................................................................ 6358
OnHide ................................................................................................................ 6359
OnMove ................................................................................................................ 6360
z
OnResi e ................................................................................................................ 6361
OnChange ................................................................................................................ 6362
OnClick ................................................................................................................ 6363
CPanel ......................................................................................................................... 6364
Create ................................................................................................................ 6369
BorderType................................................................................................................ 6370
OnSetText ................................................................................................................ 6371
OnSetColorBackground
................................................................................................................ 6372
OnSetColorBorder
................................................................................................................ 6373
OnCreate ................................................................................................................ 6374

© 2000-2025, MetaQuotes Ltd.


67 Content

OnShow ................................................................................................................ 6375


OnHide ................................................................................................................ 6376
OnMove ................................................................................................................ 6377
z
OnResi e ................................................................................................................ 6378
OnChange ................................................................................................................ 6379
CPicture
......................................................................................................................... 6380
Create ................................................................................................................ 6385
Border ................................................................................................................ 6386
BmpName ................................................................................................................ 6387
OnCreate ................................................................................................................ 6388
OnShow ................................................................................................................ 6389
OnHide ................................................................................................................ 6390
OnMove ................................................................................................................ 6391
OnChange ................................................................................................................ 6392
CScroll ......................................................................................................................... 6393
Create ................................................................................................................ 6395
OnEvent ................................................................................................................ 6396
MinPos ................................................................................................................ 6397
MaxPos ................................................................................................................ 6398
CurrPos ................................................................................................................ 6399
CreateBack
................................................................................................................ 6400
CreateI nc ................................................................................................................ 6401
CreateDec ................................................................................................................ 6402
CreateThumb
................................................................................................................ 6403
OnClickI nc ................................................................................................................ 6404
OnClickDec................................................................................................................ 6405
OnShow ................................................................................................................ 6406
OnHide ................................................................................................................ 6407
OnChangePos
................................................................................................................ 6408
OnThumbDragStart
................................................................................................................ 6409
OnThumbDragProcess
................................................................................................................ 6410
OnThumbDragEnd
................................................................................................................ 6411
CalcPos ................................................................................................................ 6412
CScrollV......................................................................................................................... 6413
CreateI nc ................................................................................................................ 6419
CreateDec ................................................................................................................ 6420
CreateThumb
................................................................................................................ 6421
z
OnResi e ................................................................................................................ 6422
OnChangePos
................................................................................................................ 6423
OnThumbDragStart
................................................................................................................ 6424
OnThumbDragProcess
................................................................................................................ 6425
OnThumbDragEnd
................................................................................................................ 6426
CalcPos ................................................................................................................ 6427
CScrollH......................................................................................................................... 6428
CreateI nc ................................................................................................................ 6434
CreateDec ................................................................................................................ 6435
CreateThumb
................................................................................................................ 6436
z
OnResi e ................................................................................................................ 6437
OnChangePos
................................................................................................................ 6438
OnThumbDragStart
................................................................................................................ 6439
OnThumbDragProcess
................................................................................................................ 6440
OnThumbDragEnd
................................................................................................................ 6441
CalcPos ................................................................................................................ 6442
CWndClient
......................................................................................................................... 6443
Create ................................................................................................................ 6446
OnEvent ................................................................................................................ 6447
ColorBackground
................................................................................................................ 6448
ColorBorder
................................................................................................................ 6449

© 2000-2025, MetaQuotes Ltd.


68 Content

BorderType................................................................................................................ 6450
VScrolled ................................................................................................................ 6451
HScrolled ................................................................................................................ 6452
CreateBack
................................................................................................................ 6453
CreateScrollV
................................................................................................................ 6454
CreateScrollH
................................................................................................................ 6455
z
OnResi e ................................................................................................................ 6456
OnVScrollShow
................................................................................................................ 6457
OnVScrollHide
................................................................................................................ 6458
OnHScrollShow
................................................................................................................ 6459
OnHScrollHide
................................................................................................................ 6460
OnScrollLineDown
................................................................................................................ 6461
OnScrollLineUp
................................................................................................................ 6462
OnScrollLineLeft
................................................................................................................ 6463
OnScrollLineRight
................................................................................................................ 6464
Rebound ................................................................................................................ 6465
CListView
......................................................................................................................... 6466
Create ................................................................................................................ 6472
OnEvent ................................................................................................................ 6473
TotalView ................................................................................................................ 6474
AddI tem ................................................................................................................ 6475
Select ................................................................................................................ 6476
SelectByText
................................................................................................................ 6477
SelectByValue
................................................................................................................ 6478
Value ................................................................................................................ 6479
CreateRow................................................................................................................ 6480
z
OnResi e ................................................................................................................ 6481
OnVScrollShow
................................................................................................................ 6482
OnVScrollHide
................................................................................................................ 6483
OnScrollLineDown
................................................................................................................ 6484
OnScrollLineUp
................................................................................................................ 6485
OnI temClick
................................................................................................................ 6486
Redraw ................................................................................................................ 6487
RowState ................................................................................................................ 6488
CheckView................................................................................................................ 6489
CComboBox
......................................................................................................................... 6490
Create ................................................................................................................ 6496
OnEvent ................................................................................................................ 6497
AddI tem ................................................................................................................ 6498
ListViewI tems
................................................................................................................ 6499
Select ................................................................................................................ 6500
SelectByText
................................................................................................................ 6501
SelectByValue
................................................................................................................ 6502
Value ................................................................................................................ 6503
CreateEdit................................................................................................................ 6504
CreateButton
................................................................................................................ 6505
CreateList ................................................................................................................ 6506
OnClickEdit................................................................................................................ 6507
OnClickButton
................................................................................................................ 6508
OnChangeList
................................................................................................................ 6509
ListShow ................................................................................................................ 6510
ListHide ................................................................................................................ 6511
CCheckBox
......................................................................................................................... 6512
Create ................................................................................................................ 6518
OnEvent ................................................................................................................ 6519
Text ................................................................................................................ 6520
Color ................................................................................................................ 6521
Checked ................................................................................................................ 6522

© 2000-2025, MetaQuotes Ltd.


69 Content

Value ................................................................................................................ 6523


CreateButton
................................................................................................................ 6524
CreateLabel
................................................................................................................ 6525
OnClickButton
................................................................................................................ 6526
OnClickLabel
................................................................................................................ 6527
G
CCheck.........................................................................................................................
roup 6528
Create ................................................................................................................ 6534
OnEvent ................................................................................................................ 6535
AddI tem ................................................................................................................ 6536
Value ................................................................................................................ 6537
CreateButton
................................................................................................................ 6538
OnVScrollShow
................................................................................................................ 6539
OnVScrollHide
................................................................................................................ 6540
OnScrollLineDown
................................................................................................................ 6541
OnScrollLineUp
................................................................................................................ 6542
OnChangeI................................................................................................................
tem 6543
Redraw ................................................................................................................ 6544
RowState ................................................................................................................ 6545
CRadioButton
......................................................................................................................... 6546
Create ................................................................................................................ 6548
OnEvent ................................................................................................................ 6549
Text ................................................................................................................ 6550
Color ................................................................................................................ 6551
State ................................................................................................................ 6552
CreateButton
................................................................................................................ 6553
CreateLabel
................................................................................................................ 6554
OnClickButton
................................................................................................................ 6555
OnClickLabel
................................................................................................................ 6556
G
CRadio .........................................................................................................................
roup 6557
Create ................................................................................................................ 6563
OnEvent ................................................................................................................ 6564
AddI tem ................................................................................................................ 6565
Value ................................................................................................................ 6566
CreateButton
................................................................................................................ 6567
OnVScrollShow
................................................................................................................ 6568
OnVScrollHide
................................................................................................................ 6569
OnScrollLineDown
................................................................................................................ 6570
OnScrollLineUp
................................................................................................................ 6571
OnChangeI................................................................................................................
tem 6572
Redraw ................................................................................................................ 6573
RowState ................................................................................................................ 6574
Select ................................................................................................................ 6575
CSpinEdit
......................................................................................................................... 6576
Create ................................................................................................................ 6581
OnEvent ................................................................................................................ 6582
MinValue ................................................................................................................ 6583
MaxValue ................................................................................................................ 6584
Value ................................................................................................................ 6585
CreateEdit................................................................................................................ 6586
CreateI nc ................................................................................................................ 6587
CreateDec ................................................................................................................ 6588
OnClickI nc ................................................................................................................ 6589
OnClickDec................................................................................................................ 6590
OnChangeValue
................................................................................................................ 6591
CDialog ......................................................................................................................... 6592
Create ................................................................................................................ 6594
OnEvent ................................................................................................................ 6595
Caption ................................................................................................................ 6596

© 2000-2025, MetaQuotes Ltd.


70 Content

Add ................................................................................................................ 6597


CreateWhiteBorder
................................................................................................................ 6598
CreateBackground
................................................................................................................ 6599
CreateCaption
................................................................................................................ 6600
CreateButtonClose
................................................................................................................ 6601
CreateClientArea
................................................................................................................ 6602
OnClickCaption
................................................................................................................ 6603
OnClickButtonClose
................................................................................................................ 6604
ClientAreaVisible
................................................................................................................ 6605
ClientAreaLeft
................................................................................................................ 6606
ClientAreaTop
................................................................................................................ 6607
ClientAreaRight
................................................................................................................ 6608
ClientAreaBottom
................................................................................................................ 6609
ClientAreaWidth
................................................................................................................ 6610
ClientAreaHeight
................................................................................................................ 6611
OnDialogDragStart
................................................................................................................ 6612
OnDialogDragProcess
................................................................................................................ 6613
OnDialogDragEnd
................................................................................................................ 6614
CAppDialog
......................................................................................................................... 6615
Create ................................................................................................................ 6618
Destroy ................................................................................................................ 6619
OnEvent ................................................................................................................ 6620
Run ................................................................................................................ 6621
ChartEvent................................................................................................................ 6622
z
Minimi ed ................................................................................................................ 6623
I niFileSave ................................................................................................................ 6624
I niFileLoad................................................................................................................ 6625
I niFileName................................................................................................................ 6626
I niFileExt ................................................................................................................ 6627
CreateCommon
................................................................................................................ 6628
CreateExpert
................................................................................................................ 6629
CreateI ndicator
................................................................................................................ 6630
CreateButtonMinMax
................................................................................................................ 6631
OnClickButtonClose
................................................................................................................ 6632
OnClickButtonMinMax
................................................................................................................ 6633
OnAnotherApplicationClose
................................................................................................................ 6634
Rebound ................................................................................................................ 6635
z
Minimi e ................................................................................................................ 6636
Maximiz e ................................................................................................................ 6637
CreateI nstanceI
................................................................................................................
d 6638
ProgramName
................................................................................................................ 6639
SubwinOff ................................................................................................................ 6640

36 Moving from .................................................................................................


MQL4 6641
37 List of MQL5 .................................................................................................
Functions 6644
38 List of MQL5 .................................................................................................
Constants 6678

© 2000-2025, MetaQuotes Ltd.


71

MQL5 Reference
MetaQuotes Language 5 (MQL5) is a high-level language designed for developing technical indicators,
trading robots and utility applications, which automate financial trading. MQL5 has been developed by
MetaQuotes for their trading platform. The language syntax is very close to C++ enabling programmers
to develop applications in the object-oriented programming (OOP) style.
In addition to the MQL5 language, the trading platform package also includes the MetaEditor IDE with
highly advanced code writing tools, such as templates, snippets, debugging, profiling and auto
completion tools, as well as built-in MQL5 S torage enabling file versioning.
The language support is available on the MQL5 Algotrading community website, which contains a huge
free CodeBase and a plethora of articles. These articles cover all the aspects of the modern trading,
including neural networks, statistics and analysis, high-frequency trading, arbitrage, testing and
optimization of trading strategies, use of trading automation robots, and more.
Traders and MQL5 program developers can communicate on the forum, order and develop applications
using the Freelance service, as well as buy and sell protected programs in the Market of automated
trading applications.
The MQL5 language provides specialized trading functions and predefined event handlers to help
programmers develop Expert Advisors (EAs), which automatically control trading processes following
specific trading rules. In addition to EAs, MQL5 allows developing custom technical indicators, scripts
and libraries.
This MQL5 language reference contains functions, operations, reserved words and other language
constructions divided into categories. The reference also provides descriptions of S tandard Library
classes used for developing trading strategies, control panels, custom graphics and enabling file
access.
Additionally, the CodeBase contains the ALGLIB numerical analysis library, which can be used for
solving various mathematical problems.

Algo Trading Books

S tartingto learn something new is always challenging. To assist beginners, we have released two
comprehensive books on MQL5 programming, designed for anyone who wish to master the creation of
trading robots and applications for algorithmic trading.
These books offer a systematic and structured presentation of the material to make the learning
process significantly easier. Detailed code examples, which explain the step-by-step creation of
trading robots and applications, allow for a deeper understanding of algorithmic trading nuances. The
books include numerous practical exercises to help reinforce the acquired knowledge and develop
programming s kills in real trading environments.
" MQL5 Programming for Traders " is the most complete and detailed tutorial on MQL5, suitable for
programmers of all levels. Beginners will learn the basics : the book introduces development tools and
basic programming concepts. Based on this material, you will create, compile and run your first
application in the MetaTrader 5 trading platform. Users with experience in other programming

© 2000-2025, MetaQuotes Ltd.


72

languages can immediately proceed to the application part: creating trading robots and analytical
applications in MQL5.
"Neural Network s for Algorithmic Trading with MQL5" is a guide to using machine learning methods in
trading robots for the MetaTrader 5 platform. You will be progressively introduced to the fundamentals
of neural networks and their application in algorithmic trading. As you advance, you will build and train
your own AI solution, gradually adding new features. In addition to learning MQL5, you will gain Python
and OpenCL programming s kills and explore integrated matrix and vector methods, which enable the
solution of complex mathematical problems with concise and efficient code.

Articles on the development of trading applications

MQL5 Articles are an excellent resource for exploring the full potential of the language, covering a
wide range of practical algorithmic trading tas ks. For easy navigation, all articles are categorized into
sections such as Example, Expert Advisors, Machine Learning and more. Every month, dozens of new
articles are published on the MQL5 Algotrading community website, written by traders for other
traders. Read and discuss these articles to master modern algorithmic trading. For beginners, we have
compiled a list of 16 recommended articles for a quick immersion into MQL5.

Types of MQL5 Applications


MQL5 programs are divided into five specialized types based on the trading automation tas ks that
they implement:
· Expert Advisor is an automated trading system linked to a chart. An Expert Advisor contains event
handlers to manage predefined events which activate execution of appropriate trading strategy
elements. For example, an event of program initialization and deinitializtion, new ticks, timer
events, changes in the Depth of Market, chart and custom events.
In addition to calculating trading signals based on the implemented rules, Expert Advisors can also
automatically execute trades and send them directly to a trading server. Expert Advisors are stored
in <Terminal_Directory>\MQL5\Experts .
· Custom Indicator s is a technical indicator developed by a user in addition to standard indicators
integrated into the trading platform. Custom indicators, as well as standard ones, cannot trade
automatically, but only implement analytical functions. Custom indicators can utilize values of other
indicators for calculations, and can be called from Expert Advisors.
Custom indicators are stored in <Terminal_Directory>\MQL5\Indicators .
· Script is a program for a single execution of an action. Unlik e Expert Advisors, scripts do not handle
any event except for trigger. A script code must contain the OnS tart handler function.
S cripts are stored in <Terminal_DIrectory>\MQL5\Scripts.
· Service is a program that, unlik e indicators, Expert Advisors and scripts, does not require to be
bound to a chart to work. Like scripts, services do not handle any event except for trigger. To
launch a service, its code should contain the OnS tart handler function. S ervices do not accept any
other events except S tart, but they are able to send custom events to charts using
EventChartCustom. S ervices are stored in <terminal_directory>\MQL5\S ervices.
· Library is a set of custom functions. Libraries are intended to store and distribute commonly used
algorithms of custom programs.
Libraries are stored in <Terminal_Directory>\MQL5\Libraries .

© 2000-2025, MetaQuotes Ltd.


73

· Include File is a source text of the most frequently used blocks of custom programs. S uch 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 where the original file is located. In this case the
#include directive with double quotes is used. Another option is to store include files in
<Terminal_Directory>\MQL5\Include. In this case #include with angle brack ets should be used.

© 2000-2025, MetaQuotes Ltd.

© 2000-2025, MetaQuotes Ltd.


74 Language Basics

Language Basics
The MetaQuotes Language 5 (MQL5) is an object-oriented high-level programming language intended
for writing 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 is based on the concept of the popular programming language C++. As compared to MQL4, the
new language now has enumerations, structures, classes and event handling. By increasing the number
of embedded main types, the interaction of executable programs in MQL5 with other applications
through dll is now as easy as possible. MQL5 syntax is similar to the syntax of C++, and this makes it
easy to translate into it programs from modern programming languages.
To help you study the MQL5 language, all topics are grouped into the following sections :
· S yntax

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

© 2000-2025, MetaQuotes Ltd.


75 Language Basics

Syntax
Asto the syntax, THE MQL5 language for programming trading strategies is very much similar to the
C++ programming language, except for some features :
· no address arithmetic;
· no goto operator;
· an anonymous enumeration can't be declared;
· no multiple inheritance.
See also
Enumerations, S tructures and Classes, Inheritance

© 2000-2025, MetaQuotes Ltd.


76 Language Basics

Comments
Multi-line comments start with the /* pair of symbols and end with the */ one. S uch kind of comments
cannot be nested. S ingle-line comments begin with the // pair of symbols and end with the newline
character, 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
*/

© 2000-2025, MetaQuotes Ltd.


77 Language Basics

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

Characters allowed to be written in an identifier: 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

See also
Variables, Functions

© 2000-2025, MetaQuotes Ltd.


78 Language Basics

Reserved Words
The following identifiers are recorded as reserved words, each of them corresponds to a certain
action, and cannot be used in another meaning:
Data Types

bool float uint


char int ulong
class long union
color short ushort
datetime string void
double struct
enum uchar

Access Specificators

const private virtual


delete protected
override public

Memory Classes

extern input static

Operators

break dynamic_cast operator


case else pack
continue for return
default if sizeof
delete new switch
do offsetof while

Other

this #define #import

true #ifdef #include

© 2000-2025, MetaQuotes Ltd.


79 Language Basics

this #define #import

false #ifndef #property

template #else group


typename #endif namespace

© 2000-2025, MetaQuotes Ltd.


80 Language Basics

Data Types
Any program operates with data. Data can be of different types depending on their purposes. For
example, integer data are used to access to array components. Price data belong to those of double
precision with floating point. This is related to the fact that no special data type for price data is
provided in MQL5.
Data of different types are processed with different rates. Integer data are processed at the fastest.
To process the double precision data, a special co-processor is used. However, because of complexity
of internal representation of data with floating point, they are processed slower than the integer ones.
S tring data are processed at the longest because of dynamic computer memory allocation/reallocation.
The basic data types are:
· integers (char, short, int, long, uchar, ushort, uint, ulong);
· logical (bool);
· literals (ushort);
· strings (string);
· floating-point numbers (double, float);
· color (color);
· date and time (datetime);
· enumerations (enum).
Complex data types are:
· structures ;
· classes.
In terms of OOP complex data types are called abstract data types.
The color and datetime types make sense only to facilitate visualization and input of parameters
defined from outside - from the table of Expert Advisor or custom indicator properties (the Inputs
tab). Data of color and datetime types are represented as integers. Integer types and floating-point
types are called arithmetic (numeric) types.
Only implicit type casting is used in expressions, unless the explicit casting is specified.
See also
Typecasting

© 2000-2025, MetaQuotes Ltd.


81 Language Basics

Integer Types
In MQL5 integers are represented by eleven types. S ome types can be used together with other ones,
if required by the program logic, but in this case it's necessary to remember the rules of typecasting.
The table below lists the characteristics of each type. Besides, the last column features a type in C++
corresponding to each type.

Type Size in Bytes Minimum Value Maximum Value C++ Analog

char 1 -128 127 char


uchar 1 0 255 unsigned char,
BYT E

bool 1 0(false) 1(true) bool


short 2 -32 768 32 767 short, wchar_t
ushort 2 0 65 535 unsigned short,
W ORD

int 4 - 2 147 483 648 2 147 483 647 int


uint 4 0 4 294 967 295 unsigned int,
DW ORD

color 4 -1 16 777 215 int, COLORREF


long 8 -9 223 372 036 9 223 372 036 __int64
854 775 808 854 775 807

ulong 8 0 18 446 744 073 unsigned __int64


709 551 615

datetime 8 0 (1970.01.01 32 535 244 799 __time64_t


0:00:00) (3000.12.31
23:59:59)

Integer type values can also be presented as numeric constants, color literals, date-time literals,
character constants and enumerations.
See also
Conversion Functions, Numerical Type Constants

© 2000-2025, MetaQuotes Ltd.


82 Language Basics

Char, Short, Int and Long Types


char
The char type takes 1 byte of memory (8 bits) and allows expressing in the binary notation 2^8=256
values. The char type can contain both positive and negative values. The range of values is from -128
to 127.

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

short
The size of the short type is 2 bytes (16 bits) and, accordingly, it allows expressing the range of values
equal to 2 to the power 16: 2^16 = 65 536.S ince the short type is a signed one, and contains both
positive and negative values, the range of values is between -32 768 and 32 767.

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

int
The size of the int type is 4 bytes (32 bits). The minimal value is -2 147 483 648, the maximal one is 2
147 483 647.

uint
The unsigned integer type is uint. It takes 4 bytes of memory and allows expressing integers from 0 to
4 294 967 295.

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

ulong
The ulong type 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;

© 2000-2025, MetaQuotes Ltd.


83 Language Basics

S incethe unsigned integer types are not designed for storing negative values, the attempt to set a
negative value can lead to unexpected consequences. S uch a simple 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);
}
}

The correct variant is :


//--- 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

© 2000-2025, MetaQuotes Ltd.


84 Language Basics

...

Examples:

//--- Negative values can not be stored in unsigned types


uchar u_ch=-120;
ushort u_sh=-5000;
uint u_in=-401280;

H exadecimal: 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

For integer variables, the values can be set in binary form using B prefix. For example, you can encode
the working hours of a trading session into int type variable and use information about them according
to the required algorithm:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set 1 for working hours and 0 for nonworking ones
int AsianSession =B'111111111'; // Asian session from 0:00 to 9:00
int EuropeanSession=B'111111111000000000'; // European session 9:00 - 18:00
int AmericanSession =B'111111110000000000000011'; // American session 16:00 - 02:00
//--- derive numerical values of the sessions
PrintFormat("Asian session hours as value =%d",AsianSession);
PrintFormat("European session hours as value is %d",EuropeanSession);
PrintFormat("American session hours as value is %d",AmericanSession);
//--- and now let's display string representations of the sessions' working hours
Print("Asian session ",GetHoursForSession(AsianSession));
Print("European session ",GetHoursForSession(EuropeanSession));
Print("American session ",GetHoursForSession(AmericanSession));
//---
}
//+------------------------------------------------------------------+
//| return the session's working hours as a string |
//+------------------------------------------------------------------+
string GetHoursForSession(int session)
{
//--- in order to check, use AND bit operations and left shift by 1 bit <<=1
//--- start checking from the lowest bit
int bit=1;
string out="working hours: ";
//--- check all 24 bits starting from the zero and up to 23 inclusively
for(int i=0;i<24;i++)
{
//--- receive bit state in number

© 2000-2025, MetaQuotes Ltd.


85 Language Basics

bool workinghour=(session&bit)==bit;
//--- add the hour's number to the message
if(workinghour )out=out+StringFormat("%d ",i);
//--- shift by one bit to the left to check the value of the next one
bit<<=1;
}
//--- result string
return out;
}

See also
Typecasting

© 2000-2025, MetaQuotes Ltd.


86 Language Basics

Character Constants
Characters as elements of a string in MQL5 are indexes in the Unicode character set. They are
hexadecimal values that can be cast into integers, and that can be manipulated by integer operations
like addition and subtraction.
Any single character in quotation marks or a hexadecimal AS CII code of a character as '\x10' is a
character constant and is of ushort type. For example, a record of '0' type is a numerical value 30, that
corresponds to the index of zero in the table of characters.
Example:

void OnStart()
{
//--- define character constants
int symbol_0='0';
int symbol_9=symbol_0+9; // get symbol '9'
//--- output values of constants
printf("In a decimal form: symbol_0 = %d, symbol_9 = %d",symbol_0,symbol_9);
printf("In a hexadecimal form: symbol_0 = 0x%x, symbol_9 = 0x%x",symbol_0,symbol_9);
//--- enter constants into a string
string test="";
StringSetCharacter(test,0,symbol_0);
StringSetCharacter(test,1,symbol_9);
//--- this is what they look like in a string
Print(test);
}

A backslash is a control character for a compiler when dealing with constant strings and character
constants in a source text of a program. S ome symbols, for example a single quote ('), double quotes
(" ), backslash (\) and control characters can be represented as a combination of symbols that start
with a backslash (\), according to the below table:

Character name Mnemonic code or Record in MQL5 Numeric value


image

new line (line feed) LF '\n' 10

horizontal tab HT '\t' 9

carriage return CR '\r' 13

backslash \ '\\' 92

single quote ' '\'' 39

double quote " '\"' 34

hexadecimal code hhhh '\xhhhh' 1 to 4 hexadecimal


characters
decimal code d '\d' decimal number from
0 to 65535

© 2000-2025, MetaQuotes Ltd.


87 Language Basics

If a backslash is followed by a character other than those described above, result is undefined.
Example

void OnStart()
{
//--- declare character constants
int a='A';
int b='$';
int c='©'; // code 0xA9
int d='\xAE'; // code of the symbol ®
//--- output print constants
Print(a,b,c,d);
//--- add a character to the string
string test="";
StringSetCharacter(test,0,a);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,b);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,c);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,d);
Print(test);
//--- represent characters as a number
int a1=65;
int b1=36;
int c1=169;
int d1=174;
//--- add a character to the string
StringSetCharacter(test,1,a1);
Print(test);
//--- add a character to the string
StringSetCharacter(test,1,b1);
Print(test);
//--- add a character to the string
StringSetCharacter(test,1,c1);
Print(test);
//--- add a character to the string
StringSetCharacter(test,1,d1);
Print(test);
}

As it was mentioned above, the value of a character constant (or variable) is an index in the table of
characters. Index being an integer, it can be written in different ways.
void OnStart()
{

© 2000-2025, MetaQuotes Ltd.


88 Language Basics

//---
int a=0xAE; // the code of ® corresponds to the '\xAE' literal
int b=0x24; // the code of $ corresponds to the '\x24' literal
int c=0xA9; // the code of © corresponds to the '\xA9' literal
int d=0x263A; // the code of ☺ corresponds to the '\x263A' literal
//--- show values
Print(a,b,c,d);
//--- add a character to the string
string test="";
StringSetCharacter(test,0,a);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,b);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,c);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,d);
Print(test);
//--- codes of suits
int a1=0x2660;
int b1=0x2661;
int c1=0x2662;
int d1=0x2663;
//--- add a character of spades
StringSetCharacter(test,1,a1);
Print(test);
//--- add a character of hearts
StringSetCharacter(test,2,b1);
Print(test);
//--- add a character of diamonds
StringSetCharacter(test,3,c1);
Print(test);
//--- add a character of clubs
StringSetCharacter(test,4,d1);
Print(test);
//--- Example of character literals in a string
test="Queen\x2660Ace\x2662";
printf("%s",test);
}

The internal representation of a character literal is the ushort type. Character constants can accept
values from 0 to 65535.
See also
S tring S etCharacter(), S tring GetCharacter(), S hortToS tring(), S hortArrayToS tring(),
S tringToS hortArray()

© 2000-2025, MetaQuotes Ltd.


89 Language Basics

Datetime Type
The datetime type is intended for storing the date and time as the number of seconds elapsed since
January 01, 1970. This type occupies 8 bytes of memory.

Constants of the date and time can be represented as a literal string, which consists of 6 parts
showing the numerical value of the year, month, day (or day, month, year), hours, minutes and
seconds. The constant is enclosed in single quotation marks and starts with the D character.
Values range from 1 January, 1970 to 31 December, 3000. Either date (year , month, day) or time
(hours, minutes, seconds), or all together can be omitted.
W ithliteral date specification, it is desirable that you specify year, month and day. Otherwise the
compiler returns a warning about an incomplete entry.
Examples:

datetime NY=D'2015.01.01 00:00'; // Time of beginning of year 2015


datetime d1=D'1980.07.19 12:30:27'; // Year Month Day Hours Minutes Seconds
datetime d2=D'19.07.1980 12:30:27'; // Equal to D'1980.07.19 12:30:27';
datetime d3=D'19.07.1980 12'; // Equal to D'1980.07.19 12:00:00'
datetime d4=D'01.01.2004'; // Equal to D'01.01.2004 00:00:00'
datetime compilation_date=__DATE__; // Compilation date
datetime compilation_date_time=__DATETIME__; // Compilation date and time
datetime compilation_time=__DATETIME__-__DATE__;// Compilation time
//--- Examples of declarations after which compiler warnings will be returned
datetime warning1=D'12:30:27'; // Equal to D'[date of compilation] 12:30:27'
datetime warning2=D''; // Equal to __DATETIME__

See also
S tructure of the Date Type, Date and Time, TimeToS tring, S tringToTime

© 2000-2025, MetaQuotes Ltd.


90 Language Basics

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 in three ways : literally, by integers, or by name (for named W eb-
colors only).
Literal representation consists of three parts representing numerical rate values of the three main
color components : red, green, blue. The constant starts with C and is enclosed in single quotes.
Numerical rate values of a color component lie in the range from 0 to 255.

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


number looks like 0x00BBGGRR, where RR is the rate of the red color component, GG - of the green
one, and BB - of the blue one. Decimal constants are not directly reflected in the RGB. They represent
a decimal value of the hexadecimal integer representation.
S pecific colors reflect the so-called W eb-colors set.
Examples:

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

See also
W eb Colors, ColorToS tring, S tringToColor, Typecasting

© 2000-2025, MetaQuotes Ltd.


91 Language Basics

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

Examples:

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

The internal representation is a whole number 1 byte large. It should be noted that in logical
expressions you can use other integer or real types or expressions of these types - the compiler will
not generate any error. In this case, the zero value 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.5 and has the true value
// i= 0 and has the false value
// d= 0 and has the false value

See also
Boolean Operations, Precedence Rules

© 2000-2025, MetaQuotes Ltd.


92 Language Basics

Enumerations
Data of the enum type belong to a certain limited set of data. Defining the enumeration type:
enum name of enumerable type
{
list of values
};

The list of values is a list of identifiers of named constants separated by commas.


Example:

enum months // enumeration of named constants


{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
};

After the enumeration is declared, a new integer-valued 4-byte data type appears. Declaration of the
new data type allows the compiler to strictly control types of passed parameters, because enumeration
introduces new named constants. In the above example, the January named constant has the value of
0, February - 1, December - 11.

Rule: If a certain value is not assigned to a named constant that is a member of the enumeration, its
new value will be formed automatically. If it is the first member of the enumeration, the 0 value will
be assigned to it. For all subsequent members, values will be calculated based on the value of the
previous members by adding one.
Example:

enum intervals // Enumeration of named constants


{
month=1, // Interval of one month
two_months, // Two months
quarter, // Three months - quarter
halfyear=6, // Half a year
year=12, // Year - 12 months
};

Notes

© 2000-2025, MetaQuotes Ltd.


93 Language Basics

· Unlik e C++, the size of the internal representation of the enumerated type in MQL5 is always equal
to 4 bytes. That is, sizeof (months) returns the value 4.
· Unlik e C++, an anonymous enumeration can't be declared in MQL5. That is, a unique name must be
always specified after the enum keyword.
See also
Typecasting

© 2000-2025, MetaQuotes Ltd.


94 Language Basics

Real Types (double, float)


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

Type Size in bytes Minimal Positive Maximum Value C++ Analog


Value

float 4 1.175494351e-38 3.402823466e+3 float


8

double 8 2.225073858507 1.797693134862 double


2014e-308 3158e+308

double
double real number type occupies 64 bits (1 sign bit, 11 exponent bits and 52 mantissa bits).

float
float real number type occupies 32 bits (1 sign bit, 8 exponent bits and 23 mantissa bits).

vector
One-dimensional array of double type numbers. Memory for data is allocated dynamically. Vector
properties can be obtained using the methods, while the vector size can be changed. The
vector<double> entry can be used in template functions.

vectorf
One-dimensional array of float type numbers can be used instead of vector if the loss of precision does
not matter. The vector<float> entry can be used in template functions.

vectorc
One-dimensional array of complex type numbers is meant to handle complex numbers. The
vector<complex> entry can be used in template functions. Operations on vectorc type vectors are not
implemented yet.

matrix
Matrix is a two-dimensional array of double type numbers. Memory for matrix elements is distributed
dynamically. Matrix properties can be obtained using the methods, while the matrix shape can be
changed. The matrix<double> entry can be used in template functions.

© 2000-2025, MetaQuotes Ltd.


95 Language Basics

matrixf
Two-dimensional array of float type numbers can be used instead of matrix if the loss of precision
does not matter. The matrix<float> entry can be used in template functions.

matrixc
Two-dimensional array of complex type numbers is meant to handle complex numbers. The
matrix<complex> entry can be used in template functions. Operations on matrixc type matrices are
not implemented yet.
The double name means that the accuracy of these numbers is twice the accuracy of the float type
numbers. In most cases, the double type is the most convenient one. In many cases the limited
precision of float numbers is not enough. The reason why the float type is still used is saving the
memory (this is important for large arrays of real numbers).
Floating-point constants consist of an integer part, a point (.) and the fractional part. The integer 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 is more compact
than the traditional one.
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

It should be remembered that real numbers are stored in memory with some limited accuracy in the
binary system, while generally the decimal notation is used. That's why many numbers that are
precisely represented in the decimal system can be written only as an infinite fraction in the binary
system.
Forexample, numbers 0.3 and 0.7 are represented in the computer as infinite fractions, while the
number of 0.25 is stored exactly, because it represents the power of two.

© 2000-2025, MetaQuotes Ltd.


96 Language Basics

In this regard, it is strongly recommended not to compare 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 some 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
}

Note that the value of epsilon in the above example can not be less than the predefined constant
DBL _EPS ILON. The value of this constant is 2.2204460492503131e-016. The constant corresponding to

© 2000-2025, MetaQuotes Ltd.


97 Language Basics

the float type is FLT_EPS ILON = 1.192092896e-07. The meaning of these values is the following: it is
the lowest value that satisfies the condition 1.0 + DBL_EPS ILON! = 1.0 (for numbers of float type 1.0
+ FLT_EPS ILON! = 1.0).
The second way offers comparing the normalized difference of two real numbers with zero. It's
meaningless to compare the difference of normalized numbers with a zero, because any mathematical
operation with normalized numbers gives a non-normalized result.
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
}

S ome operations of the mathematical co-processor can result in the invalid real number, which can't be
used in mathematical operations and operations of comparison, because the result of operations with
invalid real numbers is undefined. For example, when trying to calculate the arcsine of 2, the result is
the negative infinity.
Example:

double abnormal = MathArcsin(2.0);


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

Besides the minus infinity there is the plus infinity and NaN (not a number). To determine that this
number is invalid, you can use MathIs ValidNumber(). According to the IEEE standard, they have a
special machine representation. For example, plus infinity for the double type has the bit
representation of 0x7FF0 0000 0000 0000.
Examples:

struct str1
{
double d;
};
struct str2
{

© 2000-2025, MetaQuotes Ltd.


98 Language Basics

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 non-number SNaN
s1=s2;
printf("3. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF8000000000000; // smallest non-number QNaN
s1=s2;
printf("4. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FFF000000000000; // greatest non-number QNaN
s1=s2;
printf("5. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF0000000000000; // Positive infinity 1.#INF and smallest non-number 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;

© 2000-2025, MetaQuotes Ltd.


99 Language Basics

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
DoubleToS tring, NormalizeDouble, Numeric Type Constants

© 2000-2025, MetaQuotes Ltd.


100 Language Basics

Complex number (complex)


The built-in complex type is a structure with two double fields :
struct complex
{
double real; // Real part
double imag; // Imaginary part
};

The " complex" type can be passed by value as a parameter for MQL5 functions (in contrast to ordinary
structures, which are only passed by reference). For functions imported from DLLs, the " complex" type
must be passed only by reference.
The 'i' suffix is used to describe complex constants :
complex square(complex c)
{
return(c*c);
}
void OnStart()
{
Print(square(1+2i)); // A constant is passed as a parameter
}
// "(-3,4)" will be output, which is a string representation of the complex number

Only simple operations are currently available for complex numbers : =, +, -, *, /, +=, -=, *=, /=, ==,!=.
S upport for additional mathematical functions will be added later, enabling the calculation of the
absolute value, sine, cosine and others.

vectorc
One-dimensional array of complex type numbers is meant to handle complex numbers. The
vector<complex> entry can be used in template functions. Operations on vectorc type vectors are not
implemented yet.

matrixc
Two-dimensional array of complex type numbers is meant to handle complex numbers. The
matrix<complex> entry can be used in template functions. Operations on matrixc type matrices are
not implemented yet.

© 2000-2025, MetaQuotes Ltd.


101 Language Basics

String Type
The string type is used for storing text strings. A text string is a sequence of characters in the
Unicode format with the final zero at the end of it. A string constant can be assigned to a string
variable. A string constant is a sequence of Unicode characters enclosed in double quotes : " This is a
string constant" .
If you need to include a double quote (" ) into a string, the backslash character (\) must be put before
it. Any special character constants can be written in a string, if the backslash character (\) is typed
before them.
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";

To make the source code readable, long constant strings can be split into parts without addition
operation. During compilation, these parts will be combined into one long string:
//--- Declare a long constant string
string HTML_head="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\""
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
"<head>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"
"<title>Trade Operations Report</title>\n"
"</head>";
//--- Output the constant string into log
Print(HTML_head);
}

Built-in string type methods


S trings
can be handled by string functions, conversion functions and built-in methods of string type
provided in the table:

String method Analog Description

Constructor string(const int len) Constructs a string of a specified


string[] length both for reading and
Provides access to the string
writing. The index should be within
element by a specified index
BufferS ize()

© 2000-2025, MetaQuotes Ltd.


102 Language Basics

String method Analog Description

static string string.Init(const int len, Initializes a string using specified


S tringInit
const ushort character); symbols with a specified size
void string.Fill(const ushort Fills
in the string with a specified
S tring Fill
character); symbol
R eturns the number of characters in
int string.Len(); S tringLen
a string
R eturns the size of a buffer
int string.BufferS ize(); S tring BufferLen
distributed for a string
bool string.S etLen(const int S ets a specified length (in
S tring S etLength
new_len); characters) for a string
bool string.Reserve(const int R eserves the buffer of a specified
S tring R eserve
buffer_len); size for a string in memory
bool string.Add(const string Adds a specified substring to the
S tring Add
substring); end
int string.Concatenate(const scalar Forms a string consisting of passed
S tringConcatenate
val1, const scalar val2...); parameters
array string.S plit(const ushort
R eturnsa string array by a specified
separator, const bool S tring S plit
separator
long_separator);
Compares with a specified string
and returns 1 if the first string
int string.Compare(const string str, exceeds the second one; 0 - if the
S tringCompare
const bool case_sensivity); strings are equal; -1 (minus one) - if
the first string is less than the
second one
string string.S ubstr(const int R etrieves a substring from a
S tring S ubstr
start_pos, const int len); specified position
int string.Find(const string substr, R eturnsan index of the position the
S tring Find
const int pos); necessary substring starts from
void string.ToLower(); S tringToLower Converts all characters to lower case
void string.ToUpper(); S tringToUpper Converts all characters to upper case
Deletes spaces, as well as carriage
int string.TrimLeft(); S tringTrimLeft movement and tabulation characters
to the left
Deletes spaces, as well as carriage
int string.TrimRight() S tringTrimR ight movement and tabulation characters
to the right
void string.Double(const double var, Converts a string to a double type
DoubleToS tring
const int digits =8); number

© 2000-2025, MetaQuotes Ltd.


103 Language Basics

String method Analog Description

Converts the enumeration value of


void string.Enum(const enum value); EnumToS tring
any type into a string
void string.Integer(const int value,
Converts a string to a long type
const int str_len=0, const ushort IntegerToS tring
number
fill=' ');
void string.CharArray(const uchar
Converts part of the uchar type
array[], const int start_pos =0, const CharArrayToS tring
array to a string
int len=-1, const uint cp=CP_ACP);
void string.S hortArray(const ushort
Copies part of the ushort type array
array[], const int start_pos =0, const S hortArrayToS tring
to a string
int len=-1);
void string.Time(const datetime
Converts datetime to the
dt,const int mode=TIM E_DATE|
TimeToS tring " yyyy.mm.dd hh:mi" format string.
TIM E_MINUTES );
void string.Format(const string Formats the obtained parameters
S tring Format
format_str); into a string

See also
Conversion Functions, S tring Functions, FileOpen, FileReadS tring, FileW riteS tring

© 2000-2025, MetaQuotes Ltd.


104 Language Basics

Structures, Classes and Interfaces


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

Structure Declaration

The structure data type is determined by the following description:


struct structure_name
{
elements_description
};

The structure name can't be used as an identifier (name of a variable or function). It should be noted
that in MQL5 structure elements follow one another directly, without alignment. In C++ such an order
is made to the compiler using the following instruction:
#pragma pack(1)

If you want to do another alignment in the structure, use auxiliary members, " fillers " to the right size.
Example:

struct trade_settings
{
uchar slippage; // value of the permissible slippage-size 1 byte
char reserved1; // skip 1 byte
short reserved2; // skip 2 bytes
int reserved4; // another 4 bytes are skipped. ensure alignment of the boundary 8 bytes
double take; // values of the price of profit fixing
double stop; // price value of the protective stop
};

S uch a description of aligned structures is necessary only for transferring to imported dll-functions.
Attention: This example illustrates incorrectly designed data. It would be better first to declare the
take and stop large data of the double type, and then declare the slippage member of the uchar type.
In this case, the internal representation of data will always be the same regardless of the value
specified in #pragma pack().
If a structure contains variables of the string type and/or object of a dynamic array, the compiler
assigns an implicit constructor to such a structure. This constructor resets all the structure members
of string type and correctly initializes objects of the dynamic array.

Simple Structures

S tructuresthat do not contain strings, class objects, pointers and objects of dynamic arrays are called
simple structures. Variables of simple structures, as well as their arrays can be passed as parameters
to functions imported from DLL.

© 2000-2025, MetaQuotes Ltd.


105 Language Basics

Copying of simple structures is allowed only in two cases :


· If the objects belong to the same structure type
· if the objects are connected by the lineage meaning that one structure is a descendant of another.
To provide an example, let's develop the CustomM qlTick custom structure with its contents identical to
the built-in M qlTick one. The compiler does not allow copying the M qlTick object value to the
CustomM qlTick type object. Direct typecasting to the necessary type also causes the compilation error:
//--- copying simple structures of different types is forbidden
my_tick1=last_tick; // compiler returns an error here

//--- typecasting structures of different types to each other is forbidden as well


my_tick1=(CustomMqlTick)last_tick;// compiler returns an error here

Therefore, only one option is left – copying the values of the structure elements one by one. It is still
allowed to copy the values of the same type of CustomM qlTick.
CustomMqlTick my_tick1,my_tick2;
//--- it is allowed to copy the objects of the same type of CustomMqlTick the following way
my_tick2=my_tick1;

//--- create an array out of the objects of the simple CustomMqlTick structure and write valu
CustomMqlTick arr[2];
arr[0]=my_tick1;
arr[1]=my_tick2;

The ArrayPrint() function is called for a check to display the arr[] array value in the journal.
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- develop the structure similar to the built-in MqlTick
struct CustomMqlTick
{
datetime time; // Last price update time
double bid; // Current Bid price
double ask; // Current Ask price
double last; // Current price of the last trade (Last)
ulong volume; // Volume for the current Last price
long time_msc; // Last price update time in milliseconds
uint flags; // Tick flags
};
//--- get the last tick value
MqlTick last_tick;
CustomMqlTick my_tick1,my_tick2;
//--- attempt to copy data from MqlTick to CustomMqlTick
if(SymbolInfoTick(Symbol(),last_tick))
{

© 2000-2025, MetaQuotes Ltd.


106 Language Basics

//--- copying unrelated simple structures is forbidden


//1. my_tick1=last_tick; // compiler returns an error here

//--- typecasting unrelated structures to each other is forbidden as well


//2. my_tick1=(CustomMqlTick)last_tick;// compiler returns an error here

//--- therefore, copy the structure members one by one


my_tick1.time=last_tick.time;
my_tick1.bid=last_tick.bid;
my_tick1.ask=last_tick.ask;
my_tick1.volume=last_tick.volume;
my_tick1.time_msc=last_tick.time_msc;
my_tick1.flags=last_tick.flags;

//--- it is allowed to copy the objects of the same type of CustomMqlTick the following way
my_tick2=my_tick1;

//--- create an array out of the objects of the simple CustomMqlTick structure and write valu
CustomMqlTick arr[2];
arr[0]=my_tick1;
arr[1]=my_tick2;
ArrayPrint(arr);
//--- example of displaying values of the array containing the objects of CustomMqlTick type
/*
[time] [bid] [ask] [last] [volume] [time_msc] [flags]
[0] 2017.05.29 15:04:37 1.11854 1.11863 +0.00000 1450000 1496070277157 2
[1] 2017.05.29 15:04:37 1.11854 1.11863 +0.00000 1450000 1496070277157 2
*/
}
else
Print("SymbolInfoTick() failed, error = ",GetLastError());
}

The second example shows the features of copying simple structures by the lineage. S uppose that we
have the Animal basic structure, from which the Cat and Dog structures are derived. W e can copy the
Animal and Cat objects, as well as the Animal and Dog objects to each other but we cannot copy Cat
and Dog to each other, although both are descendants of the Animal structure.
//--- structure for describing dogs
struct Dog: Animal
{
bool hunting; // hunting breed
};
//--- structure for describing cats
struct Cat: Animal
{
bool home; // home breed
};
//--- create objects of child structures

© 2000-2025, MetaQuotes Ltd.


107 Language Basics

Dog dog;
Cat cat;
//--- can be copied from ancestor to descendant (Animal ==> Dog)
dog=some_animal;
dog.swim=true; // dogs can swim
//--- you cannot copy objects of child structures (Dog != Cat)
cat=dog; // compiler returns an error

Complete example code:


//--- basic structure for describing animals
struct Animal
{
int head; // number of heads
int legs; // number of legs
int wings; // number of wings
bool tail; // tail
bool fly; // flying
bool swim; // swimming
bool run; // running
};
//--- structure for describing dogs
struct Dog: Animal
{
bool hunting; // hunting breed
};
//--- structure for describing cats
struct Cat: Animal
{
bool home; // home breed
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- create and describe an object of the basic Animal type
Animal some_animal;
some_animal.head=1;
some_animal.legs=4;
some_animal.wings=0;
some_animal.tail=true;
some_animal.fly=false;
some_animal.swim=false;
some_animal.run=true;
//--- create objects of child types
Dog dog;
Cat cat;
//--- can be copied from ancestor to descendant (Animal ==> Dog)

© 2000-2025, MetaQuotes Ltd.


108 Language Basics

dog=some_animal;
dog.swim=true; // dogs can swim
//--- you cannot copy objects of child structures (Dog != Cat)
//cat=dog; // compiler returns an error here
//--- therefore, it is possible to copy elements one by one only
cat.head=dog.head;
cat.legs=dog.legs;
cat.wings=dog.wings;
cat.tail=dog.tail;
cat.fly=dog.fly;
cat.swim=false; // cats cannot swim
//--- it is possible to copy the values from descendant to ancestor
Animal elephant;
elephant=cat;
elephant.run=false;// elephants cannot run
elephant.swim=true;// elephants can swim
//--- create an array
Animal animals[4];
animals[0]=some_animal;
animals[1]=dog;
animals[2]=cat;
animals[3]=elephant;
//--- print out
ArrayPrint(animals);
//--- execution result
/*
[head] [legs] [wings] [tail] [fly] [swim] [run]
[0] 1 4 0 true false false true
[1] 1 4 0 true false true true
[2] 1 4 0 true false false false
[3] 1 4 0 true false true false
*/
}

Anotherway to copy simple types is using a union. The objects of the structures should be members of
the same union – see the example in union.

Access to Structure Members

The name of a structure becomes a new data type, so you can declare variables of this type. The
structure can be declared only once within a project. The structure members are accessed using the
point operation (.).
Example:

struct trade_settings
{
double take; // values of the profit fixing price
double stop; // value of the protective stop price
uchar slippage; // value of the acceptable slippage

© 2000-2025, MetaQuotes Ltd.


109 Language Basics

};
//--- create up and initialize a variable of the trade_settings type
trade_settings my_set={0.0,0.0,5};
if (input_TP>0) my_set.take=input_TP;

'pack' for aligning structure and class fields

The special pack attribute allows setting the alignment of structure or class fields.
pack([n])

where n is one of the following values : 1, 2, 4, 8 or 16. It may be absent.


Example:

struct pack(sizeof(long)) MyStruct


{
// structure members are to be aligned to the 8-byte boundary
};
or
struct MyStruct pack(sizeof(long))
{
// structure members are to be aligned to the 8-byte boundary
};

'pack (1)'
is applied by default for structures. This means that the structure members are located one
after another in memory, and the structure size is equal to the sum of its members ' size.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- simple structure with no alignment
struct Simple_Structure
{
char c; // sizeof(char)=1
short s; // sizeof(short)=2
int i; // sizeof(int)=4
double d; // sizeof(double)=8
};
//--- declare a simple structure instance
Simple_Structure s;
//--- display the size of each structure member
Print("sizeof(s.c)=",sizeof(s.c));
Print("sizeof(s.s)=",sizeof(s.s));
Print("sizeof(s.i)=",sizeof(s.i));
Print("sizeof(s.d)=",sizeof(s.d));
//--- make sure the size of POD structure is equal to the sum of its members' size

© 2000-2025, MetaQuotes Ltd.


110 Language Basics

Print("sizeof(simple_structure)=",sizeof(simple_structure));
/*
Result:
sizeof(s.c)=1
sizeof(s.s)=2
sizeof(s.i)=4
sizeof(s.d)=8
sizeof(simple_structure)=15
*/
}

Alignment of the structure fields may be needed when exchanging data with third-party libraries
(*.DLL) where such alignment is applied.
Let's use some examples to show how alignment works. We will apply a structure consisting of four
members with no alignment.
//--- simple structure with no alignment
struct Simple_Structure pack() // no size is specified, alignment to the boundary of 1 byte is t
{
char c; // sizeof(char)=1
short s; // sizeof(short)=2
int i; // sizeof(int)=4
double d; // sizeof(double)=8
};
//--- declare a simple structure instance
Simple_Structure s;

S tructure fields are to be located in memory one after another according to the declaration order and
type size. The structure size is 15, while an offset to the structure fields in the arrays is undefined.

Now declare the same structure with the alignment of 4 bytes and run the code.
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- simple structure with the 4-byte alignment
struct Simple_Structure pack(4)
{
char c; // sizeof(char)=1
short s; // sizeof(short)=2
int i; // sizeof(int)=4
double d; // sizeof(double)=8
};

© 2000-2025, MetaQuotes Ltd.


111 Language Basics

//--- declare a simple structure instance


Simple_Structure s;
//--- display the size of each structure member
Print("sizeof(s.c)=",sizeof(s.c));
Print("sizeof(s.s)=",sizeof(s.s));
Print("sizeof(s.i)=",sizeof(s.i));
Print("sizeof(s.d)=",sizeof(s.d));
//--- make sure the size of POD structure is now not equal to the sum of its members' size
Print("sizeof(simple_structure)=",sizeof(simple_structure));
/*
Result:
sizeof(s.c)=1
sizeof(s.s)=2
sizeof(s.i)=4
sizeof(s.d)=8
sizeof(simple_structure)=16 // structure size has changed
*/
}

The structure size has changed so that all members of 4 bytes and more has an offset from the
beginning of the structure multiple of 4 bytes. S maller members are to be aligned to their own size
boundary (for example, 2 for 'short'). This is how it looks (the added byte is shown in gray).

In this case, 1 byte is added after the s.c member, so that the s.s (sizeof(short)==2) field has the
boundary of 2 bytes (alignment for 'short' type).
The offset to the beginning of the structure in the array is also aligned to the 4-byte boundary, i.e. the
addresses of the a[0], a[1] and a[n] elements are to be multiple of 4 bytes for S imple_S tructure arr[].
Let's consider two more structures consisting of similar types with 4-bytes alignment but different
member order. In the first structure, the members are located in type size ascending order.
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- simple structure aligned to the 4-byte boundary
struct CharShortInt pack(4)
{
char c; // sizeof(char)=1
short s; // sizeof(short)=2
int i; // sizeof(double)=4
};

© 2000-2025, MetaQuotes Ltd.


112 Language Basics

//--- declare a simple structure instance


CharShortInt ch_sh_in;
//--- display the size of each structure member
Print("sizeof(ch_sh_in.c)=",sizeof(ch_sh_in.c));
Print("sizeof(ch_sh_in.s)=",sizeof(ch_sh_in.s));
Print("sizeof(ch_sh_in.i)=",sizeof(ch_sh_in.i));

//--- make sure the size of POD structure is equal to the sum of its members' size
Print("sizeof(CharShortInt)=",sizeof(CharShortInt));
/*
Result:
sizeof(ch_sh_in.c)=1
sizeof(ch_sh_in.s)=2
sizeof(ch_sh_in.i)=4
sizeof(CharShortInt)=8
*/
}

As we can see, the structure size is 8 and consists of the two 4-byte blocks. The first block contains
the fields with 'char' and 'short' types, while the second one contains the field with 'int' type.

Now let's turn the first structure into the second one, which differs only in the field order, by moving
the 'short' type member to the end.
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- simple structure aligned to the 4-byte boundary
struct CharIntShort pack(4)
{
char c; // sizeof(char)=1
int i; // sizeof(double)=4
short s; // sizeof(short)=2
};
//--- declare a simple structure instance
CharIntShort ch_in_sh;
//--- display the size of each structure member
Print("sizeof(ch_in_sh.c)=",sizeof(ch_in_sh.c));
Print("sizeof(ch_in_sh.i)=",sizeof(ch_in_sh.i));
Print("sizeof(ch_in_sh.s)=",sizeof(ch_in_sh.s));
//--- make sure the size of POD structure is equal to the sum of its members' size
Print("sizeof(CharIntShort)=",sizeof(CharIntShort));
/*
Result:

© 2000-2025, MetaQuotes Ltd.


113 Language Basics

sizeof(ch_in_sh.c)=1
sizeof(ch_in_sh.i)=4
sizeof(ch_in_sh.s)=2
sizeof(CharIntShort)=12
*/
}

Although the structure content has not changed, altering the member sequence has increased its size.

Alignment should also be considered when inheriting. Let's demonstrate this using the simple Parent
structure having a single 'char' type member. The structure size without alignment is 1.
struct Parent
{
char c; // sizeof(char)=1
};

Let's create the Children child class featuring the 'short' (sizeof(short)=2) type member.
struct Children pack(2) : Parent
{
short s; // sizeof(short)=2
};

As a result, when setting alignment to 2 bytes, the structure size is equal to 4, although the size of its
members is 3. In this example, 2 bytes are to be allocated to the Parent class, so that the access to
the 'short' field of the child class is aligned to 2 bytes.
The knowledge of how memory is allocated for the structure members is necessary if an MQL5
application interacts with third-party data by writing/reading on the files or streams level.
The MQL5\Include\W inAPI directory of the S tandard Library contains the functions for working with the
W inAPI functions. These functions apply the structures with a specified alignment for the cases when
it is required for working with W inAPI.
offsetof is a special command directly related to the pack attribute. It allows us to obtain a member
offset from the beginning of the structure.
//--- declare the Children type variable
Children child;
//--- detect offsets from the beginning of the structure
Print("offsetof(Children,c)=",offsetof(Children,c));
Print("offsetof(Children,s)=",offsetof(Children,s));
/*
Result:
offsetof(Children,c)=0
offsetof(Children,s)=2
*/

© 2000-2025, MetaQuotes Ltd.


114 Language Basics

Specifier 'final'

The use of the 'final' specifier during structure declaration prohibits further inheritance from this
structure. If a structure requires no further modifications, or modifications are not allowed for
security reasons, declare this structure with the 'final' modifier. In addition, all the members of the
structure will also be implicitly considered final.
struct settings final
{
//--- Structure body
};

struct trade_settings : public settings


{
//--- Structure body
};

If you try to inherit from a structure with the 'final' modifier as shown in the above example, the
compiler will return an error:
cannot inherit from 'settings' as it has been declared as 'final'
see declaration of 'settings'

Classes
Classes differ from structures in the following:
· the keyword class is used in declaration;
· by default, all class members have access specifier private, unless otherwise indicated. Data-
members of the structure have the default type of access as public, unless otherwise indicated;
· class objects always have a table of virtual functions, even if there are no virtual functions declared
in the class. S tructures cannot have virtual functions ;
· the new operator can be applied to class objects ; this operator cannot be applied to structures ;
· classes can be inherited only from classes, structures can be inherited only from structures.
Classes and structures can have an explicit constructor and destructor. If your constructor is explicitly
defined, the initialization of a structure or class variable using the initializing sequence is impossible.
Example:

struct trade_settings
{
double take; // values of the profit fixing price
double stop; // value of the protective stop price
uchar slippage; // value of the acceptable slippage
//--- 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 initialization is impossible
trade_settings my_set={0.0,0.0,5};

© 2000-2025, MetaQuotes Ltd.


115 Language Basics

Constructors and Destructors

A constructor is a special function, which is called automatically when creating an object of a structure
or class and is usually used to initialize class members. Further we will talk only about classes, while
the same applies to structures, unless otherwise indicated. The name of a constructor must match the
class name. The constructor has no return type (you can specify the void type).
Defined class members – strings, dynamic arrays and objects that require initialization – will be in any
case initialized, regardless of whether there is a constructor.
Each class can have multiple constructors, differing by the number of parameters and the initialization
list. A constructor that requires specifying parameters is called a parametric constructor.
A constructor with no parameters is called a default constructor. If no constructors are declared in a
class, the compiler creates a default constructor during compilation.
//+------------------------------------------------------------------+
//| A class for working with a date |
//+------------------------------------------------------------------+
class MyDateClass
{
private:
int m_year; // Year
int m_month; // Month
int m_day; // Day of the month
int m_hour; // Hour in a day
int m_minute; // Minutes
int m_second; // Seconds
public:
//--- Default constructor
MyDateClass(void);
//--- Parametric constructor
MyDateClass(int h,int m,int s);
};

A constructor can be declared in the class description and then its body can be defined. For example,
two constructors of MyDateClass can be defined the following way:
//+------------------------------------------------------------------+
//| Default constructor |
//+------------------------------------------------------------------+
MyDateClass::MyDateClass(void)
{
//---
MqlDateTime mdt;
datetime t=TimeCurrent(mdt);
m_year=mdt.year;
m_month=mdt.mon;
m_day=mdt.day;

© 2000-2025, MetaQuotes Ltd.


116 Language Basics

m_hour=mdt.hour;
m_minute=mdt.min;
m_second=mdt.sec;
Print(__FUNCTION__);
}
//+------------------------------------------------------------------+
//| Parametric constructor |
//+------------------------------------------------------------------+
MyDateClass::MyDateClass(int h,int m,int s)
{
MqlDateTime mdt;
datetime t=TimeCurrent(mdt);
m_year=mdt.year;
m_month=mdt.mon;
m_day=mdt.day;
m_hour=h;
m_minute=m;
m_second=s;
Print(__FUNCTION__);
}

In the default constructor, all members of the class are filled using the TimeCurrent() function. In the
parametric constructor only hour values are filled in. Other members of the class (m_year, m_month
and m_day) will be automatically initialized with the current date.
The default constructor has a special purpose when initializing an array of objects of its class. The
constructor, all parameters of which have default values, is not a default constructor. Here is an
example:
//+------------------------------------------------------------------+
//| A class with a default constructor |
//+------------------------------------------------------------------+
class CFoo
{
datetime m_call_time; // Time of the last object call
public:
//--- Constructor with a parameter that has a default value is not a default constructor
CFoo(const datetime t=0){m_call_time=t;};
//--- Copy constructor
CFoo(const CFoo &foo){m_call_time=foo.m_call_time;};

string ToString(){return(TimeToString(m_call_time,TIME_DATE|TIME_SECONDS));};
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// CFoo foo; // This variant cannot be used - a default constructor is not set
//--- Possible options to create the CFoo object

© 2000-2025, MetaQuotes Ltd.


117 Language Basics

CFoo foo1(TimeCurrent()); // An explicit call of a parametric constructor


CFoo foo2(); // An explicit call of a parametric constructor with a default par
CFoo foo3=D'2009.09.09'; // An implicit call of a parametric constructor
CFoo foo40(foo1); // An explicit call of a copy constructor
CFoo foo41=foo1; // An implicit call of a copy constructor
CFoo foo5; // An explicit call of a default constructor (if there is no defau
// then a parametric constructor with a default value is called)
//--- Possible options to receive CFoo pointers
CFoo *pfoo6=new CFoo(); // Dynamic creation of an object and receiving of a pointer to it
CFoo *pfoo7=new CFoo(TimeCurrent());// Another option of dynamic object creation
CFoo *pfoo8=GetPointer(foo1); // Now pfoo8 points to object foo1
CFoo *pfoo9=pfoo7; // pfoo9 and pfoo7 point to one and the same object
// CFoo foo_array[3]; // This option cannot be used - a default constructor is not speci
//--- Show the value of m_call_time
Print("foo1.m_call_time=",foo1.ToString());
Print("foo2.m_call_time=",foo2.ToString());
Print("foo3.m_call_time=",foo3.ToString());
Print("foo4.m_call_time=",foo4.ToString());
Print("foo5.m_call_time=",foo5.ToString());
Print("pfoo6.m_call_time=",pfoo6.ToString());
Print("pfoo7.m_call_time=",pfoo7.ToString());
Print("pfoo8.m_call_time=",pfoo8.ToString());
Print("pfoo9.m_call_time=",pfoo9.ToString());
//--- Delete dynamically created arrays
delete pfoo6;
delete pfoo7;
//delete pfoo8; // You do not need to delete pfoo8 explicitly, since it points to the automatic
//delete pfoo9; // You do not need to delete pfoo9 explicitly. since it points to the same obje
}

If you uncomment these strings


//CFoo foo_array[3]; // This variant cannot be used - a default constructor is not set

or
//CFoo foo_dyn_array[]; // This variant cannot be used - a default constructor is not set

then the compiler will return an error for them " default constructor is not defined" .
If a class has a user-defined constructor, the default constructor is not generated by the compiler. This
means that if a parametric constructor is declared in a class, but a default constructor is not declared,
you can not declare the arrays of objects of this class. The compiler will return an error for this script:
//+------------------------------------------------------------------+
//| A class without a default constructor |
//+------------------------------------------------------------------+
class CFoo
{
string m_name;
public:

© 2000-2025, MetaQuotes Ltd.


118 Language Basics

CFoo(string name) { m_name=name;}


};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Get the "default constructor is not defined" error during compilation
CFoo badFoo[5];
}

In this example, the CFoo class has a declared parametric constructor - in such cases, the compiler
does not create a default constructor automatically during compilation. At the same time when you
declare an array of objects, it is assumed that all objects should be created and initialized
automatically. During auto-initialization of an object, it is necessary to call a default constructor, but
since the default constructor is not explicitly declared and not automatically generated by the compiler,
it is impossible to create such an object. For this reason, the compiler generates an error at the
compilation stage.
There is a special syntax to initialize an object using a constructor. Constructor initializers (special
constructions for initialization) for the members of a struct or class can be specified in the
initialization list.
An initialization list is
a list of initializers separated by commas, which comes after the colon after the
list of parameters of a constructor and precedes the body (goes before an opening brace). There are
several requirements :
· Initialization lists can be used only in constructors ;
· Parent members cannot be initialized in the initialization list;
· The initialization list must be followed by a definition (implementation) of a function.
H ere is an example of several constructors for initializing class members.
//+------------------------------------------------------------------+
//| A class for storing the name of a character |
//+------------------------------------------------------------------+
class CPerson
{
string m_first_name; // First name
string m_second_name; // Second name
public:
//--- An empty default constructor
CPerson() {Print(__FUNCTION__);};
//--- A parametric constructor
CPerson(string full_name);
//--- A constructor with an initialization list
CPerson(string surname,string name): m_second_name(surname), m_first_name(name
void PrintName(){PrintFormat("Name=%s Surname=%s",m_first_name,m_second_name);};
};
//+------------------------------------------------------------------+
//| |

© 2000-2025, MetaQuotes Ltd.


119 Language Basics

//+------------------------------------------------------------------+
CPerson::CPerson(string full_name)
{
int pos=StringFind(full_name," ");
if(pos>=0)
{
m_first_name=StringSubstr(full_name,0,pos);
m_second_name=StringSubstr(full_name,pos+1);
}
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Get an error "default constructor is not defined"
CPerson people[5];
CPerson Tom="Tom Sawyer"; // Tom Sawyer
CPerson Huck("Huckleberry","Finn"); // Huckleberry Finn
CPerson *Pooh = new CPerson("Winnie","Pooh"); // Winnie the Pooh
//--- Output values
Tom.PrintName();
Huck.PrintName();
Pooh.PrintName();

//--- Delete a dynamically created object


delete Pooh;
}

In this case, the CPerson class has three constructors :


1. An explicit default constructor,
which allows creating an array of objects of this class ;
2. A constructor with one parameter, which gets a full name as a parameter and divides it to the
name and second name according to the found space;
3. A constructor with two parameters that contains an initialization list. Initializers -
m_second_name(surname) and m_first_name(name).
Note that the initialization using a list has replaced an assignment. Individual members must be
initialized as :
class_member (a list of expressions)

In the initialization list, members can go in any order, but all members of the class will be initialized
according to the order of their announcement. This means that in the third constructor, first the
m_first_name member will be initialized, as it is announced first, and only after it m_second_name is
initialized. This should be taken into account in cases where the initialization of some members of the
class depends on the values in other class members.
If a default constructor is not declared in the base class, and at the same time one or more
constructors with parameters are declared, you should always call one of the base class constructors in

© 2000-2025, MetaQuotes Ltd.


120 Language Basics

the initialization list. It goes through the comma as ordinary members of the list and will be called first
during object initialization, no matter where in the initialization list it is located.
//+------------------------------------------------------------------+
//| Base class |
//+------------------------------------------------------------------+
class CFoo
{
string m_name;
public:
//--- A constructor with an initialization list
CFoo(string name) : m_name(name) { Print(m_name);}
};
//+------------------------------------------------------------------+
//| Class derived from CFoo |
//+------------------------------------------------------------------+
class CBar : CFoo
{
CFoo m_member; // A class member is an object of the parent
public:
//--- A default constructor in the initialization list calls the constructor of a parent
CBar(): m_member(_Symbol), CFoo("CBAR") {Print(__FUNCTION__);}
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
CBar bar;
}

In this example, when creating the bar object, a default constructor CBar() will be called, in which first
a constructor for the parent CFoo is called, and then comes a constructor for the m_member class
member.
A destructor is a special function that is called automatically when a class object is destroyed. The
name of the destructor is written as a class name with a tilde (~). S trings, dynamic arrays and objects,
requiring deinitialization, will be de-initialized anyway, regardless of the destructor presence or
absence. If there is a destructor, these actions will be performed after calling the destructor.
Destructors are always virtual, regardless of whether they are declared with the virtual keyword or not.

Defining Class Methods

Class function-methods can be defined both inside the class and outside the class declaration. If the
method is defined within a class, then its body comes right after the method declaration.
Example:

class CTetrisShape
{

© 2000-2025, MetaQuotes Ltd.


121 Language Basics

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

Functions from S etR ightBorder(int border) to Draw() are declared and defined directly inside the
CTetris S hape class.
The CTetris S hape() constructor and methods CheckDown(int& pad_array[]), CheckLeft(int&
side_row[]) and CheckRight(int& side_row[]) are only declared inside the class, but not defined yet.
Definitions of these functions will be further in the code. In order to define the method outside the
class, the scope resolution operator is used, the class name is used as the scope.
Example:

//+------------------------------------------------------------------+
//| Constructor of the basic 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;

© 2000-2025, MetaQuotes Ltd.


122 Language Basics

m_right_border=0;
}
//+------------------------------------------------------------------+
//| Checking 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 Specifiers

W hen developing a new class, it is recommended to restrict access to the members from
the outside.
For this purpose k eywords private or protected are used. In this case, hidden data can
be accessed
only from function-methods of the same class. If the protected keyword is used, hidden
data can be
accessed also from methods of classes - inheritors of this class. The same method can be used to
restrict the access to functions-methods of a class.
If you need to completely open access to members and/or methods of a class, 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 of the well
int m_rows[FIELD_HEIGHT]; // Numbering of the well rows
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();

© 2000-2025, MetaQuotes Ltd.


123 Language Basics

void CheckAndDeleteRows();
void LabelOver();
};

Any class members and methods declared after the specifier public: (and before the next access
specifier) are available in any reference to the class object by the program. In this example these are
the following members : functions CTetris Field(), Init(), Deinit(), Down(), Left(), Right(), Rotate() and
Drop().

Any members that are declared after the access specifier to the elements private: (and before the
next access specifier) are available only to members-functions of this class. S pecifiers of access to
elements always end with a colon (:) and can appear in the class definition many times.
Any class members declared after the protected: access specifier (and up to the next access specifier)
are available only to members-functions of this class and members-functions of the class descendants.
W hen attempting to refer to the members featuring the private and protected specifiers from the
outside, we get the compilation stage error. Example:
class A
{
protected:
//--- the copy operator is available only inside class A and its descendants
void operator=(const A &)
{
}
};
class B
{
//--- class A object declared
A a;
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare two B type variables
B b1, b2;
//--- attempt to copy one object into another
b2=b1;
}

W hen compiling the code, the error message is received — an attempt to call the remote copy
operator:
attempting to reference deleted function 'void B::operator=(const B&)' trash3.mq5 32 6

The second string below provides a more detailed description — the copy operator in class B was
explicitly deleted, since the unavailable copy operator of class A is called:
function 'void B::operator=(const B&)' was implicitly deleted because it invokes inaccessible fu

© 2000-2025, MetaQuotes Ltd.


124 Language Basics

Access to the members of the basis class can be redefined during inheritance in derived classes.

'delete' specifier

The delete specifier marks the class members-functions that cannot be used. This means if the
program refers to such a function explicitly or implicitly, the error is received at the compilation stage
already. For example, this specifier allows you to make parent methods unavailable in a child class.
The same result can be achieved if we declare the function in the private area of the parent class
(declarations in the private section). Here, using delete makes the code more readable and
manageable at the level of descendants.
class A
{
public:
A(void) {value=5;};
double GetValue(void) {return(value);}
private:
double value;
};
class B: public A
{
double GetValue(void)=delete;
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare the A type variable
A a;
Print("a.GetValue()=", a.GetValue());
//--- attempt to get value from the B type variable
B b;
Print("b.GetValue()=", b.GetValue()); // the compiler displays an error at this string
}

The compiler message:


attempting to reference deleted function 'double B::GetValue()'
function 'double B::GetValue()' was explicitly deleted here

The 'delete' specifier allows disabling auto casting or the copy constructor, which otherwise would have
to be hidden in the private section as well. Example:
class A
{
public:
void SetValue(double v) {value=v;}
//--- disable int type call
void SetValue(int) = delete;
//--- disable the copy operator

© 2000-2025, MetaQuotes Ltd.


125 Language Basics

void operator=(const A&) = delete;


private:
double value;
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare two A type variables
A a1, a2;
a1.SetValue(3); // error!
a1.SetValue(3.14); // OK
a2=a1; // error!
}

During the compilation, we get the error messages :


attempting to reference deleted function 'void A::SetValue(int)'
function 'void A::SetValue(int)' was explicitly deleted here
attempting to reference deleted function 'void A::operator=(const A&)'
function 'void A::operator=(const A&)' was explicitly deleted here

Specifier 'final'

The use of the 'final' specifier during class declaration prohibits further inheritance from this class. If
the class interface requires no further modifications, or modifications are not allowed for security
reasons, declare this class with the 'final' modifier. In addition, all the members of the class will also
be implicitly considered final.
class CFoo final
{
//--- Class body
};

class CBar : public CFoo


{
//--- Class body
};

If you try to inherit form a class with the 'final' specifier as shown in the above example, the compiler
will return an error:
cannot inherit from 'CFoo' as it has been declared as 'final'
see declaration of 'CFoo'

Unions (union)
Union isa special data type consisting of several variables sharing the same memory area. Therefore,
the union provides the ability to interpret the same bit sequence in two (or more) different ways.
Union declaration is similar to structure declaration and starts with the union k eyword.

union LongDouble

© 2000-2025, MetaQuotes Ltd.


126 Language Basics

{
long long_value;
double double_value;
};

Unlik ethe structure, various union members belong to the same memory area. In this example, the
union of LongDouble is declared with long and double type values sharing the same memory area.
Please note that it is impossible to make the union store a long integer value and a double real value
simultaneously (unlike a structure), since long_value and double_value variables overlap (in memory).
On the other hand, an MQL5 program is able to process data containing in the union as an integer
(long) or real (double) value at any time. Therefore, the union allows receiving two (or more) options
for representing the same data sequence.
During the union declaration, the compiler automatically allocates the memory area sufficient to store
the largest type (by volume) in the variable union. The same syntax is used for accessing the union
element as for the structures – point operator.
union LongDouble
{
long long_value;
double double_value;
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
LongDouble lb;
//--- get and display the invalid -nan(ind) number
lb.double_value=MathArcsin(2.0);
printf("1. double=%f integer=%I64X",lb.double_value,lb.long_value);
//--- largest normalized value (DBL_MAX)
lb.long_value=0x7FEFFFFFFFFFFFFF;
printf("2. double=%.16e integer=%I64X",lb.double_value,lb.long_value);
//--- smallest positive normalized (DBL_MIN)
lb.long_value=0x0010000000000000;
printf("3. double=%.16e integer=%.16I64X",lb.double_value,lb.long_value);
}
/* Execution result
1. double=-nan(ind) integer=FFF8000000000000
2. double=1.7976931348623157e+308 integer=7FEFFFFFFFFFFFFF
3. double=2.2250738585072014e-308 integer=0010000000000000
*/

S incethe unions allow the program to interpret the same memory data in different ways, they are
often used when an unusual type conversion is required.
The unions cannot be involved in the inheritance, and they also cannot have static members due to
their very nature. In all other aspects, the union behaves like a structure with all its members having a
zero offset. The following types cannot be the union members :

© 2000-2025, MetaQuotes Ltd.


127 Language Basics

· dynamic arrays
· strings
· pointers to objects and functions
· class objects
· structure objects having constructors or destructors
· structure objects having members from the points 1-5
S imilarto classes, the union is capable of having constructors and destructors, as well as methods. By
default, the union members are of public access type. In order to create private elements, use the
private keyword. All these possibilities are displayed in the example illustrating how to convert a color
of the color type to ARGB as does the ColorToARGB() function.
//+------------------------------------------------------------------+
//| Union for color(BGR) conversion to ARGB |
//+------------------------------------------------------------------+
union ARGB
{
uchar argb[4];
color clr;
//--- constructors
ARGB(color col,uchar a=0){Color(col,a);};
~ARGB(){};
//--- public methods
public:
uchar Alpha(){return(argb[3]);};
void Alpha(const uchar alpha){argb[3]=alpha;};
color Color(){ return(color(clr));};
//--- private methods
private:
//+------------------------------------------------------------------+
//| set the alpha channel value and color |
//+------------------------------------------------------------------+
void Color(color col,uchar alpha)
{
//--- set color to clr member
clr=col;
//--- set the Alpha component value - opacity level
argb[3]=alpha;
//--- interchange the bytes of R and B components (Red and Blue)
uchar t=argb[0];argb[0]=argb[2];argb[2]=t;
};
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- 0x55 means 55/255=21.6 % (0% - fully transparent)

© 2000-2025, MetaQuotes Ltd.


128 Language Basics

uchar alpha=0x55;
//--- color type is represented as 0x00BBGGRR
color test_color=clrDarkOrange;
//--- values of bytes from the ARGB union are accepted here
uchar argb[];
PrintFormat("0x%.8X - here is how the 'color' type look like for %s, BGR=(%s)",
test_color,ColorToString(test_color,true),ColorToString(test_color));
//--- ARGB type is represented as 0x00RRGGBB, RR and BB components are swapped
ARGB argb_color(test_color);
//--- copy the bytes array
ArrayCopy(argb,argb_color.argb);
//--- here is how it looks in ARGB representation
PrintFormat("0x%.8X - ARGB representation with the alpha channel=0x%.2x, ARGB=(%d,%d,%d,%d)",
argb_color.clr,argb_color.Alpha(),argb[3],argb[2],argb[1],argb[0]);
//--- add opacity level
argb_color.Alpha(alpha);
//--- try defining ARGB as 'color' type
Print("ARGB as color=(",argb_color.clr,") alpha channel=",argb_color.Alpha());
//--- copy the bytes array
ArrayCopy(argb,argb_color.argb);
//--- here is how it looks in ARGB representation
PrintFormat("0x%.8X - ARGB representation with the alpha channel=0x%.2x, ARGB=(%d,%d,%d,%d)",
argb_color.clr,argb_color.Alpha(),argb[3],argb[2],argb[1],argb[0]);
//--- check with the ColorToARGB() function results
PrintFormat("0x%.8X - result of ColorToARGB(%s,0x%.2x)",ColorToARGB(test_color,alpha),
ColorToString(test_color,true),alpha);
}
/* Execution result
0x00008CFF - here is how the color type looks for clrDarkOrange, BGR=(255,140,0)
0x00FF8C00 - ARGB representation with the alpha channel=0x00, ARGB=(0,255,140,0)
ARGB as color=(0,140,255) alpha channel=85
0x55FF8C00 - ARGB representation with the alpha channel=0x55, ARGB=(85,255,140,0)
0x55FF8C00 - result of ColorToARGB(clrDarkOrange,0x55)
*/

Interfaces
An interface allows determining specific functionality, which a class can then implement. In fact, an
interface is a class that cannot contain any members, and may not have a constructor and/or a
destructor. All methods declared in an interface are purely virtual, even without an explicit definition.
An interface is defined using the " interface" keyword. Example:
//--- Basic interface for describing animals
interface IAnimal
{
//--- The methods of the interface have public access by default
void Sound(); // The sound produced by the animal
};

© 2000-2025, MetaQuotes Ltd.


129 Language Basics

//+------------------------------------------------------------------+
//| The CCat class is inherited from the IAnimal interface |
//+------------------------------------------------------------------+
class CCat : public IAnimal
{
public:
CCat() { Print("Cat was born"); }
~CCat() { Print("Cat is dead"); }
//--- Implementing the Sound method of the IAnimal interface
void Sound(){ Print("meou"); }
};
//+------------------------------------------------------------------+
//| The CDog class is inherited from the IAnimal interface |
//+------------------------------------------------------------------+
class CDog : public IAnimal
{
public:
CDog() { Print("Dog was born"); }
~CDog() { Print("Dog is dead"); }
//--- Implementing the Sound method of the IAnimal interface
void Sound(){ Print("guaf"); }
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- An array of pointers to objects of the IAnimal type
IAnimal *animals[2];
//--- Creating child classes of IAnimal and saving pointers to them into an array
animals[0]=new CCat;
animals[1]=new CDog;
//--- Calling the Sound() method of the basic IAnimal interface for each child
for(int i=0;i<ArraySize(animals);++i)
animals[i].Sound();
//--- Deleting objects
for(int i=0;i<ArraySize(animals);++i)
delete animals[i];
//--- Execution result
/*
Cat was born
Dog was born
meou
guaf
Cat is dead
Dog is dead
*/
}

© 2000-2025, MetaQuotes Ltd.


130 Language Basics

Like with abstract classes, an interface object cannot be created without inheritance. An interface can
only be inherited from other interfaces and can be a parent for a class. An interface is always publicly
visible.
An interface cannot be declared within a class or structure declaration, but a pointer to the interface
can be saved in a variable of type void *. Generally speaking, a pointer to an object of any class can be
saved into a variable of type void *. In order to convert a void * pointer to a pointer to an object of a
particular class, use the dynamic_cast operator. If conversion is not possible, the result of the
dynamic_cast operation will be NULL.
See also
Object-Oriented Programming

© 2000-2025, MetaQuotes Ltd.


131 Language Basics

Dynamic Array Object


Dynamic Arrays

Maximum 4-dimension array can be declared. W hen declaring a dynamic array (an array of unspecified
value in the first pair of s quare brackets), the compiler automatically creates a variable of the above
structure (a dynamic array object) and provides a code for the correct initialization.
Dynamic arrays are automatically freed when going beyond the visibility area of the block they are
declared in.
Example:

double matrix[][10][20]; // 3-dimensional dynamic array


ArrayResize(matrix,5); // Set the size of the first dimension

Static Arrays

W hen all significant array dimensions are explicitly specified, the compiler pre-allocates the necessary
memory size. S uch an array is called static. Nevertheless, the compiler allocates additional memory for
the object of a dynamic array, which (object) is associated with the pre-allocated static buffer
(memory part for storing the array).
Creating a dynamic array object is due to the possible need to pass this static array as a parameter to
some function.
Examples:

double stat_array[5]; // 1-dimensional static array


some_function(stat_array);
...
bool some_function(double& array[])
{
if(ArrayResize(array,100)<0) return(false);
...
return(true);
}

Arrays in Structures

W hen a static array is declared as a member of a structure, a dynamic array object is not created.
This is done to ensure compatibility of data structures used in the W indows API.
H owever, static arrays that are declared as members of structures can also be passed to MQL5
functions. In this case, when passing the parameter, a temporary object of a dynamic array will be
created. S uch an object is linked with the static array - member of structure.
See also
Array Functions, Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and
Deleting Objects

© 2000-2025, MetaQuotes Ltd.


132 Language Basics

Matrices and vectors


Type vector is a special data type in MQL5, which enables operations with vectors. A vector is a one-
dimensional array of type double. It is one of the fundamental concepts of linear algebra, which is used
in many fields of science, including physics, geometry, and others. Vectors are used to solve systems
of linear equations, in 3D graphics and in other application areas. Vectors can be added and multiplied.
The length or distance between vectors can be obtained through the Norm. In programming, vectors
are usually represented by arrays of homogeneous elements, which may have no regular vector
operations, i.e. when arrays cannot be added or multiply, and they have no norm.
Vectors can be represented as row vectors and string vectors when working with matrices. Also,
vectors in linear algebra use the concepts of covariance and contravariance. These concepts do not
make any difference when writing an MQL5 code, as only the programmer decides what each object of
the vector type is. For example, it can be rotation, displacement or compression vector in 3D
graphics.
Generally speak ing,from the point of view of linear algebra, a number is also a vector, but in a one-
dimensional vector space. A vector itself can be considered as a special case of a matrix.
Type matrix is another special data type in MQL5 to represent matrices. A matrix is actually a two-
dimensional array of type double. Vectors and matrices have been introduced into MQL5 for easier
operations with certain types of data sets. W ith them, developers can benefit from the linear algebra
possibilities in a simple and math-like form. Matrices can be used to compactly write systems of linear
or differential equations. The number of matrix rows corresponds to the number of equations, while
the the number of columns is equal to the number of unknowns. As a result, systems of linear
equations can be solved through matrix operations.
The following data types exist:
· matrix — a matrix containing double elements.
· matrixf — a matrix containing float elements.
· matrixc — a matrix containing complex elements.
· vector — a vector containing double elements.
· vectorf — a vector containing float elements.
· vectorc — a vector containing complex elements.
Template functions support notations like matrix<double>, matrix<float>, vector<double>,
vector<float> instead of the corresponding types.
The following algebraic operations are defined for the matrices :
· Addition of same-size matrices
· Multiplication of suitable-size matrices : the number of columns in the left matrix must equal the
number of rows in the right matrix
· Matrix multiplication by a column vector; multiplication of a row vector by a matrix according to the
matrix multiplication rule. In this sense the vector is a special case of a matrix
· Matrix multiplication by a number, that is, by a scalar
Mathematics considers many different matrix types. For example, identity matrix, symmetric, s kew-
symmetric, upper and lower triangular matrices, and other types. Various Normal forms play an
important role in the matrix theory. They represent a certain canonical form of a matrix, which can be

© 2000-2025, MetaQuotes Ltd.


133 Language Basics

obtained by means of certain transformations. In practice, normal forms that have additional
properties, such as for example stability, are used.
The use of vectors and matrices, or rather, of special methods of the relevant types, enables the
creation of simpler, briefer and clearer code, which is close to mathematical notation. W ith these
methods, you can avoid the need to create nested loops or to mind correct indexing of arrays in
calculations. Therefore, the use of these methods increases reliability and speed in developing
complex programs.

List of matrix and vector methods


Types matrix and vector include methods that correspond to the relevant NumPy library methods.
Using these methods, you can translate algorithms and codes from Python to MQL5 with minimum
efforts. A lot of data processing tas ks, mathematical equations, neural networks and machine learning
tas ks can be solved using ready-made Python methods and libraries.

Analogous method
Method matrix/vector Description
in NumPy

void matrix.Eye(const int rows, Construct a matrix with ones on the


eye
const int cols, const int ndiag=0) diagonal and zeros elsewhere
Construct a s quare matrix with ones
void matrix.Identity(const int rows) identity
on the main diagonal
void matrix.Ones(const int rows, Construct a new matrix of given
ones
const int cols) rows and columns, filled with ones
void matrix.Zeros(const int rows, Construct a new matrix of given
zeros
const int cols) rows and columns, filled with zeros
Construct a new matrix of given
void matrix.Full(const int rows,
full rows and columns, filled with scalar
const int cols, const scalar value)
value
void matrix.Copy(const matrix a) copy Construct a copy of the given matrix
void matrix.FromBuffer(const int
rows, const int cols, const scalar Construct a matrix created from a 1-
frombuffer
array[], const int count=-1, const int dimensional array
offset=0)
void matrix.FromFile(const int rows,
condt int cols, const int file_handle, Construct a matrix from data in a
fromfile
const int count=-1, const int text or binary file
offset=0)
void vector.FromS tring(const string Construct a vector initialized from
fromstring
source, const string sep=" " ) text data in a string
void vector.Arange(const scalar
Construct evenly spaced values
start, const scalar stop, const scalar arange
within a given interval
step=1)

© 2000-2025, MetaQuotes Ltd.


134 Language Basics

Analogous method
Method matrix/vector Description
in NumPy

void matrix.Diag(const vector v, Extract a diagonal or construct a


diag
const int ndiag=0) diagonal matrix
Construct a matrix with ones at and
void matrix.Tri(const int rows, const
tri below the given diagonal and zeros
int cols, const int ndiag=0)
elsewhere
void matrix.Tril(const int rows, R eturna copy of a matrix with
const int cols, const scalar array[], tril elements above the k-th diagonal
const int ndiag=0) zeroed

void matrix.Triu(const int rows, R eturna copy of a matrix with the


const int cols, const scalar array[], triu elements below the k-th diagonal
const int ndiag=0) zeroed

void matrix.Vander(const vector v,


const int cols =-1, const bool vander Generate a Vandermonde matrix
increasing=false)
vector matrix.Row(const unsigned
R eturn a row vector
nrow)
vector matrix.Col(const unsigned
R eturn a column vector
ncol)
R eturn the number of rows in a
unsigned matrix.Rows()
matrix
R eturn the number of columns in a
unsigned matrix.Cols()
matrix
void matrix.Init() Initialize a matrix
R everse or permute the axes of a
matrix matrix.Transpose() transpose
matrix; returns the modified matrix
matrix matrix.Dot(const matrix b) dot Dot product of two matrices
matrix matrix.Inner(const matrix b) inner Inner product of two matrices
Compute the outer product of two
matrix matrix.Outer(const matrix b) outer
matrices
matrix matrix.MatMul(const matrix
matmul Matrix product of two matrices
b)
matrix matrix.MatrixPower(const int R aise a s quare matrix to the
matrix_power
power) (integer) power n
R eturn Kroneck er product of two
matrix matrix.Kron(const matrix b) k ron
matrices
bool matrix.Choles ky(matrix& L) choles ky R eturn the Choles k y decomposition

© 2000-2025, MetaQuotes Ltd.


135 Language Basics

Analogous method
Method matrix/vector Description
in NumPy

bool matrix.QR(matrix& Q, matrix& Compute the qr factorization of a


qr
R) matrix
bool matrix.SVD(matrix& U, matrix&
svd S ingular value decomposition
V, vector& singular_values)

bool matrix.Eig(matrix&
Compute the eigenvalues and right
eigen_vectors, vector& eig
eigenvectors of a s quare matrix
eigen_values)
bool matrix.EigH(matrix&
R eturn the eigenvalues and
eigen_vectors, vector& eigh
eigenvectors of a Hermitian matrix
eigen_values)
bool matrix.EigVals(vector& Compute the eigenvalues of a
eigvals
eigen_values) general matrix
bool matrix.EigVals H(vector& Compute the eigenvalues of a
eigvalsh
eigen_values) H ermitian matrix

LU decomposition of a matrix as the


bool matrix.LU(matrix& L, matrix&
product of a lower triangular matrix
U)
and an upper triangular matrix
LUP decomposition with partial
bool matrix.LUP(matrix& L, matrix& pivoting, which refers to LU
U, matrix & P) decomposition with row
permutations only: PA=LU
double matrix.Norm(const norm) norm R eturn matrix or vector norm
Compute the condition number of a
double matrix.Cond(const norm) cond
matrix
Compute spectrum of a matrix as
vector matrix.S pectrum() the set of its eigenvalues from the
product AT*A
Compute the determinant of an
double matrix.Det() det
array
R eturn matrix rank of array using
int matrix.Rank() matrix_rank
the Gaussian method
Compute the sign and logarithm of
int matrix.S LogDet(int& sign) slogdet
the determinant of an array
R eturnthe sum along diagonals of
double matrix.Trace() trace
the matrix
S olvea linear matrix equation, or
vector matrix.S olve(const vector b) solve
system of linear algebraic equations

© 2000-2025, MetaQuotes Ltd.


136 Language Basics

Analogous method
Method matrix/vector Description
in NumPy

R eturn the least-s quares solution of


vector matrix.LstSq(const vector b) lsts q linear algebraic equations (for non-
s quare or degenerate matrices)
Compute the (multiplicative) inverse
matrix matrix.Inv() inv
of a matrix
Compute the pseudo-inverse of a
matrix matrix.PInv() pinv matrix by the Moore-Penrose
method
int matrix.Compare(const matrix
matrix_c, const double epsilon)
int matrix.Compare(const matrix
Compare the elements of two
matrix_c, const int digits)
matrices /vectors with the specified
int vector.Compare(const vector
precision
vector_c, const double epsilon)
int vector.Compare(const vector
vector_c, const int digits)
double matrix.Flat(const ulong
index) Allows addressing a matrix element
flat
bool matrix.Flat(const ulong through one index instead of two
index,const double value)
double vector.ArgMax()
double matrix.ArgMax() R eturn the index of the maximum
argmax
vector matrix.ArgMax(const int value
axis)
double vector.ArgMin()
R eturn the index of the minimum
double matrix.ArgMin() argmin
value
vector matrix.ArgMin(const int axis)
double vector.Max()
R eturn the maximum value in a
double matrix.Max() max
matrix/vector
vector matrix.Max(const int axis)
double vector.Mean()
Compute the arithmetic mean of
double matrix.Mean() mean
element values
vector matrix.Mean(const int axis)
double vector.Min()
R eturn the minimum value in a
double matrix.Min() min
matrix/vector
vector matrix.Min(const int axis)
double vector.S um() R eturn the sumof the matrix/vector
double matrix.S um() sum elements which can also be
vector matrix.S um(const int axis) performed for the given axis (axes).
void vector.Clip(const double Limit the elements of a
clip
min_value,const double max_value) matrix/vector to a specified range

© 2000-2025, MetaQuotes Ltd.


137 Language Basics

Analogous method
Method matrix/vector Description
in NumPy

void matrix.Clip(const double


of valid values
min_value,const double max_value)
vector vector.CumProd()
R eturn the cumulative product of
vector matrix.CumProd()
cumprod matrix/vector elements, including
matrix matrix.CumProd(const int
those along the given axis
axis)
vector vector.CumS um()
R eturn the cumulative sum of
vector matrix.CumS um()
cumsum matrix/vector elements, including
matrix matrix.CumS um(const int
those along the given axis
axis)
double vector.Prod(const double
initial=1)
R eturn the product of the
double matrix.Prod(const double
prod matrix/vector elements which can
initial=1)
also be performed for the given axis
vector matrix.Prod(const int
axis,const double initial=1)
void matrix.Reshape(const ulong Change the shape of a matrix
reshape
rows, const ulong cols) without changing its data
void matrix.Resize(const ulong R eturn a
new matrix with a changed
resize
rows,const ulong cols) shape and size
bool matrix.S wapRows(const ulong
S wap rows in a matrix
row1, const ulong row2)
bool matrix.S wapCols(const ulong
S wap columns in a matrix
col1, const ulong col2)
double vector.Ptp() R eturn the range of values of a
double matrix.Ptp() ptp matrix/vector or of the given matrix
vector matrix.Ptp(const int axis) axis, equivalent to Max() - Min()
double vector.Percentile(const int
R eturn the specified percentile of
percent)
values of matrix/vector elements or
double matrix.Percentile(const int
percentile elements along the specified axis.
percent)
Valid values of the 'percent'
vector matrix.Percentile(const int
parameter are in the range [0, 100]
percent,const int axis)
double vector.Quantile(const int
R eturn the specified quantile of
percent)
values of matrix/vector elements or
double matrix.Quantile(const int
quantile elements along the specified axis.
percent)
The 'percent' parameter takes values
vector matrix.Quantile(const int
in the range [0, 1]
percent,const int axis)
double vector.Median() Compute the median of the
median
double matrix.Median() matrix/vector elements. The

© 2000-2025, MetaQuotes Ltd.


138 Language Basics

Analogous method
Method matrix/vector Description
in NumPy

median is the middle value that


separates the highest half of the
vector matrix.Median(const int axis)
array/vector elements from the
lowest half of elements.
Compute the arithmetic mean of
double vector.Average()
matrix/vector values. The sum of
double matrix.Average()
average the weights in the denominator
vector matrix.Average(const int
cannot be equal to 0, but some
axis)
weights can be 0
double vector.S td() R eturn the standard deviation of
double matrix.S td() std values of matrix/vector elements or
vector matrix.S td(const int axis) of elements along the given axis
double vector.Var()
Compute the variance of values of
double matrix.Var() var
matrix/vector elements
vector matrix.Var(const int axis)
Compute the Pearson correlation
double vector.CorrCoef(const
coefficient (linear correlation
vector& v) corrcoef
coefficient). The correlation
matrix matrix.CorrCoef()
coefficient is in the range [-1, 1]
Compute the cross-correlation of
vector vector.Correlate(const two vectors. The 'mode' parameter
correlate
vector& v,enum mode) determines the linear convolution
calculation mode
R eturn the discrete, linear
vector vector.Convolve(const convolution of two vectors The
convolve
vector& v, enum mode) 'mode' parameter determines the
linear convolution calculation mode
Compute the covariance matrix. The
matrix matrix.Cov()
covariance of two samples (two
matrix vector.Cov(const vector& v); cov
random variables) is a measure of
(resulting matrix 2 x 2)
their linear dependence

© 2000-2025, MetaQuotes Ltd.


139 Language Basics

Typecasting
Casting Numeric Types

Often a necessity occurs to convert one numeric type into another. Not all numeric types can be
converted into another. Here is the scheme of allowed casting:

S olidlines with arrows indicate changes that are performed almost without any loss of information.
Instead of the char type, the bool type can be used (both take 1 byte of memory), instead of type int,
the color type can be used (4 bytes), instead of the long type, datetime can be used (take 8 bytes).
The four dashed grey lines, also arrowed, denote conversions, when the loss of precision can occur.
For example, the number of digits in an integer equal to 123456789 (int) is higher than the number of
digits that can be represented by float.
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

A number converted into float has the same order, but is less accurate. Conversions, contrary to black
arrows, can be performed with possible data loss. Conversions between char and uchar, short and
ushort, int and uint, long and ulong (conversions to both sides), may lead to the loss of data.
As a result of converting floating point values to integer type, the fractional part is always deleted. If
you want to round off a float to the nearest whole number (which in many cases is more useful), you
should use 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
math_round_g = 10
*/

© 2000-2025, MetaQuotes Ltd.


140 Language Basics

If two values are combined by a binary operator, before the operation execution the operand of a
lower type is converted to the higher type in accordance with the priority given in the below scheme:

The data types char, uchar, short, and ushort unconditionally are converted to the int type.
Examples:

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

//--- Second example


d2=c1/2.0+0.3;
Print("c1/2.0 + 0.3 = ",d2);
// Result: c1/2.0+0.3 = 1.8

The calculated expression consists of two operations. In the first example, the variable c1 of the char
type is converted to a temporary variable of the int type, because the second operand in the division
operation, the constant 2, is of the higher type int. As a result of the integer division 3/2 we get the
value 1, which is of the int type.
In the second operation of the first example, the second operand is the constant 0.3, which is of the
double type, so the result of the first operation is converted into a temporary variable of the double
type with a value of 1.0.
In the second example the variable of the char type c1 is converted to a temporary variable of the
double type, because the second operand in the division operation, the constant 2.0, is of the double
type; no further conversions are made.

Typecasting of Numeric Types

In the expressions of the MQL5 language both explicit and implicit typecasting can be used. The
explicit typecasting is written as follows :
var_1 = (type)var_2;

An expression or function execution result can be used as the var_2 variable. The function style
notation of the explicit typecasting is also possible:
var_1 = type(var_2);

Let's consider an explicit typecasting on the basis of the first example.


//--- Third example
double d2=(double)c1/2+0.3;

© 2000-2025, MetaQuotes Ltd.


141 Language Basics

Print("(double)c1/2 + 0.3 = ",d2);


// Result: (double)c1/2+0.3 = 1.80000000

Before the division operation is performed, the c1 variable is explicitly cast to the double type. Now
the integer constant 2 is cast to the value 2.0 of the double type, because as a result of converting the
first operand has taken the double type. In fact, the explicit typecasting is a unary operation.
Besides, when trying to cast types, 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 c=-112
Print("u = ",u); // Result u=144

Beforeoperations (except for the assignment ones) are performed, the data are converted into the
maximum priority type. Before assignment operations are performed, the data are cast into the target
type.
Examples:

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


Print("i = 1/2 ",i);

int k=1/2.0; // the expression is cast to the double type,


Print("k = 1/2 ",k); // then is to the target type of int, the result is 0

double d=1.0/2.0; // no types casting, the result is 0.5


Print("d = 1/2.0; ",d);

double e=1/2.0; // the expression is cast to the double type,


Print("e = 1/2.0; ",e);// that is the same as the target type, the result is 0.5

double x=1/2; // the expression of the int type is cast to the double target typr,
Print("x = 1/2; ",x); // the result is 0.0

W hen converting long/ulong type into double, precision may be lost in case the integer value is
greater than 9223372036854774784 or less than -9223372036854774784.
void OnStart()
{
long l_max=LONG_MAX;
long l_min=LONG_MIN+1;
//--- define the highest integer value, which does not lose accuracy when being cast to double
while(l_max!=long((double)l_max))
l_max--;
//--- define the lowest integer value, which does not lose accuracy when being cast to double
while(l_min!=long((double)l_min))
l_min++;
//--- derive the found interval for integer values

© 2000-2025, MetaQuotes Ltd.


142 Language Basics

PrintFormat("When casting an integer value to double, it must be "


"within [%I64d, %I64d] interval",l_min,l_max);
//--- now, let's see what happens if the value falls out of this interval
PrintFormat("l_max+1=%I64d, double(l_max+1)=%.f, ulong(double(l_max+1))=%I64d",
l_max+1,double(l_max+1),long(double(l_max+1)));
PrintFormat("l_min-1=%I64d, double(l_min-1)=%.f, ulong(double(l_min-1))=%I64d",
l_min-1,double(l_min-1),long(double(l_min-1)));
//--- receive the following result
// When casting an integer value to double, it should be within [-9223372036854774784, 922337203685
// l_max+1=9223372036854774785, double(l_max+1)=9223372036854774800, ulong(double(l_max+1))=9223372
// l_min-1=-9223372036854774785, double(l_min-1)=-9223372036854774800, ulong(double(l_min-1))=-9223
}

Typecasting for the String Type

The string type has the highest priority among simple types. Therefore, if one of operands of an
operation is of the string type, the second operand will be cast to a string automatically. Note that for
a string, a single dyadic two-place operation of addition is possible. The explicit casting of string to
any numeric type is allowed.
Examples:

string s1=1.0/8; // the expression is cast to the double type,


Print("s1 = 1.0/8; ",s1); // then is to the target type of string,
// result is "0.12500000" (a string containing 10 characters)

string s2=NULL; // string deinitialization


Print("s2 = NULL; ",s2); // the result is an empty string
string s3="Ticket N"+12345; // the expression is cast to the string type
Print("s3 = \"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 Base Class Pointers to Pointers of Derivative Classes

Objects of the open generated class can also be viewed 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 a

© 2000-2025, MetaQuotes Ltd.


143 Language Basics

linked list (List) of them, as we view them as objects of the base type. But the converse is not true:
the base class objects are not automatically objects of a derived class.
You can use the explicit casting to convert the base class pointers to the pointers of a derived class.
But you must be fully confident in the admissibility of such a transformation, because otherwise a
critical runtime error will occur and the mql5 program will be stopped.

Dynamic typecasting using dynamic_cast operator

Dynamic typecasting is performed using dynamic_cast operator that can be applied only to pointers to
classes. Type validation is performed at runtime. This means that the compiler does not check the
data type applied for typecasting when dynamic_cast operator is used. If a pointer is converted to a
data type which is not the actual type of an object, the result is NULL.
dynamic_cast <type-id> ( expression )

The type-id parameter in angle brackets should point to a previously defined class type. Unlike C++,
expression operand type can be of any value except for void.

Example:

class CBar { };
class CFoo : public CBar { };

void OnStart()
{
CBar bar;
//--- dynamic casting of *bar pointer type to *foo pointer is allowed
CFoo *foo = dynamic_cast<CFoo *>(&bar); // no critical error
Print(foo); // foo=NULL
//--- an attempt to explicitly cast a Bar type object reference to a Foo type object is forbidden
foo=(CFoo *)&bar; // critical runtime error
Print(foo); // this string is not executed
}

See also
Data Types

© 2000-2025, MetaQuotes Ltd.


144 Language Basics

Void Type and NULL Constant


S yntactically the void type 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 any value, or as a function parameter it denotes the absence of
parameters.
The predefined constant variable NULL is of the void type. It can be assigned to variables of any other
fundamental types without conversion. The comparison of fundamental type variables with the NULL
value is allowed.
Example:

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

Also NULL can be compared to pointers to objects created with the new operator.
See also
Variables, Functions

© 2000-2025, MetaQuotes Ltd.


145 Language Basics

User-defined types
The typedef keyword in C++ allows creating user-defined data types. To do this, simply specify a new
data type name for an already existing data type. The new data type is not created. A new name for
the existing type is defined instead. User-defined types make applications more flexible: sometimes,
it is enough to change typedef instructions using substitution macros (#define). User-defined types
also improve code readability since it is possible to apply custom names to standard data types using
typedef. The general format of the entry for creating a user-defined type:
typedef type new_name;

H ere,type means any acceptable data type, while new_name is a new name of the type. A new name

is set only as an addition (not as a replacement) to an existing type name. MQL5 allows creating
pointers to functions using typedef.

Pointer to the function


A pointer to a function is generally defined in the following format
typedef function_result_type (*Function_name_type)(list_of_input_parameters_types);

where after typedef, the function signature (number and type of input parameters, as well as a type of
a result returned by the function) is set. Below is a simple example of creating and applying a pointer
to a function:
//--- declare a pointer to a function that accepts two int parameters
typedef int (*TFunc)(int,int);
//--- TFunc is a type, and it is possible to declare the variable pointer to the function
TFunc func_ptr; // pointer to the function
//--- declare the functions corresponding to the TFunc description
int sub(int x,int y) { return(x-y); } // subtract one number from another
int add(int x,int y) { return(x+y); } // addition of two numbers
int neg(int x) { return(~x); } // invert bits in the variable
//--- the func_ptr variable may store the function address to declare it later
func_ptr=sub;
Print(func_ptr(10,5));
func_ptr=add;
Print(func_ptr(10,5));
func_ptr=neg; // error: neg does not have int (int,int) type
Print(func_ptr(10)); // error: two parameters needed

In this example, the func_ptr variable may receive the sub and add functions since they have two
inputs each of int type as defined in the TFunc pointer to the function. On the contrary, the neg
function cannot be assigned to the func_ptr pointer since its signature is different.

Arranging event models in the user interface

Pointers to functions allow you to easily create processing of events when creating a user interface.
Let's use an example from the CButton section to show how to create buttons and add the functions for
handling pressing to them. First, define a pointer to the TAction function to be called by pressing the
button and create three functions according to the TAction description.

© 2000-2025, MetaQuotes Ltd.


146 Language Basics

//--- create a custom function type


typedef int(*TAction)(string,int);
//+------------------------------------------------------------------+
//| Open the file |
//+------------------------------------------------------------------+
int Open(string name,int id)
{
PrintFormat("%s function called (name=%s id=%d)",__FUNCTION__,name,id);
return(1);
}
//+------------------------------------------------------------------+
//| Save the file |
//+------------------------------------------------------------------+
int Save(string name,int id)
{
PrintFormat("%s function called (name=%s id=%d)",__FUNCTION__,name,id);
return(2);
}
//+------------------------------------------------------------------+
//| Close the file |
//+------------------------------------------------------------------+
int Close(string name,int id)
{
PrintFormat("%s function called (name=%s id=%d)",__FUNCTION__,name,id);
return(3);
}

Then, create the MyButton class from CButton, where we should add the TAction pointer to the
function.
//+------------------------------------------------------------------+
//| Create the button class with the events processing function |
//+------------------------------------------------------------------+
class MyButton: public CButton
{
private:
TAction m_action; // chart events handler
public:
MyButton(void){}
~MyButton(void){}
//--- constructor specifying the button text and the pointer to the events handling function
MyButton(string text, TAction act)
{
Text(text);
m_action=act;
}
//--- set the custom function called from the OnEvent() events handler
void SetAction(TAction act){m_action=act;}

© 2000-2025, MetaQuotes Ltd.


147 Language Basics

//--- standard chart events handler


virtual bool OnEvent(const int id,const long &lparam,const double &dparam,const string &spa
{
if(m_action!=NULL && lparam==Id())
{
//--- call the custom m_action() handler
m_action(sparam,(int)lparam);
return(true);
}
else
//--- return the result of calling the handler from the CButton parent class
return(CButton::OnEvent(id,lparam,dparam,sparam));
}
};

Create the CControls Dialog derivative class from CAppDialog, add the m_buttons array to it for storing
the buttons of the MyButton type, as well as the AddButton(MyButton &button) and CreateButtons()
methods.

//+------------------------------------------------------------------+
//| CControlsDialog class |
//| Objective: graphical panel for managing the application |
//+------------------------------------------------------------------+
class CControlsDialog : public CAppDialog
{
private:
CArrayObj m_buttons; // button array
public:
CControlsDialog(void){};
~CControlsDialog(void){};
//--- create
virtual bool Create(const long chart,const string name,const int subwin,const int x1,const
//--- add the button
bool AddButton(MyButton &button){return(m_buttons.Add(GetPointer(button)));m_button
protected:
//--- create the buttons
bool CreateButtons(void);
};
//+------------------------------------------------------------------+
//| Create the CControlsDialog object on the chart |
//+------------------------------------------------------------------+
bool CControlsDialog::Create(const long chart,const string name,const int subwin,const int x1,const
{
if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
return(false);
return(CreateButtons());
//---
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


148 Language Basics

//| defines |
//+------------------------------------------------------------------+
//--- indents and gaps
#define INDENT_LEFT (11) // indent from left (with allowance for borde
#define INDENT_TOP (11) // indent from top (with allowance for border
#define CONTROLS_GAP_X (5) // gap by X coordinate
#define CONTROLS_GAP_Y (5) // gap by Y coordinate
//--- for buttons
#define BUTTON_WIDTH (100) // size by X coordinate
#define BUTTON_HEIGHT (20) // size by Y coordinate
//--- for the indication area
#define EDIT_HEIGHT (20) // size by Y coordinate
//+------------------------------------------------------------------+
//| Create and add buttons to the CControlsDialog panel |
//+------------------------------------------------------------------+
bool CControlsDialog::CreateButtons(void)
{
//--- calculate buttons coordinates
int x1=INDENT_LEFT;
int y1=INDENT_TOP+(EDIT_HEIGHT+CONTROLS_GAP_Y);
int x2;
int y2=y1+BUTTON_HEIGHT;
//--- add buttons objects together with pointers to functions
AddButton(new MyButton("Open",Open));
AddButton(new MyButton("Save",Save));
AddButton(new MyButton("Close",Close));
//--- create the buttons graphically
for(int i=0;i<m_buttons.Total();i++)
{
MyButton *b=(MyButton*)m_buttons.At(i);
x1=INDENT_LEFT+i*(BUTTON_WIDTH+CONTROLS_GAP_X);
x2=x1+BUTTON_WIDTH;
if(!b.Create(m_chart_id,m_name+"bt"+b.Text(),m_subwin,x1,y1,x2,y2))
{
PrintFormat("Failed to create button %s %d",b.Text(),i);
return(false);
}
//--- add each button to the CControlsDialog container
if(!Add(b))
return(false);
}
//--- succeed
return(true);
}

Now, we can develop the program using the CControls Dialog control panel having 3 buttons : Open,
S ave and Close. W hen click ing a button, the appropriate function in the form of the TAction pointer is
called.

© 2000-2025, MetaQuotes Ltd.


149 Language Basics

//--- declare the object on the global level to automatically create it when launching the program
CControlsDialog MyDialog;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- now, create the object on the chart
if(!MyDialog.Create(0,"Controls",0,40,40,380,344))
return(INIT_FAILED);
//--- launch the application
MyDialog.Run();
//--- application successfully initialized
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy dialog
MyDialog.Destroy(reason);
}
//+------------------------------------------------------------------+
//| Expert chart event function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, // event ID
const long& lparam, // event parameter of the long type
const double& dparam, // event parameter of the double type
const string& sparam) // event parameter of the string type
{
//--- call the handler from the parent class (here it is CAppDialog) for the chart events
MyDialog.ChartEvent(id,lparam,dparam,sparam);
}

The launched application's appearance and button clicking results are provided on the screenshot.

© 2000-2025, MetaQuotes Ltd.


150 Language Basics

The full source code of the program


//+------------------------------------------------------------------+
//| Panel_Buttons.mq5 |
//| Copyright 2017, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+

#property copyright "Copyright 2017, MetaQuotes Software Corp."


#property link "https://www.mql5.com"
#property version "1.00"
#property description "The panel with several CButton buttons"
#include <Controls\Dialog.mqh>
#include <Controls\Button.mqh>
//+------------------------------------------------------------------+
//| defines |
//+------------------------------------------------------------------+
//--- indents and gaps
#define INDENT_LEFT (11) // indent from left (with allowance for borde
#define INDENT_TOP (11) // indent from top (with allowance for border
#define CONTROLS_GAP_X (5) // gap by X coordinate
#define CONTROLS_GAP_Y (5) // gap by Y coordinate

© 2000-2025, MetaQuotes Ltd.


151 Language Basics

//--- for buttons


#define BUTTON_WIDTH (100) // size by X coordinate
#define BUTTON_HEIGHT (20) // size by Y coordinate
//--- for the indication area
#define EDIT_HEIGHT (20) // size by Y coordinate

//--- create the custom function type


typedef int(*TAction)(string,int);
//+------------------------------------------------------------------+
//| Open the file |
//+------------------------------------------------------------------+
int Open(string name,int id)
{
PrintFormat("%s function called (name=%s id=%d)",__FUNCTION__,name,id);
return(1);
}
//+------------------------------------------------------------------+
//| Save the file |
//+------------------------------------------------------------------+
int Save(string name,int id)
{
PrintFormat("%s function called (name=%s id=%d)",__FUNCTION__,name,id);
return(2);
}
//+------------------------------------------------------------------+
//| Close the file |
//+------------------------------------------------------------------+
int Close(string name,int id)
{
PrintFormat("%s function called (name=%s id=%d)",__FUNCTION__,name,id);
return(3);
}
//+------------------------------------------------------------------+
//| Create the button class with the events processing function |
//+------------------------------------------------------------------+
class MyButton: public CButton
{
private:
TAction m_action; // chart events handler
public:
MyButton(void){}
~MyButton(void){}
//--- constructor specifying the button text and the pointer to the events handling function
MyButton(string text,TAction act)
{
Text(text);
m_action=act;
}
//--- set the custom function called from the OnEvent() events handler

© 2000-2025, MetaQuotes Ltd.


152 Language Basics

void SetAction(TAction act){m_action=act;}


//--- standard chart events handler
virtual bool OnEvent(const int id,const long &lparam,const double &dparam,const string &spa
{
if(m_action!=NULL && lparam==Id())
{
//--- call the custom handler
m_action(sparam,(int)lparam);
return(true);
}
else
//--- return the result of calling the handler from the CButton parent class
return(CButton::OnEvent(id,lparam,dparam,sparam));
}
};
//+------------------------------------------------------------------+
//| CControlsDialog class |
//| Objective: graphical panel for managing the application |
//+------------------------------------------------------------------+
class CControlsDialog : public CAppDialog
{
private:
CArrayObj m_buttons; // button array
public:
CControlsDialog(void){};
~CControlsDialog(void){};
//--- create
virtual bool Create(const long chart,const string name,const int subwin,const int x1,const
//--- add the button
bool AddButton(MyButton &button){return(m_buttons.Add(GetPointer(button)));m_button
protected:
//--- create the buttons
bool CreateButtons(void);
};
//+------------------------------------------------------------------+
//| Create the CControlsDialog object on the chart |
//+------------------------------------------------------------------+
bool CControlsDialog::Create(const long chart,const string name,const int subwin,const int x1,const
{
if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
return(false);
return(CreateButtons());
//---
}
//+------------------------------------------------------------------+
//| Create and add buttons to the CControlsDialog panel |
//+------------------------------------------------------------------+
bool CControlsDialog::CreateButtons(void)
{

© 2000-2025, MetaQuotes Ltd.


153 Language Basics

//--- calculate buttons coordinates


int x1=INDENT_LEFT;
int y1=INDENT_TOP+(EDIT_HEIGHT+CONTROLS_GAP_Y);
int x2;
int y2=y1+BUTTON_HEIGHT;
//--- add buttons objects together with pointers to functions
AddButton(new MyButton("Open",Open));
AddButton(new MyButton("Save",Save));
AddButton(new MyButton("Close",Close));
//--- create the buttons graphically
for(int i=0;i<m_buttons.Total();i++)
{
MyButton *b=(MyButton*)m_buttons.At(i);
x1=INDENT_LEFT+i*(BUTTON_WIDTH+CONTROLS_GAP_X);
x2=x1+BUTTON_WIDTH;
if(!b.Create(m_chart_id,m_name+"bt"+b.Text(),m_subwin,x1,y1,x2,y2))
{
PrintFormat("Failed to create button %s %d",b.Text(),i);
return(false);
}
//--- add each button to the CControlsDialog container
if(!Add(b))
return(false);
}
//--- succeed
return(true);
}
//--- declare the object on the global level to automatically create it when launching the program
CControlsDialog MyDialog;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- now, create the object on the chart
if(!MyDialog.Create(0,"Controls",0,40,40,380,344))
return(INIT_FAILED);
//--- launch the application
MyDialog.Run();
//--- application successfully initialized
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy dialog
MyDialog.Destroy(reason);

© 2000-2025, MetaQuotes Ltd.


154 Language Basics

}
//+------------------------------------------------------------------+
//| Expert chart event function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, // event ID
const long& lparam, // event parameter of the long type
const double& dparam, // event parameter of the double type
const string& sparam) // event parameter of the string type
{
//--- call the handler from the parent class (here it is CAppDialog) for the chart events
MyDialog.ChartEvent(id,lparam,dparam,sparam);
}

See also
Variables, Functions

© 2000-2025, MetaQuotes Ltd.


155 Language Basics

Object Pointers
MQL5 enables the dynamic creation of complex type objects. This is done by using the ‘new’
operatorwhich returns a descriptor of the created object. The descriptor size is 8 bytes. S yntactically,
object descriptors in MQL5 are similar to C++ pointers.
Example:

MyObject* hobject= new MyObject();

Unlik eC++, the ‘hobject’ variable from the example above is not a pointer to memory, but is an
object descriptor. Furthermore, in MQL5, all objects in function parameters must be passed by
reference. The examples below show the passing of objects as function parameters :
class Foo
{
public:
string m_name;
int m_id;
static int s_counter;
//--- constructors and destructors
Foo(void){Setup("noname");};
Foo(string name){Setup(name);};
~Foo(void){};
//--- initialize the Foo object
void Setup(string name)
{
m_name=name;
s_counter++;
m_id=s_counter;
}
};
int Foo::s_counter=0;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare the object as a variable, with automatic creation
Foo foo1;
//--- variant of passing an object by reference
PrintObject(foo1);

//--- declare a pointer to an object and create it using the 'new' operator
Foo *foo2=new Foo("foo2");
//--- variant of passing a pointer to an object by reference
PrintObject(foo2); // the pointer to the object is converted by the compiler automatically

//--- declare an array of Foo objects


Foo foo_objects[5];

© 2000-2025, MetaQuotes Ltd.


156 Language Basics

//--- variant of passing an array of objects


PrintObjectsArray(foo_objects); // a separate function for passing an array of objects

//--- declare an array of pointers to objects of type Foo


Foo *foo_pointers[5];
for(int i=0;i<5;i++)
foo_pointers[i]=new Foo("foo_pointer");
//--- variant of passing an array of pointers
PrintPointersArray(foo_pointers); // a separate function for passing an array of pointers

//--- before finishing, be sure to delete the objects created as pointers


delete(foo2);
//--- remove the array of pointers
int size=ArraySize(foo_pointers);
for(int i=0;i<5;i++)
delete(foo_pointers[i]);
//---
}
//+------------------------------------------------------------------+
//| Objects are always passed by reference |
//+------------------------------------------------------------------+
void PrintObject(Foo &object)
{
Print(__FUNCTION__,": ",object.m_id," Object name=",object.m_name);
}
//+------------------------------------------------------------------+
//| Pass an array of objects |
//+------------------------------------------------------------------+
void PrintObjectsArray(Foo &objects[])
{
int size=ArraySize(objects);
for(int i=0;i<size;i++)
PrintObject(objects[i]);
}
//+------------------------------------------------------------------+
//| Pass an array of object pointers |
//+------------------------------------------------------------------+
void PrintPointersArray(Foo* &objects[])
{
int size=ArraySize(objects);
for(int i=0;i<size;i++)
PrintObject(objects[i]);
}
//+------------------------------------------------------------------+

Check the pointer before use

© 2000-2025, MetaQuotes Ltd.


157 Language Basics

An attempt to access an invalid pointer causes the critical shutdown of the program. The CheckPointer
function is utilized to check a pointer before use. The pointer can be invalid in the following cases :
· the pointer is equal to NULL;
· the object was destroyed using the delete operator.
This function can be used to validate of a pointer. A non-zero value indicates that data can be
accessed at this pointer.
class CMyObject
{
protected:
double m_value;
public:
CMyObject(void);
CMyObject(double value) {m_value=value;};
~CMyObject(void){};
//---
double Value(void) {return(m_value);}
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- create a non-initialized object
CMyObject *pointer;
if(CheckPointer(pointer)==POINTER_INVALID)
Print("1. pointer is ", EnumToString(CheckPointer(pointer)));
else
Print("1. pointer.Value()=", pointer.Value());

//--- initialize the pointer


pointer=new CMyObject(M_PI);
if(CheckPointer(pointer)==POINTER_INVALID)
Print("2. pointer is ", EnumToString(CheckPointer(pointer)));
else
Print("2. pointer.Value()=", pointer.Value());

//--- delete the object


delete(pointer);
if(CheckPointer(pointer)==POINTER_INVALID)
Print("3. pointer is ", EnumToString(CheckPointer(pointer)));
else
Print("3. pointer.Value()=", pointer.Value());
}
/*
1. pointer is POINTER_INVALID
2. pointer.Value()=3.141592653589793
3. pointer is POINTER_INVALID

© 2000-2025, MetaQuotes Ltd.


158 Language Basics

*/

To quickly validate the pointer, you can also use operator "!" (LNOT) which checks it via an implicit call
of the CheckPointer function. This allows a more concise and clear code writing. Below are the checks
from the previous example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- create a non-initialized object
CMyObject *pointer;
if(!pointer)
Print("1. pointer is ", EnumToString(CheckPointer(pointer)));
else
Print("1. pointer.Value()=", pointer.Value());

//--- initialize the pointer


pointer=new CMyObject(M_PI);
if(!pointer)
Print("2. pointer is ", EnumToString(CheckPointer(pointer)));
else
Print("2. pointer.Value()=", pointer.Value());

//--- delete the object


delete(pointer);
if(!pointer)
Print("3. pointer is ", EnumToString(CheckPointer(pointer)));
else
Print("3. pointer.Value()=", pointer.Value());
}
/*
1. pointer is POINTER_INVALID
2. pointer.Value()=3.141592653589793
3. pointer is POINTER_INVALID
*/

Operator "==" is used for a quick check for NULL. For example: ptr==NULL or ptr!=NULL.

See also
Variables, Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and
Deleting Objects

© 2000-2025, MetaQuotes Ltd.


159 Language Basics

References: Modifier & and Keyword this


Passing Parameters by Reference
In MQL5 parameters of simple types can be passed both by value and by reference, while parameters
of compound types are always passed by reference. To inform the compiler that a parameter must be
passed by reference, the ampersand character & is added before the parameter name.
Passing a parameter by reference means passing the address of the variable, that's why all changes in
the parameter that is passed by reference will be immediately reflected in the source variable. Using
parameter passing by reference, you can implement return of several results of a function at the same
time. In order to prevent changing of a parameter passed by reference, use the const modifier.
Thus, if the input parameter of a function is an array, a structure or class object, symbol '&' is placed
in the function header after the variable type and before its name.
Example

class CDemoClass
{
private:
double m_array[];

public:
void setArray(double &array[]);
};
//+------------------------------------------------------------------+
//| filling the array |
//+------------------------------------------------------------------+
void CDemoClass::setArray(double &array[])
{
if(ArraySize(array)>0)
{
ArrayResize(m_array,ArraySize(array));
ArrayCopy(m_array, array);
}
}

In the above example class CDemoClass is declared, which contains the private member - array
m_array[] of double type. Function setArray() is declared, to which array[] is passed by reference. If
the function header doesn't contain the indication about passing by reference, i.e. doesn't contain the
ampersand character, an error message will be generated at the attempt to compile such a code.
Despite the fact that the array is
passed by reference, we can't assign one array to another. W e need
to perform the element-wise copying of contents of the source array to the recipient array. The
presence of & in the function description is the obligatory condition for arrays and structures when
passed as the function parameter.

Keyword this

© 2000-2025, MetaQuotes Ltd.


160 Language Basics

A variable of class type (object) can be passed both by reference and by pointer. As well as reference,
the pointer allows having access to an object. After the object pointer is declared, the new operator
should be applied to it to create and initialize it.
The reserved word this is intended for obtaining the reference of the object to itself, which is
available inside class or structure methods. this always references to the object, in the method of
which it is used, and the expression GetPointer(this) gives the pointer of the object, whose member is
the function, in which call of GetPointer() is performed. In MQL5 functions can't return objects, but
they can return the object pointer.
Thus, if we need a function to return an object, we can return the pointer of this object in the form of
GetPointer(this). Let's add function getDemoClass() that returns pointer of the object of this class,
into the description of CDemoClass.
class CDemoClass
{
private:
double m_array[];

public:
void setArray(double &array[]);
CDemoClass *getDemoClass();
};
//+------------------------------------------------------------------+
//| filling the array |
//+------------------------------------------------------------------+
void CDemoClass::setArray(double &array[])
{
if(ArraySize(array)>0)
{
ArrayResize(m_array,ArraySize(array));
ArrayCopy(m_array,array);
}
}
//+------------------------------------------------------------------+
//| returns its own pointer |
//+------------------------------------------------------------------+
CDemoClass *CDemoClass::getDemoClass(void)
{
return(GetPointer(this));
}

S tructures don't have pointers, operators new and delete can't be applied to them, GetPointer(this)
can't be used.
See also
Object Pointers, Creating and Deleting Objects, Visibility S cope and Lifetime of Variables

© 2000-2025, MetaQuotes Ltd.


161 Language Basics

Operations and Expressions


S omecharacters and character sequences are of a special importance. These are so-called operation
symbols, for example:
+ - * / % Symbols of arithmetic operations
&& || Symbols of logical operations
= += *= Characters assignment operators

Operation symbols are used in expressions and have sense when appropriate operands are given to
them. Punctuation marks are emphasized, as well. These are parentheses, braces, comma, colon, and
semicolon.
Operation symbols, punctuation marks, and spaces are used to separate language elements from each
other.
This section contains the description of the following topics :
· Expressions

· Arithmetic Operations

· Assignment Operations
· Operations of Relation
· Boolean Operations
· Bitwise Operations
· Other Operations
· Priorities and Operations Order

© 2000-2025, MetaQuotes Ltd.


162 Language Basics

Expressions
An expression consists of one or more operands and operation symbols. An expression can be written
in several lines.
Examples:

a++; b = 10; // several expressions are located in one line


//--- one expression is divided into several lines
x = (y * z) /
(w + 2) + 127;

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


See also
Precedence Rules

© 2000-2025, MetaQuotes Ltd.


163 Language Basics

Arithmetic Operations
Arithmetic operations include additive and multiplicative operations :
Sum of variables i = j + 2;
Difference of variables i = j - 3;
Changing the sign x = - x;
Product of variables z = 3 * x;
Division quotient i = j / 5;
Remainder of division minutes = time % 60;
Adding 1 to the variable value i++;
Adding 1 to the variable value ++i;
Subtracting 1 from the variable value k--;
Subtracting 1 from the variable value --k;

Increment and decrement operations are applied only to variables, they can't be applied to constants.
The prefix increment (++i) and decrement (--k) are applied to the variable right before this variable is
used in an expression.
Post-increment (i++) and post-decrement (k--) are applied to the variable right after this variable is
used in an expression.
Important Notice
int i=5;
int k = i++ + ++i;

Computational problems may occur while moving the above expression from one programming
environment to another one (for example, from Borland C++ to MQL5). In general, the order of
computations depends on the compiler implementation. In practice, there are two ways to implement
the post-decrement (post-increment):
1. The post-decrement (post-increment) is applied to the variable after calculating the whole
expression.
2. The post-decrement (post-increment) is applied to the variable immediately at the operation.

Currently the first way of post-decrement (post-increment) calculation is implemented in MQL5. But
even knowing this peculiarity, it is not recommended to experiment with its use.
Examples:

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

See also
Precedence Rules

© 2000-2025, MetaQuotes Ltd.


164 Language Basics

Assignment Operations
The value of the expression that includes the given operation is the value of the left operand after
assignment:
Assigning the value of x to the y variable y = x;

The following operations unite arithmetic or bitwise operations with operation of assignment:
Adding x to the y variable y += x;
Subtracting x from the y variable y -= x;
Multiplying the y variable by x y *= x;
Dividing the y variable by x y /= x;
Reminder of division of the y variable by x y %= x;
Shift of the binary representation of y to the right by x bits y >>= x;
Shift of the binary representation of y to the left by x bits 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 can be applied to integers only. W hen performing the operation of the logical shift
of the y representation to the right/left by x bits, the 5 smallest binary digits of the x value are used,
the highest ones are dropped, i.e. the shift is made to 0-31 bits.
By %= operation (y value by module of x), the result sign is equal to the sign of divided number.
The assignment operator can be used several times in an expression . In this case the processing of
the expression is performed from left to right:
y=x=3;

First, the variable x will be assigned the value 3, then the y variable will be assigned the value of x,
i.e. also 3.
See also
Precedence Rules

© 2000-2025, MetaQuotes Ltd.


165 Language Basics

Operations of Relation
Boolean FAL SE is represented with an integer zero value, while the boolean TRUE is represented by any
non-zero value.
The value of expressions containing operations of relation or logical operations is FAL SE (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;

The equality of two real numbers can't be compared. In most cases, two seemingly identical numbers
can be unequal because of different values in the 15th decimal place. In order to correctly compare two
real numbers, 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 and %.16f are equal",first,third);
}
}
// Result: 0.3000000000000000 0.2999999999999998 are equal

See also
Precedence Rules

© 2000-2025, MetaQuotes Ltd.


166 Language Basics

Boolean Operations
Logical Negation NOT (!)

Operand of the logical negation (!) must be of arithmetic type. The result is TRUE (1), if the operand
value is FALSE (0); and it is equal to FALSE (0), if the operand differs from FALSE (0).
if(!a) Print("not 'a'");

Logical Operation OR (||)

Logical OR operation (||) of x and y values. The expression value is TRUE (1), if x or y value is true
(not null). Otherwise - FALSE (0).
if(x<0 || x>=max_bars) Print("out of range");

Logical Operation AND (&&)

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

Brief Estimate of Boolean Operations

The scheme of the so called " brief estimate" is applied to boolean operations, i.e. the calculation of
the expression is terminated when the result of the expression can be precisely estimated.
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- the first example of the brief estimate
if(func_false() && func_true())
{
Print("Operation &&: You will never see this expression");
}
else
{
Print("Operation &&: Result of the first expression is false, so the second wasn't calculated
}
//--- the second example of the brief estimate
if(!func_false() || !func_true())
{
Print("Operation ||: Result of the first expression is true, so the second wasn't calculated"
}
else
{
Print("Operation ||: You will never see this expression");
}
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


167 Language Basics

//| the function always returns false |


//+------------------------------------------------------------------+
bool func_false()
{
Print("Function func_false()");
return(false);
}
//+------------------------------------------------------------------+
//| the function always returns true |
//+------------------------------------------------------------------+
bool func_true()
{
Print("Function func_true()");
return(true);
}

See also
Precedence Rules

© 2000-2025, MetaQuotes Ltd.


168 Language Basics

Bitwise Operations
Complement to One

Complement of the variable value up to one. The value of the expression contains 1 in all digits where
the variable value contains 0, and 0 in all digits where 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 digits. If the value to shift is of the unsigned
type, the logical right shift is made, i.e. the freed left-side bits will be filled with zeroes.
If the value to shift is of a sign type, the arithmetic right shift is made, i.e. the freed left-side digits
will be filled with the value of a sign bit (if the number is positive, the value of the 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);
//--- 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 digits, the freed right-side digits are filled
with zeros.
x = x << y;

Example:

char a='a',b='b';
Print("Before: a = ",a, " b = ",b);
//--- shift to the left
b=a<<1;
Print("After: a = ",a, " b = ",b);

© 2000-2025, MetaQuotes Ltd.


169 Language Basics

// The result will be:


// Before: a = 97 b = 98
// After: a = 97 b = -62

It is not recommended to shift by the number of bits larger or equal to the length of the variable
shifted, because the result of such an operation is undefined.

Bitwise AND Operation

The bitwise AND operation of binary-coded x and y representations. The value of the expression
contains a 1 (TRUE) in all digits where both x and y contain non-zero, and it contains 0 (FALSE) in all
other digits.
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

The bitwise OR operation of binary representations of x and y. The value of the expression contains 1
in all digits where x or y does not contain 0, and it contains 0 in all other digits.
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 Exclusive Operation OR

The bitwise exclusive OR (eXclusive OR) operation of binary representations of x and y. The value of
the expression contains a 1 in all digits where x and y have different binary values, and it contains 0 in
all other digits.
b = x ^ y;

Example:

© 2000-2025, MetaQuotes Ltd.


170 Language Basics

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 = 3

Bitwise operations are performed with integers only.


See also
Precedence Rules

© 2000-2025, MetaQuotes Ltd.


171 Language Basics

Other operations
Indexing ( [] )
W hen addressing the i-th element of the array, the expression value is the value of a variable with the
serial number i.
Example:

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

Only an integer can be index of an array. Four-dimensional and below arrays are allowed. Each
dimension is indexed from 0 to dimension size-1. In particular case, for a one-dimensional array
consisting of 50 elements, the reference to the first element will look like array [0], that to the last
element will be array [49].
W hen addressing beyond the array, the executing subsystem will generate a critical error, and the
program will be stopped.

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


Each argument can represent a constant, variable, or expression of the corresponding type. The
arguments passed are separated by commas and must be inside of parentheses, the opening
parenthesis must follow the name of the called function.
The expression value is the value returned by the function. If the return value is of void type, such
function call cannot be placed to the right in the assignment operation. Note that the expressions
x1,..., xn are executed exactly in this order.
Example:

int length=1000000;
string a="a",b="b",c;
//---Other Operations
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 executed from left to right. All side effects of the left
expression calculation can appear before the right expression is calculated. The result type and value
coincide with those of the right expression. The list of parameters to be passed (see above) can be
considered as an example.
Example:

© 2000-2025, MetaQuotes Ltd.


172 Language Basics

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

Dot Operator ( . )
For the direct access to the public members of structures and classes the dot operation is used.
S yntax :

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;

Scope Resolution Operation ( :: )


Each function in a mql5 program has its own execution scope. For example, the Print() system function
is performed in a global scope. Imported functions are called in the scope of the corresponding import.
Method functions of classes have the scope of the corresponding class. The syntax of the scope
resolution operation is as follows :
[Scope_name]::Function_name(parameters)

If there is no scope name, this is the explicit direction to use the global scope. If there is no scope
resolution operation, the function is sought in the nearest scope. If there is no function in the local
scope, the search is conducted in the global scope.
The scope resolution operation is also used to define function-class member.
type Class_name::Function_name(parameters_description)
{
// function body
}

Use ofseveral functions of the same name from different execution contexts in a program may cause
ambiguity. The priority order of function calls without explicit scope specification is the following:
1. Class methods. If no function with the specified name is set in the class, move to the next level.
2. MQL5 functions. If the language does not have such a function, move to the next level.
3. User defined global functions. If no function with the specified name is found, move to the next
level.

© 2000-2025, MetaQuotes Ltd.


173 Language Basics

4. Imported functions. If no function with the specified name is found, the compiler returns an error.
To avoid the ambiguity of function calls, always explicitly specify the function scope using the scope
resolution operation.

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();
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


174 Language Basics

Operation of Obtaining Data Type Size or Size of Any Data Type


Object ( sizeof )
Using the sizeof operation, the memory size corresponding to an identifier or type can be defined. The
sizeof operation is of the following format:
Example:

sizeof(expression)

Any identifier, or type name enclosed in brackets can be used as an expression. Note that the void
type name can't be used, and the identifier cannot belong to the field of bits, or be a function name.
If the expression is the name of a static array (i.e. the first dimension is given), then the result is the
size of the whole array (i.e. the product of the number of elements and the length of the type). If the
expression is the name of a dynamic array (the first dimension is not specified), the result will be the
size of the object of the dynamic array.
W hen sizeof is applied to the name of structure or class type, or to the identifier of the structure or
class type, 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));

The size is calculated at the compilation stage.


See also
Precedence Rules

© 2000-2025, MetaQuotes Ltd.


175 Language Basics

Precedence Rules
Each group of operations in the table has the same priority. The higher the priority of operations is,
the higher it is position of the group in the table. The precedence rules determine the grouping of
operations and operands.
Attention: Precedence of operations in the MQL5 language corresponds to the priority adopted in C++,
and differs from the priority given in the MQL4 language.

Operation Desciption Execution Order

() Function Call From left to right


[] R eferencing to an array element
. R eferencing to a structure element
! Logical negation R ight to left
~ Bitwise negation (complement)
– S ign changing
++ Increment by one
-- Decrement by one
(type) Typecasting
sizeof Determining size in bytes

* Multiplication From left to right


/ Division
% Module division
+ Addition From left to right
– S ubtraction

<< Left shift From left to right


>> R ight shift

< Less than From left to right


<= Less than or equal
> Greater than
>= Greater than or equal

== Equal From left to right


!= Not equal

& Bitwise AND operation From left to right


^ Bitwise exclusive 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 R ight to left
= Assignment R ight to left
*= Multiplication with assignment
/= Division with assignment

© 2000-2025, MetaQuotes Ltd.


176 Language Basics

Operation Desciption Execution Order

%= Module with assignment


+= Addition with assignment
-= S ubtraction with assignment
<<= Left shift with assignment
>>= R ight shift with assignment
&= Bitwise AND with assignment
^= Exclusive OR with assignment
|= Bitwise OR with assignment

, Comma From left to right

To change the operation execution order, parenthesis that are of higher priority are used.

© 2000-2025, MetaQuotes Ltd.


177 Language Basics

Operators
Language operators describe some algorithmic operations that must be executed to accomplish a tas k.
The program body is a sequence of such operators. Operators following one by one are separated by
semicolons.

Operator Description

Compound 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 calling
program
if-else conditional operator Is used when it's necessary to make a choice
?: conditional operator A simple analog of the if-else conditional operator
switch selection operator Passes control to the operator, which corresponds to the
expression value
while loop operator Performs an operator until the expression checked becomes false.
The expression is checked before each iteration
for loop operator Performs an operator until the expression checked becomes false.
The expression is checked before each iteration
do-while loop operator Performs an operator until the expression checked becomes false.
The end condition is checked, after each loop. The loop body is
always executed at least once.
break operator Terminates the execution of the nearest attached external
operator switch, while, do-while or for
continue operator Passes control to the beginning of the nearest external loop
operator while, do-while or for
new operator Creates an object of the appropriate size and returns a descriptor
of the created object.
delete operator Deletes the object created by the new operator

One operator can occupy one or more lines. Two or more operators can be located in the same line.
Operators that control over the execution order (if, if-else, switch, while and for), can be nested into
each other.
Example:

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

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


178 Language Basics

Compound Operator
A compound operator (a block) consists of one or more operators of any type, enclosed in braces {}.
The closing brace must not be followed by a semicolon (;).
Example:

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

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


179 Language Basics

Expression Operator
Any expression followed by a semicolon (;) is the operator. Here are some examples of expression
operators.

Assignment Operator
Identifier = expression;
x=3;
y=x=3;
bool equal=(x==y);

Assignment operator can be used many times in an expression. In this case, the expression is
processed from right to left.

Function Calling Operator


Function_name (argument1,..., argumentN);
FileClose(file);

Empty Operator
Consists only of a semicolon (;) and is used to denote an empty body of a control operator.
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


180 Language Basics

Return Operator
The return operator terminates the current function execution and returns control to the calling
program. The expression calculation result is returned to the calling function. The expression can
contain an assignment operator.
Example:

int CalcSum(int x, int y)


{
return(x+y);
}

In functions with the void return type, the return operator without expression must be used:
void SomeFunction()
{
Print("Hello!");
return; // this operator can be removed
}

The right brace of the function means implicit execution of the return operator without expression.
W hat can be returned: simple types, simple structures, object pointers. W ith the return operator you
can't return any arrays, class objects, variables of compound structure type.
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


181 Language Basics

If-Else Conditional Operator


The IF - ELSE operator is used when a choice must be made. Formally, the syntax is as follows :
if (expression)
operator1
else
operator2

If the expression is true, operator1 is executed and control is given to the operator that follows
operator2 (operator2 is not executed). If the expression is false, operator2 is executed.
The else part of the if operator can be omitted. Thus, a divergence may appear in nested if operators
with omitted else part. In this case, else addresses to the nearest previous if operator in the same
block that has no else part.
Examples:

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


if(x>1)
if(y==2) z=5;
else z=6;
//--- The else part refers to the first if operator:
if(x>l)
{
if(y==2) z=5;
}
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");

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


182 Language Basics

Ternary Operator ?:
The general form of the ternary operator is as follows :
expression1 ? expression2 : expression3

For the first operand - " expression1" - any expression that results in a bool type value can be used. If
the result is true, then the operator set by the second operand, i.e. " expression2" is executed.
If the first operand is false, the third operand - " expression3" is performed. The second and third
operands, i.e. " expression2" and " expression3" should return values of one type and should not be of
void type. The result of the conditional operator execution is the result of expression2 or result of the
expression3, depending on the result of expression1.
//--- normalize difference between open and close prices for a day range
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 the range is not null

Operator Use Restrictions


Based on the value of " expression1" , the operator must return one of the two values - either
" expression2" or " expression3" . There are several limitations to these expressions :
1 . Do not mix user-defined type with simple type or enumeration. NULL can be used for the pointer.
2. If types of values are simple, the operator will be of the maximum type (see Type casting).
3. If one of the values is an enumeration and the second one is of a numeric type, the enumeration is
replaced by int and the second rule is applied.
4. If both values are enumerations, their types must be identical, and the operator will be of type
enumeration.
R estrictions for the user-defined types (classes or structures):
a) Types must be identical or one should be derived from the other one.
b) If types are not identical (inheritance), then the child is implicitly cast to the parent, i.e. the
operator will be of the parent type.
c) Do not mix object and the pointer – both expressions must be either objects or pointers. NULL can
be used for the pointer.
Note

Be careful when using the conditional operator as an argument of an overloaded function, because the
type of the result of a conditional operator is defined at the time of program compilation. And this
type is determined as the larger of the types " expression2" and " expression3" .
Example:

© 2000-2025, MetaQuotes Ltd.


183 Language Basics

void func(double d) { Print("double argument: ",d); }


void func(string s) { Print("string argument: ",s); }

bool Expression1=true;
double Expression2=M_PI;
string Expression3="3.1415926";

void OnStart()
{
func(Expression2);
func(Expression3);

func(Expression1?Expression2:Expression3); // warning on implicit casting to string


func(!Expression1?Expression2:Expression3); // warning on implicit casting to string
}

// Result:
// double argument: 3.141592653589793
// string argument: 3.1415926
// string argument: 3.141592653589793
// string argument: 3.1415926

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


184 Language Basics

Switch Operator
Compares the expression value with constants in all the case variants and passes control to the
operator that corresponds to the expression value. Each variant of case can be marked with an integer
constant, a literal constant or a constant expression. The constant expression can't contain variables
or function calls. Expression of the switch operator must be of integer type – int or uint.
switch(expression)
{
case constant: operators
case constant: operators
...
default: operators
}

Operators marked by the default label are executed if none of the constants in case operators is equal
to the expression value. The default variant should not be necessarily declared and should not be
necessarily the last one. If none of the constants corresponds to the expression value and the default
variant is not available, no actions are executed.
The case keyword with a constant are just labels, and if operators are executed for some case variant,
the program will further execute the operators of all subsequent variants until the break operator
occurs. It allows to bind a sequence of operators with several variants.
A constant expression is calculated during compilation. No two constants in one switch operator can
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;

© 2000-2025, MetaQuotes Ltd.


185 Language Basics

default:
res="default";break;
case 2:
res=i;break;
case 3:
res=i;break;
}
Print(res);
/*
Result
default
*/

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


186 Language Basics

While Loop Operator


The while operator consists of a checked expression and the operator, which must be fulfilled:
while(expression)
operator;

If the expression is true, the operator is executed until the expression becomes false. If the
expression is false, the control is passed to the next operator. The expression value is defined before
the operator is executed. Therefore, if the expression is false from the very beginning, the operator
will not be executed at all.
Note

If it is expected that a large number of iterations will be handled in a loop, it is advisable that you
check the fact of forced program termination using the Is S topped() function.
Example:

while(k<n && !IsStopped())


{
y=y*x;
k++;
}

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


187 Language Basics

For Loop Operator


The for operator consists of three expressions and an executable operator:
for(expression1; expression2; expression3)
operator;

Expression1 describes the loop initialization. Expression2 checks the conditions of the loop
termination. If it is true, the loop body for is executed. The loop repeats expression2 until it becomes
false. If it is false, the loop is terminated, and control is given to the next operator. Expression3 is
calculated after each iteration.
The for operator is equivalent to the following succession of operators :
expression1;
while(expression2)
{
operator;
expression3;
};

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

If it is expected that a large number of iterations will be handled in a loop, it is advisable that you
check the fact of forced program termination using the Is S topped() function.
Examples:

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

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


188 Language Basics

Loop Operator do while


The for and while loops check the termination at the beginning, not at the end of a loop. The third
loop operator do - while checks the condition of termination at the end, after each loop iteration. The
loop body is always executed at least once.
do
operator;
while(expression);

Firstthe operator is executed, then the expression is calculated. If it is true, then the operator is
executed again, and so on. If the expression becomes false, the loop terminates.
Note

If it is expected that a large number of iterations will be handled in a loop, it is advisable that you
check the fact of forced program termination using the Is S topped() function.
Example:

//--- Calculate the Fibonacci series


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 an infinite loop will appear!
}
while(i<counterFibonacci && !IsStopped());

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


189 Language Basics

Break Operator
The break operator terminates the execution of the nearest nested outward switch, while, do-while or
for operator. The control is passed to the operator that follows the terminated one. One of the
purposes of this operator is to finish the looping execution when a certain value is assigned to a
variable.
Example:

//--- searching for the first zero element


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

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


190 Language Basics

Continue Operator
The continue operator passes control to the beginning of the nearest outward loop while, do-while or
for operator, the next iteration being called. The purpose of this operator is opposite to that of break
operator.
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);
}

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


191 Language Basics

Object Create Operator new


The new operator automatically creates an object of a corresponding size, calls the object constructor
and returns a descriptor of created object. In case of failure, the operator returns a null descriptor
that can be compared with the NULL constant.
The new operator can be applied only to class objects. It can't be applied to structures.
The operator shall not be used to create arrays of objects. To do this, use the ArrayResize() function.
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;
}
//--- draw
if(m_shape!=NULL)
{
//--- pre-settings
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 object descriptor is not a pointer to memory address.


An object created with the new operator must be explicitly removed using the delete operator.
See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


192 Language Basics

Object Delete Operator delete


The delete operator deletes an object created by the new operator, calls the corresponding class
destructor and frees up memory occupied by the object. A real descriptor of an existing object is used
as an operand. After the delete operation is executed, the object descriptor becomes invalid.
Example:

//--- delete figure


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

See also
Initialization of Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


193 Language Basics

Functions
Every tas k can be divided into subtas ks, each of which can either be directly represented in the form
of a code, or divided into smaller sub-tas ks. This method is called stepwise refinement. Functions are
used for writing the code of sub-tas ks to be solved. The code that describes what a function does is
called function definition:
function_header
{
instructions
}

All that is
before the first brace is the header of the function definition, and what is between braces is
the body of the function definition. The function header includes a description of the return value
type, name (identifier) and formal parameters. The number of parameters passed to the function is
limited and cannot exceed 64.
The function can be called from other parts of the program as many times as necessary. In fact, the
return type, function identifier and parameter types constitute the function prototype.
Function prototype is the function declaration, but not its definition. Due to the explicit declaration of
the return type and a list of argument types, the strict type checking and implicit typecasting are
possible during function calls. Very often function declarations are used in classes to improve the code
readability.
The function definition must exactly match its declaration. Each declared function must be defined.
Example:

double // return value type


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

The return operator can return the value of an expression located in this operator. If necessary, the
expression value is converted to the function result type. W hat can be returned: simple types, simple
structures, object pointers. W ith the return operator you can't return any arrays, class objects,
variables of compound structure type.
A function that returns no value should be described as that of void type.
Example:

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

© 2000-2025, MetaQuotes Ltd.


194 Language Basics

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("Required parameter a = ",a);
Print("Pass the following parameters: d = ",d," n = ",n," b = ",b," s = ",s);
return(0);
}

If any of parameters has a default value, all subsequent parameters must also have default values.
Example of incorrect declaration:

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

See also
Overload, Virtual Functions, Polymorphism

© 2000-2025, MetaQuotes Ltd.


195 Language Basics

Function Call
If a name that has not been described before, appears in the expression and is followed by the left
parenthesis, it is contextually considered as the name of a function.
function_name (x1, x2,..., xn)

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

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

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

void somefunc(double init,


double sec=0.0001, //set default values
int level=10);
//...
somefunc(); // Wrong call. The first parameter must be presented.
somefunc(3.14); // Correct call
somefunc(3.14,0.0002); // Correct call
somefunc(3.14,0.0002,10); // Correct call

W hen calling a function, one may not s kip parameters, even those having default values :
somefunc(3.14, , 10); // Wrong call -> the second parameter was skipped.

See also
Overload, Virtual Functions, Polymorphism

© 2000-2025, MetaQuotes Ltd.


196 Language Basics

Passing Parameters
There are two methods, by which the machine language can pass arguments to a subprogram
(function). The first method is to send a parameter by value. This method copies the argument value
into a formal function parameter. Therefore, any changes in this parameter within the function have
no influence on the corresponding call argument.
//+------------------------------------------------------------------+
//| 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 is to pass by reference. In this case, reference to a parameter (not its value) is
passed to a function parameter. Inside the function, it is used to refer to the actual parameter
specified in the call. This means that the parameter changes will affect the argument used to call the
function.
//+------------------------------------------------------------------+
//| Passing parameters by reference |
//+------------------------------------------------------------------+
double SecondMethod(int &i,int &j)
{
double res;
//---
i*=2;
j/=2;
res=i+j;

© 2000-2025, MetaQuotes Ltd.


197 Language Basics

//---
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 execution
// a and b before call: 14 8
// a and b after call: 28 4

MQL5 uses both methods, with one exception: arrays, structure type variables and class objects are
always passed by reference. In order to avoid changes in actual parameters (arguments passed at
function call) use the access specifier const. W hen trying to change the contents of a variable declared
with the const specifier, the compiler will generate an error.

Note

It should be noted that parameters are passed to a function in reversed order, i.e., first the last
parameter is calculated and passed, and then the last but one, etc. The last calculated and passed
parameter is the one that stands first after opening parenthesis.
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)
{

© 2000-2025, MetaQuotes Ltd.


198 Language Basics

Print(comment,": par1 = ",par1," par2 = ",par2);


}

In first call (see example above) the i variable is first used in strings concatenation:
"First call (i = "+string(i)+")"

H ere its value doesn't change. Then the i variable is used in calculation of the a[i++] array element,
i.e. when array element with index i is accessed, the i variable is incremented. And only after that the
first parameter with changed value of i variable is calculated.
In the second call the same value of i (calculated on the first phase of function calling) is used when
calculating all three parameters. Only after the first parameters is calculated the i variable is changed
again.
See also
Visibility S cope and Lifetime of Variables, Overload, Virtual Functions, Polymorphism

© 2000-2025, MetaQuotes Ltd.


199 Language Basics

Function Overloading
Usually the function name tends to reflect its main purpose. As a rule, readable programs contain
various well selected identifiers. S ometimes different functions are used for the same purposes. Let's
consider, for example, a function that calculates the average value of an array of double precision
numbers and the same function, but operating with an array of integers. Both are convenient to be
called AverageFromArray:
//+------------------------------------------------------------------+
//| The calculation of average for an array of double type |
//+------------------------------------------------------------------+
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]; // Summation for the double
}
aver=sum/size; // Just divide the sum by the number
//---
Print("Calculation of the average for an array of double type");
return aver;
}
//+------------------------------------------------------------------+
//| The calculation of average for an array of int type |
//+------------------------------------------------------------------+
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]; // Summation for the int
}
aver=(double)sum/size;// Give the amount of type double, and divide
//---
Print("Calculation of the average for an array of int type");
return aver;
}

Each function contains the message output via the Print() function;
Print("Calculation of the average for an array of int type");

© 2000-2025, MetaQuotes Ltd.


200 Language Basics

The compiler selects a necessary function in accordance with the types of arguments and their
quantity. The rule, according to which the choice is made, is called the signature matching algorithm.
A signature is 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 int type
// Calculate the average for an array of double type
// int_aver= 3.00000000 double_aver= 3.30000000

Function overloading is a process of creating several functions with the same name, but different
parameters. This means that in overloaded variants of a function, the number of arguments and/or
their type must be different. A specific function variant is selected based on the correspondence of
the list of arguments when calling the function, to the list of parameters in the function declaration.
W hen an overloaded function is called, the compiler must have an algorithm to select the appropriate
function. The algorithm that performs this choice depends on castings of what types are present. The
best correspondence must be unique. An overloaded function must be the best match among all the
other variants for at least one argument. At the same time it must match for all other arguments not
worse than other variants.
Below is a matching algorithm for each argument.

Algorithm of Choosing an Overloaded Function


1. Use strict matching (if possible).
2. Try standard type increase.
3. Try standard typecasting.

The standard type increase is better than other standard conversions. Increase is the conversion of
float to double, of bool, char, short or enum to int. Typecasting of arrays of similar integer types also
belongs to typecasting. S imilar types are: bool, char, uchar, since all the three types are single-byte
integers ; double-byte integers short and ushort; 4-byte integers int, uint, and color; long, ulong, and
datetime.
Of course, the strict matching is the best. To achieve such a consistency typecasting can be used. The
compiler cannot cope with ambiguous situations. Therefore you should not rely on subtle differences of
types and implicit conversions that make the overloaded function unclear.

© 2000-2025, MetaQuotes Ltd.


201 Language Basics

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


Examples of overloaded functions in MQL5 can be seen in the example of ArrayInitialize() functions.
Function overloading rules apply to overload of class methods.

Overloading of system functions is allowed, but it should be observed that the compiler is able to
accurately select the necessary function. For example, we can overload the system function MathMax()
in 4 different ways, but only two variants are correct.
Example:

// 1. overload is allowed - function differs from built-in MathMax() function in the number of para
double MathMax(double a,double b,double c);

// 2. overload is not allowed!


// number of parameters is different, but the last has a default value
// this leads to the concealment of the system function when calling, which is unacceptable
double MathMax(double a,double b,double c=DBL_MIN);

// 3. overload is allowed - normal overload by type of parameters a and b


double MathMax(int a,int b);

// 4. overload is not allowed!


// the number and types of parameters are the same as in original double MathMax(double a,double b)
int MathMax(double a,double b);

See also
Overload, Virtual Functions, Polymorphism

© 2000-2025, MetaQuotes Ltd.


202 Language Basics

Operation Overloading
For ease of code reading and writing, overloading of some operations is allowed. Overloading operator
is written using the keyword operator. The following operators can be overloaded:
· binary +,-,/,*,%,<<,>>,==,!=,<,>,<=,>=,=,+=,-=,/=,*=,%=,&=,|=,^=,<<=,>>=,&&,||,&,|,^
· unary +,-,++,--,!,~
· assignment operator =
· indexing operator []

Operation overloading allows the use of the operating notation (written in the form of simple
expressions) for complex objects - structures and classes. W riting expressions using overloaded
operations simplifies the view of the source code, because a more complex implementation is hidden.
For example, consider complex numbers, which consist of real and imaginary parts. They are widely
used in mathematics. The MQL5 language has no data type to represent complex numbers, but it is
possible to create a new data type in the form of a structure or class. Declare the complex structure
and define four methods that implement four arithmetic operations :
//+------------------------------------------------------------------+
//| A structure for operations with complex numbers |
//+------------------------------------------------------------------+
struct complex
{
double re; // Real part
double im; // Imaginary part
//--- Constructors
complex():re(0.0),im(0.0) { }
complex(const double r):re(r),im(0.0) { }
complex(const double r,const double i):re(r),im(i) { }
complex(const complex &o):re(o.re),im(o.im) { }
//--- Arithmetic operations
complex Add(const complex &l,const complex &r) const; // Addition
complex Sub(const complex &l,const complex &r) const; // Subtraction
complex Mul(const complex &l,const complex &r) const; // Multiplication
complex Div(const complex &l,const complex &r) const; // Division
};

Now, in our code we can declare variables representing complex numbers, and work with them.
For example:
void OnStart()
{
//--- Declare and initialize variables of a complex type
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f, b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);
//--- Sum up two numbers
complex z;

© 2000-2025, MetaQuotes Ltd.


203 Language Basics

z=a.Add(a,b);
PrintFormat("a+b=%.2f+i*%.2f",z.re,z.im);
//--- Multiply two numbers
z=a.Mul(a,b);
PrintFormat("a*b=%.2f+i*%.2f",z.re,z.im);
//--- Divide two numbers
z=a.Div(a,b);
PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//---
}

But it would be more convenient to use usual operators " +" , " -" , "*" and "/" for ordinary arithmetic
operations with complex numbers.
Keyword operator is used for defining a member function that performs type conversion. Unary and
binary operations for class object variables can be overloaded as non-static member functions. They
implicitly act on the class object.
Most binary operations can be overloaded like regular functions that take one or both arguments as a
class variable or a pointer to an object of this class. For our type complex, overloading in the
declaration will look like this :
//--- Operators
complex operator+(const complex &r) const { return(Add(this,r)); }
complex operator-(const complex &r) const { return(Sub(this,r)); }
complex operator*(const complex &r) const { return(Mul(this,r)); }
complex operator/(const complex &r) const { return(Div(this,r)); }

The full example of the script:


//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Declare and initialize variables of type complex
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f, b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);
//a.re=5;
//a.im=1;
//b.re=-1;
//b.im=-5;
//--- Sum up two numbers
complex z=a+b;
PrintFormat("a+b=%.2f+i*%.2f",z.re,z.im);
//--- Multiply two numbers

z=a*b;
PrintFormat("a*b=%.2f+i*%.2f",z.re,z.im);
//--- Divide two numbers
z=a/b;

© 2000-2025, MetaQuotes Ltd.


204 Language Basics

PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//---
}
//+------------------------------------------------------------------+
//| A structure for operations with complex numbers |
//+------------------------------------------------------------------+
struct complex
{
double re; // Real part
double im; // Imaginary part
//--- Constructors
complex():re(0.0),im(0.0) { }
complex(const double r):re(r),im(0.0) { }
complex(const double r,const double i):re(r),im(i) { }
complex(const complex &o):re(o.re),im(o.im) { }
//--- Arithmetic operations
complex Add(const complex &l,const complex &r) const; // Addition
complex Sub(const complex &l,const complex &r) const; // Subtraction
complex Mul(const complex &l,const complex &r) const; // Multiplication
complex Div(const complex &l,const complex &r) const; // Division
//--- Binary operators
complex operator+(const complex &r) const { return(Add(this,r)); }
complex operator-(const complex &r) const { return(Sub(this,r)); }
complex operator*(const complex &r) const { return(Mul(this,r)); }
complex operator/(const complex &r) const { return(Div(this,r)); }
};
//+------------------------------------------------------------------+
//| Addition |
//+------------------------------------------------------------------+
complex complex::Add(const complex &l,const complex &r) const
{
complex res;
//---
res.re=l.re+r.re;
res.im=l.im+r.im;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Subtraction |
//+------------------------------------------------------------------+
complex complex::Sub(const complex &l,const complex &r) const
{
complex res;
//---
res.re=l.re-r.re;
res.im=l.im-r.im;
//--- Result
return res;

© 2000-2025, MetaQuotes Ltd.


205 Language Basics

}
//+------------------------------------------------------------------+
//| Multiplication |
//+------------------------------------------------------------------+
complex complex::Mul(const complex &l,const complex &r) const
{
complex res;
//---
res.re=l.re*r.re-l.im*r.im;
res.im=l.re*r.im+l.im*r.re;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Division |
//+------------------------------------------------------------------+
complex complex::Div(const complex &l,const complex &r) const
{
//--- Empty complex number
complex res(EMPTY_VALUE,EMPTY_VALUE);
//--- Check for zero
if(r.re==0 && r.im==0)
{
Print(__FUNCTION__+": number is zero");
return(res);
}
//--- Auxiliary variables
double e;
double f;
//--- Selecting calculation variant
if(MathAbs(r.im)<MathAbs(r.re))
{
e = r.im/r.re;
f = r.re+r.im*e;
res.re=(l.re+l.im*e)/f;
res.im=(l.im-l.re*e)/f;
}
else
{
e = r.re/r.im;
f = r.im+r.re*e;
res.re=(l.im+l.re*e)/f;
res.im=(-l.re+l.im*e)/f;
}
//--- Result
return res;
}

© 2000-2025, MetaQuotes Ltd.


206 Language Basics

Most unary operations for classes can be overloaded as ordinary functions that accept a single class
object argument or a pointer to it. Add overloading of unary operations " -" and "!" .
//+------------------------------------------------------------------+
//| A structure for operations with complex numbers |
//+------------------------------------------------------------------+
struct complex
{
double re; // Real part
double im; // Imaginary part
...
//--- Unary operators
complex operator-() const; // Unary minus
bool operator!() const; // Negation
};
...
//+------------------------------------------------------------------+
//| Overloading the "unary minus" operator |
//+------------------------------------------------------------------+
complex complex::operator-() const
{
complex res;
//---
res.re=-re;
res.im=-im;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Overloading the "logical negation" operator |
//+------------------------------------------------------------------+
bool complex::operator!() const
{
//--- Are the real and imaginary parts of the complex number equal to zero?
return (re!=0 && im!=0);
}

Now we can check the value of a complex number for zero and get a negative value:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Declare and initialize variables of type complex
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f, b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);
//--- Divide the two numbers

© 2000-2025, MetaQuotes Ltd.


207 Language Basics

complex z=a/b;
PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//--- A complex number is equal to zero by default (in the default constructor re==0 and im==0)
complex zero;
Print("!zero=",!zero);
//--- Assign a negative value
zero=-z;
PrintFormat("z=%.2f+i*%.2f, zero=%.2f+i*%.2f",z.re,z.im, zero.re,zero.im);
PrintFormat("-zero=%.2f+i*%.2f",-zero.re,-zero.im);
//--- Check for zero once again
Print("!zero=",!zero);
//---
}

Note that we did not have to overload the assignment operator "=" , as structures of simple types can
be directly copied one into each other. Thus, we can now write a code for calculations involving
complex numbers in the usual manner.
Overloading of the indexing operator allows to obtain the values of the arrays enclosed in an object, in
a simple and familiar way, and it also contributes to a better readability of the source code. For
example, we need to provide access to a symbol in the string at the specified position. A string in
MQL5 is a separate type string, which is not an array of symbols, but with the help of an overloaded
indexing operation we can provide a simple and transparent work in the generated CS tring class :
//+------------------------------------------------------------------+
//| Class to access symbols in string as in array of symbols |
//+------------------------------------------------------------------+
class CString
{
string m_string;

public:
CString(string str=NULL):m_string(str) { }
ushort operator[] (int x) { return(StringGetCharacter(m_string,x)); }
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- An array for receiving symbols from a string
int x[]={ 19,4,18,19,27,14,15,4,17,0,19,14,17,27,26,28,27,5,14,
17,27,2,11,0,18,18,27,29,30,19,17,8,13,6 };
CString str("abcdefghijklmnopqrstuvwxyz[ ]CS");
string res;
//--- Make up a phrase using symbols from the str variable
for(int i=0,n=ArraySize(x);i<n;i++)
{
res+=ShortToString(str[x[i]]);
}

© 2000-2025, MetaQuotes Ltd.


208 Language Basics

//--- Show the result


Print(res);
}

Another example of overloading of the indexing operation is operations with matrices. The matrix
represents a two-dimensional dynamic array, the array size is not defined in advance. Therefore, you
cannot declare an array of form array[][] without specifying the size of the second dimension, and
then pass this array as a parameter. A possible solution is a special class CMatrix, which contains an
array of CRow class objects.
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Operations of addition and multiplication of matrices
CMatrix A(3),B(3),C();
//--- Prepare an array for rows
double a1[3]={1,2,3}, a2[3]={2,3,1}, a3[3]={3,1,2};
double b1[3]={3,2,1}, b2[3]={1,3,2}, b3[3]={2,1,3};
//--- Fill the matrices
A[0]=a1; A[1]=a2; A[2]=a3;
B[0]=b1; B[1]=b2; B[2]=b3;
//--- Output the matrices in the Experts log
Print("---- Elements of matrix A");
Print(A.String());
Print("---- Elements of matrix B");
Print(B.String());

//--- Addition of matrices


Print("---- Addition of matrices A and B");
C=A+B;
//--- Output the formatted string representation
Print(C.String());

//--- Multiplication of matrices


Print("---- Multiplication of matrices A and B");
C=A*B;
Print(C.String());

//--- Now we show how to get values in the style of dynamic arrays matrix[i][j]
Print("Output the values of matrix C elementwise");
//--- Go through the matrix rows - CRow objects - in a loop
for(int i=0;i<3;i++)
{
string com="| ";
//--- Form rows from the matrix for the value
for(int j=0;j<3;j++)
{

© 2000-2025, MetaQuotes Ltd.


209 Language Basics

//--- Get the matrix element by the number of the row and column
double element=C[i][j];// [i] - Access to CRow in the array m_rows[] ,
// [j] - Overloaded operator of indexing in CRow
com=com+StringFormat("a(%d,%d)=%G ; ",i,j,element);
}
com+="|";
//--- Output the values of the row
Print(com);
}
}
//+------------------------------------------------------------------+
//| Class "Row" |
//+------------------------------------------------------------------+
class CRow
{
private:
double m_array[];
public:
//--- Constructors and a destructor
CRow(void) { ArrayResize(m_array,0); }
CRow(const CRow &r) { this=r; }
CRow(const double &array[]);
~CRow(void){};
//--- Number of elements in the row
int Size(void) const { return(ArraySize(m_array));}
//--- Returns a string with values
string String(void) const;
//--- Indexing operator
double operator[](int i) const { return(m_array[i]); }
//--- Assignment operators
void operator=(const double &array[]); // An array
void operator=(const CRow & r); // Another CRow object
double operator*(const CRow &o); // CRow object for multiplication
};
//+------------------------------------------------------------------+
//| Constructor for initializing a row with an array |
//+------------------------------------------------------------------+
void CRow::CRow(const double &array[])
{
int size=ArraySize(array);
//--- If the array is not empty
if(size>0)
{
ArrayResize(m_array,size);
//--- Fill with values
for(int i=0;i<size;i++)
m_array[i]=array[i];
}
//---

© 2000-2025, MetaQuotes Ltd.


210 Language Basics

}
//+------------------------------------------------------------------+
//| Assignment operation for the array |
//+------------------------------------------------------------------+
void CRow::operator=(const double &array[])
{
int size=ArraySize(array);
if(size==0) return;
//--- Fill the array with values
ArrayResize(m_array,size);
for(int i=0;i<size;i++) m_array[i]=array[i];
//---
}
//+------------------------------------------------------------------+
//| Assignment operation for CRow |
//+------------------------------------------------------------------+
void CRow::operator=(const CRow &r)
{
int size=r.Size();
if(size==0) return;
//--- Fill the array with values
ArrayResize(m_array,size);
for(int i=0;i<size;i++) m_array[i]=r[i];
//---
}
//+------------------------------------------------------------------+
//| Operator of multiplication by another row |
//+------------------------------------------------------------------+
double CRow::operator*(const CRow &o)
{
double res=0;
//--- Verifications
int size=Size();
if(size!=o.Size() || size==0)
{
Print(__FUNCSIG__,": Failed to multiply two matrices, their sizes are different");
return(res);
}
//--- Multiply arrays elementwise and add the products
for(int i=0;i<size;i++)
res+=m_array[i]*o[i];
//--- Result
return(res);
}
//+------------------------------------------------------------------+
//| Returns a formatted string representation |
//+------------------------------------------------------------------+
string CRow::String(void) const
{

© 2000-2025, MetaQuotes Ltd.


211 Language Basics

string out="";
//--- If the size of the array is greater than zero
int size=ArraySize(m_array);
//--- We work only with a non-zero number of array elements
if(size>0)
{
out="{";
for(int i=0;i<size;i++)
{
//--- Collect the values to a string
out+=StringFormat(" %G;",m_array[i]);
}
out+=" }";
}
//--- Result
return(out);
}
//+------------------------------------------------------------------+
//| Class "Matrix" |
//+------------------------------------------------------------------+
class CMatrix
{
private:
CRow m_rows[];

public:
//--- Constructors and a destructor
CMatrix(void);
CMatrix(int rows) { ArrayResize(m_rows,rows); }
~CMatrix(void){};
//--- Get the matrix sizes
int Rows() const { return(ArraySize(m_rows)); }
int Cols() const { return(Rows()>0? m_rows[0].Size():0); }
//--- Returns the value of the column in the form of a CRow row
CRow GetColumnAsRow(const int col_index) const;
//--- Returns a string with the matrix values
string String(void) const;
//--- The indexing operator returns a string by its number
CRow *operator[](int i) const { return(GetPointer(m_rows[i])); }
//--- Addition operator
CMatrix operator+(const CMatrix &m);
//--- Multiplication operator
CMatrix operator*(const CMatrix &m);
//--- Assignment operator
CMatrix *operator=(const CMatrix &m);
};
//+------------------------------------------------------------------+
//| A default constructor, create an array of rows of zero size |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


212 Language Basics

CMatrix::CMatrix(void)
{
//--- The zero number of rows in the matrix
ArrayResize(m_rows,0);
//---
}
//+------------------------------------------------------------------+
//| Returns the column value in the form of CRow |
//+------------------------------------------------------------------+
CRow CMatrix::GetColumnAsRow(const int col_index) const
{
//--- A variable to get the values from the column
CRow row();
//--- The number of rows in the matrix
int rows=Rows();
//--- If the number of rows is greater than zero, execute the operation
if(rows>0)
{
//--- An array to receive the values of the column with index col_index
double array[];
ArrayResize(array,rows);
//--- Filling the array
for(int i=0;i<rows;i++)
{
//--- Check the number of the column for row i - it may exceed the boundaries of the array
if(col_index>=this[i].Size())
{
Print(__FUNCSIG__,": Error! Column number ",col_index,"> row size ",i);
break; // row will be uninitialized object
}
array[i]=this[i][col_index];
}
//--- Create a CRow row based on the array values
row=array;
}
//--- Result
return(row);
}
//+------------------------------------------------------------------+
//| Addition of two matrices |
//+------------------------------------------------------------------+
CMatrix CMatrix::operator+(const CMatrix &m)
{
//--- The number of rows and columns in the passed matrix
int cols=m.Cols();
int rows=m.Rows();
//--- The matrix to receive the addition results
CMatrix res(rows);
//--- The sizes of the matrix must match

© 2000-2025, MetaQuotes Ltd.


213 Language Basics

if(cols!=Cols() || rows!=Rows())
{
//--- Addition impossible
Print(__FUNCSIG__,": Failed to add two matrices, their sizes are different");
return(res);
}
//--- Auxiliary array
double arr[];
ArrayResize(arr,cols);
//--- Go through rows to add
for(int i=0;i<rows;i++)
{
//--- Write the results of addition of matrix strings in the array
for(int k=0;k<cols;k++)
{
arr[k]=this[i][k]+m[i][k];
}
//--- Place the array to the matrix row
res[i]=arr;
}
//--- return the result of addition of matrices
return(res);
}
//+------------------------------------------------------------------+
//| Multiplication of two matrices |
//+------------------------------------------------------------------+
CMatrix CMatrix::operator*(const CMatrix &m)
{
//--- Number of columns of the first matrix, number of rows passed in the matrix
int cols1=Cols();
int rows2=m.Rows();
int rows1=Rows();
int cols2=m.Cols();
//--- Matrix to receive the addition result
CMatrix res(rows1);
//--- Matrices should be coordinated
if(cols1!=rows2)
{
//--- Multiplication impossible
Print(__FUNCSIG__,": Failed to multiply two matrices, format is not compatible "
"- number of columns in the first factor should be equal to the number of rows in the s
return(res);
}
//--- Auxiliary array
double arr[];
ArrayResize(arr,cols1);
//--- Fill the rows in the multiplication matrix
for(int i=0;i<rows1;i++)// Go through rows
{

© 2000-2025, MetaQuotes Ltd.


214 Language Basics

//--- Reset the receiving array


ArrayInitialize(arr,0);
//--- Go through elements in the row
for(int k=0;k<cols1;k++)
{
//--- Take values of column k of the matrix m in the for of CRow
CRow column=m.GetColumnAsRow(k);
//--- Multiply two rows and write the result of scalar multiplication of vectors in the i-
arr[k]=this[i]*column;
}
//--- place array arr[] in the i-th row of the matrix
res[i]=arr;
}
//--- Return the product of two matrices
return(res);
}
//+------------------------------------------------------------------+
//| Assignment operation |
//+------------------------------------------------------------------+
CMatrix *CMatrix::operator=(const CMatrix &m)
{
//--- Find and set the number of rows
int rows=m.Rows();
ArrayResize(m_rows,rows);
//--- Fill our rows with the values of rows of the passed matrix
for(int i=0;i<rows;i++) this[i]=m[i];
//---
return(GetPointer(this));
}
//+------------------------------------------------------------------+
//| String representation of the matrix |
//+------------------------------------------------------------------+
string CMatrix::String(void) const
{
string out="";
int rows=Rows();
//--- Form string by string
for(int i=0;i<rows;i++)
{
out=out+this[i].String()+"\r\n";
}
//--- Result
return(out);
}

See also
Overloading, Arithmetic Operations, Function Overloading, Precedence Rules

© 2000-2025, MetaQuotes Ltd.


215 Language Basics

Description of External Functions


External functions defined in another module must be explicitly described. The description includes
returned type, function name and series of input parameters with their types. The absence of such a
description can lead to errors when compiling, building, or executing a program. W hen 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

W ith the help of import, it is easy to describe functions that are called from external DLL or compiled
EX5 libraries. EX5 libraries are compiled ex5 files, which have the library property. Only function
described with the export modifier can be imported from EX5 libraries.
Please keep in mind that DLL and EX5 libraries should have different names (regardless of the
directories they are located in) if they are imported together. All imported functions have the scope
resolution corresponding to the library's " file name" .
Example:

#import "kernel32.dll"
int GetLastError();
#import "lib.ex5"
int GetLastError();
#import

class CFoo
{
public:
int GetLastError() { return(12345); }
void func()
{
Print(GetLastError()); // call of the class method
Print(::GetLastError()); // call of the MQL5 function
Print(kernel32::GetLastError()); // call of the DLL library function from kernel32.dll
Print(lib::GetLastError()); // call of the EX5 library function from lib.ex5
}
};

void OnStart()
{
CFoo foo;
foo.func();
}

© 2000-2025, MetaQuotes Ltd.


216 Language Basics

See also
Overload, Virtual Functions, Polymorphism

© 2000-2025, MetaQuotes Ltd.


217 Language Basics

Exporting Functions
A function declared in a mql5 program with the export postmodifier can be used in another mql5
program. S uch a function is called exportable, and it can be called from other programs after
compilation.
int Function() export
{
}

This modifier orders the compiler to add the function into the table of EX5 functions exported by this
ex5 file. Only function with such a modifier are accessible (" visible" ) from other mql5 programs.
The library property tells the compiler that the EX5-file will be a library, and the compiler will show it in
the header of EX5.
All functions that are planned as exportable ones must be marked with the export modifier.
See also
Overload, Virtual Functions, Polymorphism

© 2000-2025, MetaQuotes Ltd.


218 Language Basics

Event Handling Functions


The MQL5 language provides processing of some predefined events. Functions for handling these
events must be defined in a MQL5 program; function name, return type, composition of parameters (if
there are any) and their types must strictly conform to the description of the event handler function.
The event handler of the client terminal identifies functions, handling this or that event, by the type
of return value and type of parameters. If other parameters, not corresponding to below descriptions,
are specified for a corresponding function, or another return type is indicated for it, such a function
will not be used as an event handler.

OnStart

The OnS tart() function is the S tart event handler, which is automatically generated only for running
scripts. It must be of void type, with no parameters :

void OnStart();

For the OnS tart() function, the int return type can be specified.

OnInit

The OnInit() function is the Init event handler. It must be of void or int type, with no parameters :
void OnInit();

The Init event is generated immediately after an Expert Advisor or an indicator is downloaded; this
event is not generated for scripts. The OnInit() function is used for initialization. If OnInit() has the
int type of the return value, the non-zero return code means unsuccessful initialization, and it
generates the Deinit event with the code of deinitialization reason REAS ON_INITFAILED.
W hen returning INIT _FAIL ED, the EA is forcibly unloaded from the chart.
W hen returning INIT _FAIL ED, the indicator is not unloaded from the chart. The indicator remaining on
the chart is non-operational — event handlers are not called in the indicator.
To optimize input parameters of an Expert Advisor, it is recommended to use values of the
ENUM _INIT _RETCODE enumeration as the return code. These values are used for organizing the course
of optimization, including the selection of the most appropriate testing agents. During initialization of
an Expert Advisor before the start of testing you can request information about the configuration and
resources of an agent (the number of cores, amount of free memory, etc.) using the
TerminalInfoInteger() function. Based on the information obtained, you can either allow to use this
testing agent, or reject using it during the optimization of this Expert Advisor.
ENUM_INIT_RETCODE

Identifier Description

INIT_SUCCEEDED S uccessfulinitialization, testing of the Expert Advisor can be


continued.
This code means the same as a null value – the Expert Advisor
has been successfully initialized in the tester.

© 2000-2025, MetaQuotes Ltd.


219 Language Basics

Identifier Description

INIT_FAILED Initialization failed; there is no point in continuing testing


because of fatal errors. For example, failed to create an
indicator that is required for the work of the Expert Advisor.
This return value means the same as a value other than zero -
initialization of the Expert Advisor in the tester failed.
INIT_PARAM ETERS_INCORRECT This value means the incorrect set of input parameters. The
result string containing this return code is highlighted in red in
the general optimization table.
Testing for the given set of parameters of the Expert Advisor
will not be executed, the agent is free to receive a new tas k.
Upon receiving this value, the strategy tester will reliably not
pass this tas k to other agents for retry.
INIT_AGENT_NOT_SUITABLE No errors during initialization, but for some reason the agent is
not suitable for testing. For example, not enough memory, no
OpenCL support, etc.
After the return of this code, the agent will not receive tas k s
until the end of this optimization.

The OnInit() function of the void type always denotes successful initialization.

OnDeinit

The OnDeinit() function is called during deinitialization and is the Deinit event handler. It must be
declared as the void type and should have one parameter of the const int type, which contains the
code of deinitialization reason. If a different type is declared, the compiler will generate a warning,
but the function will not be called. For scripts the Deinit event is not generated and therefore the
OnDeinit() function can't be used in scripts.
void OnDeinit(const int reason);

The Deinit event is generated for Expert Advisors and indicators in the following cases :
· before reinitialization due to the change of a symbol or chart period, to which the mql5 program is
attached;
· before reinitialization due to the change of input parameters ;
· before unloading the mql5 program.
OnTick

The NewTick event is generated for Expert Advisors only when a new tick for a symbol is received, to
the chart of which the Expert Advisor is attached. It's useless to define the OnTick() function in a
custom indicator or script, because the NewTick event is not generated for them.
The Tick event is generated only for Expert Advisors, but this does not mean that Expert Advisors
required the OnTick() function, since not only NewTick events are generated for Expert Advisors, but
also events of Timer, BookEvent and ChartEvent are generated. It must be declared as the void type,
with no parameters :
void OnTick();

© 2000-2025, MetaQuotes Ltd.


220 Language Basics

OnTimer

The OnTimer() function is called when the Timer event occurs, which is generated by the system timer
only for Expert Advisors and indicators - it can't be used in scripts. The frequency of the event
occurrence is set when subscribing to notifications about this event to be received by the
EventS etTimer() function.

You can unsubscribe from receiving timer events for a particular Expert Advisor using the
EventKillTimer() function. The function must be defined with the void type, with no parameters :

void OnTimer();

It is recommended to call the EventS etTimer() function once in the OnInit() function, and the
EventKillTimer() function should be called once in OnDeinit().

Every Expert Advisor, as well as every indicator work s with its own timer and receives events only
from it. As soon as the mql5 program stops operating, the timer is destroyed forcibly, if it was created
but hasn't been disabled by the EventKillTimer() function.

OnTrade

The function is called when the Trade event occurs, which appears when you change the list of placed
orders and open positions, the history of orders and history of deals. W hen a trade activity is
performed (pending order opening, position opening/closing, stops setting, pending order triggering,
etc.) the history of orders and deals and/or list of positions and current orders is changed accordingly.
void OnTrade();

Users must independently implement in the code the verification of a trade account state when such
an event is received (if this is required by the trade strategy conditions). If the OrderS end() function
call has been completed successfully and returned a value of true, this means that the trading server
has put the order into the queue for execution and assigned a ticket number to it. As soon as the
server processes this order, the Trade event will be generated. And if a user remembers the ticket
value, he/she will be able to find out what happened to the order using this value during OnTrade()
event handling.

OnTradeTransaction

W hen performing some definite actions on a trade account, its state changes. S uch actions include:
· S ending a trade request from any MQL5 application in the client terminal using OrderS end and
OrderS endAsync functions and its further execution;
· S ending a trade request via the terminal graphical interface and its further execution;
· Pending orders and stop orders activation on the server;
· Performing operations on a trade server side.
The following trade transactions are performed as a result of these actions :
· handling a trade request;
· changing open orders ;
· changing orders history;
· changing deals history;

© 2000-2025, MetaQuotes Ltd.


221 Language Basics

· changing positions.
For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions. Arrival of such a transaction at the terminal is a
TradeTransaction event. It calls OnTradeTransaction handler
void OnTradeTransaction(
const MqlTradeTransaction& trans, // trade transaction structure
const MqlTradeRequest& request, // request structure
const MqlTradeResult& result // result structure
);

The handler contains three parameters :


· trans - this parameter gets M qlTradeTransaction structure describing a trade transaction applied to
a trade account;
· request - this parameter gets M qlTradeR equest structure describing a trade request;
· result - this parameter gets M qlTradeR esult structure describing a trade request execution result.

The last two request and result parameters are filled by values only for
TRADE_TRANSACTION_REQUES T type transaction, data on transaction can be received from type
parameter of trans variable. Note that in this case, request_id field in result variable contains ID of
request trade request, after the execution of which the trade transaction described in trans variable
has been performed. Request ID allows to associate the performed action (OrderS end or
OrderS endAsync functions call) with the result of this action sent to OnTradeTransaction().
One trade request manually sent from the terminal or via OrderS end()/OrderS endAsync() functions can
generate several consecutive transactions on the trade server. Priority of these transactions ' arrival at
the terminal is not guaranteed. Thus, you should not expect that one group of transactions will arrive
after another one when developing your trading algorithm.

· All types of trade transactions are described in ENUM _TRADE_TRANSACTION_TYPE enumeration.


· M qlTradeTransaction structure describing a trade transaction is filled in different ways
depending on a transaction type. For example, only type field (trade transaction type) must be
analyzed for TRADE_TRANSACTION_REQUES T type transactions. The second and third
parameters of OnTradeTransaction function (request and result) must be analyzed for additional
data. For more information, see "S tructure of a Trade Transaction" .
· A trade transaction description does not deliver all available information concerning orders,
deals and positions (e.g., comments). OrderGet*, HistoryOrderGet*, HistoryDealGet* and
PositionGet* functions should be used to get extended information.

After applying trade transactions for a client account, they are consistently placed to the terminal
trade transactions queue, from which they consistently sent to OnTradeTransaction entry point in
order of arrival at the terminal.
W hen handling trade transactions by an Expert Advisor using OnTradeTransaction handler, the
terminal continues handling newly arrived trade transactions. Therefore, the state of a trade account
can change during OnTradeTransaction operation already. For example, while an MQL5 program
handles an event of adding a new order, it may be executed, deleted from the list of the open ones
and moved to the history. Further on, the application will be notified of these events.

© 2000-2025, MetaQuotes Ltd.


222 Language Basics

Transactions queue length comprises 1024 elements. If OnTradeTransaction handles a new transaction
for too long, the old ones in the queue may be superseded by the newer ones.

· Generally, there is no accurate ratio of the number of OnTrade and OnTradeTransaction calls.
One OnTrade call corresponds to one or several OnTradeTransaction calls.
· OnTrade is called after appropriate OnTradeTransaction calls.

OnTester

The OnTester() function is the handler of the Tester event that is automatically generated after a
history testing of an Expert Advisor on the chosen interval is over. The function must be defined with
the double type, with no parameters :
double OnTester();

The function is called right before the call of OnDeinit() and has the same type of the return value -
double. OnTester() can be used only in the testing of Expert Advisors. Its main purpose is to calculate
a certain value that is used as the Custom max criterion in the genetic optimization of input
parameters.
In the genetic optimization descending sorting is applied to results within one generation. I.e. from
the point of view of the optimization criterion, the best results are those with largest values (for the
Custom max optimization criterion values returned by the OnTester function are taken into account).
In such a sorting, the worst values are positioned at the end and further thrown off and do not
participate in the forming of the next generation.

OnTesterInit

The function is called in EAs when the TesterInit event occurs to perform necessary actions before
optimization in the strategy tester. There are two function types.
The version that returns the result
int OnTesterInit(void);

Return Value

int type value, zero means successful initialization of an EA launched on a chart before optimization
starts.
The OnTesterInit() call that returns the execution result is recommended for use since it not only
allows for program initialization, but also returns an error code in case of an early optimization stop.
R eturn of any value other than INIT _SUCCEEDED (0) means an error, no optimization is launched.

The version without a result return is left only for compatibility with old codes. Not recommended
for use
void OnTesterInit(void);

W ith the start of optimization, an Expert Advisor with the OnTesterDeinit() or OnTesterPass() handler
is automatically loaded in a separate terminal chart with the symbol and period specified in the tester,
and receives the TesterInit event. The function is used for Expert Advisor initialization before the
start of optimization for further processing of optimization results.

© 2000-2025, MetaQuotes Ltd.


223 Language Basics

OnTesterPass

The OnTesterPass() function is the handler of the TesterPass event, which is automatically generated
when a frame is received during Expert Advisor optimization in the strategy tester. The function must
be defined with the void type. It has no parameters :
void OnTesterPass();

An Expert Advisor with the OnTesterPass() handler is automatically loaded in a separate terminal chart
with the symbol/period specified for testing, and gets TesterPass events when a frame is received
during optimization. The function is used for dynamic handling of optimization results " on the spot"
without waiting for its completion. Frames are added using the FrameAdd() function, which can be
called after the end of a single pass in the OnTester() handler.

OnTesterDeinit

OnTesterDeinit() is the handler of the TesterDeinit event, which is automatically generated after the
end of Expert Advisor optimization in the strategy tester. The function must be defined with the void
type. It has no parameters :
void OnTesterDeinit();

An Expert Advisor with the TesterDeinit() handler is automatically loaded on a chart at the start of
optimization, and receives TesterDeinit after its completion. The function is used for final processing
of all optimization results.

OnBookEvent

The OnBookEvent() function is the BookEvent handler. BookEvent is generated for Expert Advisors and
indicators when Depth of Market changes. It must be of the void type and have one parameter of the
string type:
void OnBookEvent (const string& symbol);

To receive BookEvent events for any symbol, you just need to pre-subscribe to receive these events
for this symbol using the MarketBookAdd() function. In order to unsubscribe from receiving the
BookEvent events for a particular symbol, call Mark etBookR elease().

Unlik e other events, the BookEvent event is broadcast. This means that if one Expert Advisor
subscribes to receiving BookEvent events using MarketBookAdd, all the other Experts Advisors that
have the OnBookEvent() handler will receive this event. It is therefore necessary to analyze the name
of the symbol, which is passed to the handler as the const string& symbol parameter.

OnChartEvent

OnChartEvent() is the handler of a group of ChartEvent events :


· CHARTEVENT_KEYDOWN — event of a keystroke, when the chart window is focused;
· CHARTEVENT_MOUSE_MOVE — mouse move events and mouse click events (if
CHART_EVENT_MOUSE_MOVE=true is set for the chart);
· CHARTEVENT_OBJECT_CREATE — event of graphical object creation (if
CHART_EVENT_OBJECT_CREATE=true is set for the chart);

© 2000-2025, MetaQuotes Ltd.


224 Language Basics

· CHARTEVENT_OBJECT_CHANGE — event of change of an object property via the properties dialog;


· CHARTEVENT_OBJECT_DELETE — event of graphical object deletion (if
CHART_EVENT_OBJECT_DELETE=true is set for the chart);
· CHARTEVENT_CLICK — event of a mouse click on the chart;
· CHARTEVENT_OBJECT_CLICK — event of a mouse click in a graphical object belonging to the chart;
· CHARTEVENT_OBJECT_DRAG — event of a graphical object move using the mouse;
· CHARTEVENT_OBJECT_ENDEDIT — event of the finished text editing in the entry box of the
LabelEdit graphical object;
· CHARTEVENT_CHART_CHANGE — event of chart changes ;
· CHARTEVENT_CUS TOM+n — ID of the user event, where n is in the range from 0 to 65535.
· CHARTEVENT_CUS TOM _LAS T — the last acceptable ID of a custom event (CHARTEVENT_CUS TOM
+65535).
The function can be called only in Expert Advisors and indicators. The function should be of void type
with 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
);

For each type of event, the input parameters of the OnChartEvent() function have definite values that
are required for the processing of this event. The events and values passed through these parameters
are listed in the table below.

Event Value of the id Value of the Value of the Value of the


parameter lparam dparam sparam
parameter parameter parameter

Event of a CHARTEVENT_KE code of a R epeat count The string value


k eystrok e YDOWN pressed key (the number of of a bit mas k
times the describing the
k eystrok e is status of
repeated as a k eyboard buttons
result of the user
holding down the
k ey)

Mouse events (if CHARTEVENT_MO the X coordinate the Y coordinate The string value
property USE_MOVE of a bit mas k
CHART_EVENT_ describing the
MOUSE_MOVE=tr status of mouse
ue is set for the buttons
chart)
Event of CHARTEVENT_OB — — Name of the
graphical object JECT _CREAT E created graphical
creation (if object
CHART_EVENT_O

© 2000-2025, MetaQuotes Ltd.


225 Language Basics

Event Value of the id Value of the Value of the Value of the


parameter lparam dparam sparam
parameter parameter parameter

BJECT _CREAT E=t


rue is set for the
chart)
Event of change CHARTEVENT_OB — — Name of the
of an object JECT _CHANGE modified
property via the graphical object
properties dialog
Event of CHARTEVENT_OB — — Name of the
graphical object JECT _DEL ET E deleted graphical
deletion (if object
CHART_EVENT_O
BJECT _DEL ET E=t
rue is set for the
chart)
Event of a CHARTEVENT_C the X coordinate the Y coordinate —
mouse click on LICK
the chart
Event of a CHARTEVENT_OB the X coordinate the Y coordinate Name of the
mouse click in a JECT _CLICK graphical object,
graphical object on which the
belonging to the event occurred
chart
Event of a CHARTEVENT_OB — — Name of the
graphical object JECT _DRAG moved graphical
dragging using object
the mouse
Event of the CHARTEVENT_OB — — Name of the
finished text JECT _ENDEDIT LabelEdit
editing in the graphical object,
entry box of the in which text
LabelEdit editing has
graphical object completed
Event of chart CHARTEVENT_C — — —
Changes HAR T _CHANGE

ID of the user CHARTEVENT_CU Value set by the Value set by the Value set by the
event under the S TOM+N EventChartCusto EventChartCusto EventChartCusto
N number m() function m() function m() function

OnCalculate

The OnCalculate() function is called only in custom indicators when it's necessary to calculate the
indicator values by the Calculate event. This usually happens when a new tick is received for the

© 2000-2025, MetaQuotes Ltd.


226 Language Basics

symbol, for which the indicator is calculated. This indicator is not required to be attached to any price
chart of this symbol.
The OnCalculate() function must have a return type int. There are two possible definitions. W ithin one
indicator you cannot use both versions of the function.
The first form is intended for those indicators that can be calculated on a single data buffer. An
example of such an indicator is Custom Moving Average.
int OnCalculate (const int rates_total, // size of the price[] array
const int prev_calculated, // bars handled on a previous call
const int begin, // where the significant data start from
const double& price[] // array to calculate
);

As the price[] array, one of timeseries or a calculated buffer of some indicator can be passed. To
determine the direction of indexing in the price[] array, call ArrayGetAs S eries(). In order not to
depend on the default values, you must unconditionally call the ArrayS etAs S eries() function for those
arrays, that are expected to work with.
Necessary time series or an indicator to be used as the price[] array can be selected by the user in the
" Parameters " tab when starting the indicator. To do this, you should specify the necessary item in the
drop-down list of "Apply to" field.

To receive values of a custom indicator from other mql5 programs, the iCustom() function is used,
which returns the indicator handle for subsequent operations. You can also specify the appropriate
price[] array or the handle of another indicator. This parameter should be transmitted last in the list
of input variables of the custom indicator.
Example:

void OnStart()
{
//---
string terminal_path=TerminalInfoString(STATUS_TERMINAL_PATH);

© 2000-2025, MetaQuotes Ltd.


227 Language Basics

int handle_customMA=iCustom(Symbol(),PERIOD_CURRENT, "Custom Moving Average",13,0, MODE_EMA,PRIC


if(handle_customMA>0)
Print("handle_customMA = ",handle_customMA);
else
Print("Cannot open or not EX5 file '"+terminal_path+"\\MQL5\\Indicators\\"+"Custom Moving Ave
}

In this example, the last parameter passed is the PRICE_TYPICAL value (from the
ENUM _APPLIED_PR ICE enumeration), which indicates that the custom indicator will be built on typical
prices obtained as (High+Low+Close)/3. If this parameter is not specified, the indicator is built based
on PRICE_CLOSE values, i.e. closing prices of each bar.
Another example that shows passing of the indicator handler as the last parameter to specify the
price[] array, is given in the description of the iCustom() function.

The second form is intended for all other indicators, in which more than one time series is used for
calculations.
int OnCalculate (const int rates_total, // size of input time series
const int prev_calculated, // bars handled in 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
);

Parameters of open[], high[], low[] and close[] contain arrays with open prices, high and low prices
and close prices of the current time frame. The time[] parameter contains an array with open time
values, the spread[] parameter has an array containing the history of spreads (if any spread is
provided for the traded security). The parameters of volume[] and tick_volume[] contain the history of
trade and tick volume, respectively.
To determine the indexing direction of time[], open[], high[], low[], close[], tick_volume[], volume[]
and spread[], call ArrayGetAs S eries(). In order not to depend on default values, you should
unconditionally call the ArrayS etAs S eries() function for those arrays, which are expected to work with.
The first rates _total parameter contains the number of bars, available to the indicator for calculation,
and corresponds to the number of bars available in the chart.
We should note the connection between the return value of OnCalculate() and the second input
parameter prev _calculated. During the function call, the prev _calculated parameter contains a value
returned by OnCalculate() during previous call. This allows for economical algorithms for calculating
the custom indicator in order to avoid repeated calculations for those bars that haven't changed since
the previous run of this function.
Forthis, it is usually enough to return the value of the rates _total parameter, which contains the
number of bars in the current function call. If since the last call of OnCalculate() price data has

© 2000-2025, MetaQuotes Ltd.


228 Language Basics

changed (a deeper history downloaded or history blanks filled), the value of the input parameter
prev _calculated will be set to zero by the terminal.
Note: if OnCalculate returns zero, then the indicator values are not shown in the DataW indow of the
client terminal.
To understand it better, it would be useful to start the indicator, which code 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 clrDarkBlue
#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(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| 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 symbol and chart period
int bars=Bars(Symbol(),0);
Print("Bars = ",bars,", rates_total = ",rates_total,", prev_calculated = ",prev_calculated);
Print("time[0] = ",time[0]," time[rates_total-1] = ",time[rates_total-1]);
//--- return value of prev_calculated for next call

© 2000-2025, MetaQuotes Ltd.


229 Language Basics

return(rates_total);
}
//+------------------------------------------------------------------+

See also
R unning Programs, Client Terminal Events, W orking with Events

© 2000-2025, MetaQuotes Ltd.


230 Language Basics

Variables
Declaring Variables

Variables must be declared before they are used. Unique names are used to identify variables. To
declare a variable, you must specify its type and a unique name. Declaration of variable is not an
operator.
S imple 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 – double-precision floating point number;
· float – single-precision floating point number;
· string – character strings.
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:

S tructures are composite data types, constructed using other types.


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

You can't declare variables of the structure type until you declare the structure.
Arrays

Array is the indexed sequence of identical-type data:


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

© 2000-2025, MetaQuotes Ltd.


231 Language Basics

Only an integer can be an array index. No more than four-dimensional arrays are allowed. Numbering
of array elements starts with 0. The last element of a one-dimensional array has the number which is 1
less than the array size. This means that call for the last element of an array consisting of 50 integers
will appear as a[49]. The same concerns multidimensional arrays : A dimension is indexed from 0 to
the dimension size-1. The last element of a two-dimensional array from the example will appear as
m[6][49].
S taticarrays can't be represented as timeseries, i.e., the ArrayS etAs S eries() function, which sets
access to array elements from the end to beginning, can't be applied to them. If you want to provide
access to an array the same as in timeseries, use the dynamic array object.
If there is an attempt to access out of the array range, the executing subsystem will generate a critical
error and the program will be stopped.

Built-in methods for working with arrays

The functions from the Array Functions section, as well as the built-in methods can be used to handle
the arrays :

Method Analog Description

void array.Fill(const scalar value,


ArrayFill, Fills the array with the specified
const int start_pos =0, const int
ArrayInitialize value
count=-1);
R eleases the dynamic array buffer
void array.Free(); ArrayFree and sets the zero dimension size to
0 (zero)

int array.Resize(const int


range0_size, const int reserve); S ets
a new size in the array first
ArrayR esize
int array.Resize(const int dimension
range_sizes [], const int reserve);
Displays simple type array values in
int array.Print(); ArrayPrint
the journal
R eturns the number of elements in
ArrayS ize,
int array.S ize(const int range=-1); the entire array (range=-1) or in the
ArrayR ange
specified array dimension
bool array.Is Dynamic(); ArrayIs Dynamic Checks if the array is dynamic
Checks if the array is an indicator
bool array.IsIndicatorBuffer();
buffer
bool array.Is S eries(); ArrayIs S eries Checks if the array is a timeseries
bool array.As S eries(); ArrayGetAs S eries Checks the array indexing direction
bool array.As S eries(const bool S ets the indexing direction in the
ArrayS etAs S eries
as _series); array
int array.Copy(const src_array[],
ArrayCopy Copies array values to another array
const int dst_start, const int

© 2000-2025, MetaQuotes Ltd.


232 Language Basics

Method Analog Description

src_start, const int cnt);


int array.Compare(const src_array[], R eturns the result of comparing two
const int dst_start, const int ArrayCompare simple type arrays or custom
src_start, const int cnt); structures
Inserts the specified number of
int array.Insert(const src_array[],
elements from a source array to a
const int dst_start, const int ArrayInsert
receiving one starting from a
src_start, const int cnt);
specified index
R emoves the specified number of
int array.Remove(const int
ArrayR emove elements from the array starting
start_pos, const int count);
with a specified index
R everses the specified number of
int array.Reverse(const int
ArrayR everse elements in the array starting with a
start_pos, const int count);
specified index
Exchanges the content with another
bool array.S wap(array& arr[]); ArrayS wap
dynamic array of the same type
S ortsnumeric arrays by the first
void array.S ort(sort_function); ArrayS ort
dimension
R eturns the index of the first
int array.S earch(scalar value,
ArrayBsearch element detected in the array first
search_function);
dimension
Performs a search in the array using
int array.Find((scalar value,
the passed function and returns the
search_function);
index of the first detected element
Performs a search in the array using
array array.S elect(scalar value,
the passed function and returns the
search_function);
array with all detected elements

Access Specifiers

Access specifiers define how the compiler can access variables, members of structures or classes.
The const specifier declares a variable as a constant, and does not allow to change this variable during
runtime. A single initialization of a variable is allowed when declaring it.
Example:

int OnCalculate (const int rates_total, // size of the price[] array


const int prev_calculated, // bars handled on a previous call
const int begin, // where the significant data start from
const double& price[] // array to calculate
);

© 2000-2025, MetaQuotes Ltd.


233 Language Basics

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


· public – allows unrestricted access to the variable or class method
· protected – allows access from methods of this class, as well as from methods of publicly inherited
classes. Other access is impossible;
· private – allows access to variables and class methods only from methods of the same class.
· virtual – applies only to class methods (but not to methods of structures) and tells the compiler that
this method should be placed in the table of virtual functions of the class.
Storage Classes

There are three storage classes : static, input and extern. These modifiers of a storage class explicitly
indicate to the compiler that corresponding variables are distributed in a pre-allocated area of
memory, which is called the global pool. Besides, these modifiers indicate the special processing of
variable data. If a variable declared on a local level is not a static one, memory for such a variable is
allocated automatically at a program stack. Freeing of memory allocated for a non-static array is also
performed automatically when going beyond the visibility area of the block, in which the array is
declared.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility S cope and
Lifetime of Variables, Creating and Deleting Objects, S tatic Members of a Class

© 2000-2025, MetaQuotes Ltd.


234 Language Basics

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

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

S cope of a variable is a program part, in which a variable can be referred to. Variables declared inside
a block (at the internal level), have the block as their scope. The block scope start with the variable
declaration and ends with the final right brace.
Local variables declared in the beginning of a function also have the scope of block, as well as function
parameters that are local variables. Any block can contain variable declarations. If blocks are nested
and the identifier in the external block has the same name as the identifier in the internal block, the
external block identifier is hidden, until the operation of the internal block is over.
Example:

void OnStart()
{
//---
int i=5; // local variable of the function
{
int i=10; // function variable
Print("Inside block i = ",i); // result is i=10;
}
Print("Outside block i = ",i); // result is i=5;
}

This means that while the internal block is running, it sees values of its own local identifiers, not the
values of identifiers with identical names in the external block.
Example:

void OnStart()
{
//---
int i=5; // local variable of the function
for(int i=0;i<3;i++)
Print("Inside for i = ",i);
Print("Outside the block i = ",i);
}
/* Execution result

© 2000-2025, MetaQuotes Ltd.


235 Language Basics

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 since
the program start.

Stack
In every MQL5 program, a special memory area called stack is allocated for storing local function
variables that are created automatically. One stack is allocated for all functions, its default size for
indicators is equal to 1Mb. In Expert Advisors and scripts, stack size can be managed using the
#property stack size compiler directive (which sets the stack size in bytes), a memory of 8Mb is
allocated by default for the stack.
S tatic local variables
are stored in the same place where other static and global variables are stored -
in a special memory area, which exists separately from the stack. Dynamically created variables also
use a memory area separate from the stack.
W ith each function call,
a place on the stack is allocated for internal non-static variables. After exiting
the function, the memory is available for use again.
If from the first function the second one is called, then the second function occupies the required size
from the remaining stack memory for its variables. Thus, when using included functions, stack
memory will be sequentially occupied for each function. This may lead to a shortage of memory during
one of the function calls, such a situation is called stack overflow.
Therefore, for large local data you should better use dynamic memory - when entering a function,
allocate the memory, which is required for local needs, in the system (new, ArrayResize()), and when
exiting the function, release the memory (delete, ArrayFree()).
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility S cope and
Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


236 Language Basics

Formal Parameters
Parameters passed to the function are local. The scope is the function block. Formal parameters must
have names differing from those of external variables and local variables defined within one function.
S ome values can be assigned to formal parameters in the function block . If a formal parameter is
declared with the const modifier, its value can't be changed within 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 by constants. In this case, the initializing value is considered as
the default value. Parameters, next to the initialized one, must also be initialized.
Example:

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


{
...
}

W hen callingsuch a function, the initialized parameters can be omitted, the defaults being substituted
instead of them.
Example:

func(123, 0.5);

Parameters of simple types are passed by value, i.e., modifications of the corresponding local variable
of this type inside the called function will not be reflected in the calling function. Arrays of any type
and data of the structure type are always passed by reference. If it is necessary to prohibit modifying
the array or structure contents, the parameters of these types must be declared with the const
k eyword.

There is an opportunity to pass parameters of simple types by reference. In this case, modification of
such parameters inside the calling function will affect the corresponding variables passed by reference.
In order to indicate that a parameter is passed by reference, put the & modifier after the data type.
Example:

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


{
double calculated_tp;
...
for(int i=0; i<OrdersTotal(); i++)
{
if(i==ArraySize(z)) break;
if(OrderSelect(i)==false) break;

© 2000-2025, MetaQuotes Ltd.


237 Language Basics

z[i]=OrderOpenPrice();
}
x=i;
y=calculated_tp;
}

Parameters passed by reference can't be initialized by default values.


Maximum 64 parameters can be passed into a function.
See also
Input Variables, Data Types, Encapsulation and Extensibility of Types,Initialization of Variables,
Visibility S cope and Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


238 Language Basics

Static Variables
The storage class of static defines a static variable. The static modifier is indicated before the data
type.
Example:

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

A static variable can be initialized by a constant or constant expression corresponding to its type,
unlike a simple local variable, which can be initialized by any expression.
S tatic variables exist from the moment of program execution and are initialized only once before the
specialized functions OnInit() is called. If the initial values are not specified, variables of the static
storage class are taking zero initial values.
Local variables declared with the static keyword retain their values throughout the function lifetime.
W ith each next function call, such local variables contain the values that they had during the previous
call.
Any variables in a block, except formal parameters of a function, can be defined as static. If a
variable declared on a local level is not a static one, memory for such a variable is allocated
automatically at a program stack.
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);
}

See also

© 2000-2025, MetaQuotes Ltd.


239 Language Basics

Data Types, Encapsulation and Extensibility of Types, Initialization of Variables, Visibility S cope and
Lifetime of Variables, Creating and Deleting Objects, S tatic Class Members

© 2000-2025, MetaQuotes Ltd.


240 Language Basics

Global Variables
Global variables are created by placing their declarations outside function descriptions. Global
variables are defined at the same level as functions, i.e., they are not local in any block.
Example:

int GlobalFlag=10; // Global variable


int OnStart()
{
...
}

The scope of global variables is the entire program. Global variables are accessible from all functions
defined in the program. They are initialized to zero unless another initial value is explicitly defined. A
global variable can be initialized only by a constant or constant expression that corresponds to its type.
Global variables are initialized only once after the program is loaded into the client terminal memory
and before the first handling of the Init event. For global variables representing class objects, during
their initialization the corresponding constructors are called. In scripts global variables are initialized
before handling the S tart event.
Note: Variables declared at global level must not be mixed up with the client terminal global variables
that can be accessed using the GlobalVariable...() functions.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility S cope and
Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


241 Language Basics

Input Variables
The input storage class defines the external variable. The input modifier is indicated before the data
type. A variable with the input modifier can't be changed inside mql5-programs, such variables can be
accessed for reading only. Values of input variables can be changed only by a user from the program
properties window. External variables are always reinitialized immediately before the OnInit() is
called.
The maximum length of input variable names is 63 characters. For the input parameter of string type,
the maximum value length (string length) can be from 191 to 253 characters (see the Note). The
minimum length is 0 characters (the value is not set).
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 a program. They are available from the Properties
window of a program.

There is another way to set how your input parameter will look like in the Inputs tab. For this, place a
string comment after the description of an input parameter in the same line. In this way you can make
names of input parameters more understandable for users.
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

© 2000-2025, MetaQuotes Ltd.


242 Language Basics

Note: Arrays and variables of complex types can't act as input variables.
Note: The length of a string comment for Input variables cannot exceed 63 characters.
Note: For input variables of string type, the limitation of the value length (string length) is set by the
following conditions :
· the parameter value is represented by the " parameter_name=parameter_value" string ('=' is
considered),
· maximum representation length of 255 characters (total_length_max=255 or 254 characters
excluding '='),
· maximum length of the parameter_name_length string parameter = 63 characters.
Thus, the maximum string size for a string parameter is calculated using the equation:
parameter_value_length=total_length_max-parameter_name_length=254-parameter_name_length

This provides the maximum string size from 191 (parameter_name_length=63) to 253 characters
(parameter_name_length=1).

Passing Parameters When Calling Custom Indicators from MQL5 Programs

Custom Indicators are called using the iCustom() function. After the name of the custom indicator,
parameters should go in a strict accordance with the declaration of input variables of this custom
indicator. If indicated parameters are less than input variables declared in the called custom indicator,
the missing parameters are filled with values specified during the declaration of variables.
If the custom indicator uses the OnCalculate function of the first type (i.e., the indicator is calculated
using the same array of data), then one of ENUM _APPLIED_PRICE values or handle of another indicator
should be used as the last parameter when calling such a custom indicator. All parameters
corresponding to input variables must be clearly indicated.

© 2000-2025, MetaQuotes Ltd.


243 Language Basics

Enumerations as input Parameters

Not only built-in enumerationsprovided in MQL5, but also user defined variables can be used as input
variables (input parameters for mql5 programs). For example, we can create the dayOfW eek
enumeration, describing days of the week, and use the input variable to specify a particular day of the
week, not as a number, but in a more common way.
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 enable a user to select a necessary value from the properties window during the script
startup, we use the preprocessor command #property script_show_inputs. W e start the script and can
choose one of values of the dayOfW eek enumeration from the list. W e start the EnumInInput script
and go to the Inputs tab. By default, the value of swapday (day of triple swap charge) is W ednesday (W
= 3), but we can specify any other value, and use this value to change the program operation.

Number of possible values of an enumeration is limited. In order to select an input value the drop-
down list is used. Mnemonic names of enumeration members are used for values displayed in the list.

© 2000-2025, MetaQuotes Ltd.


244 Language Basics

If a comment is associated with a mnemonic name, as shown in this example, the comment content is
used instead of the mnemonic name.
Each value of the dayOfW eek enumeration has its value from 0 to 6, but in the list of parameters,
comments specified for each value will be shown. This provides additional flexibility for writing
programs with clear descriptions of input parameters.

Variables with sinput Modifier


Variables with input modifier allow not only setting external parameters values when launching
programs but are also necessary when optimizing trading strategies in the S trategy Tester. Each input
variable excluding the one of a string type can be used in optimization.
S ometimes, it is necessary to exclude some external program parameters from the area of all passes
in the tester. sinput memory modifier has been introduced for such cases. sinput stands for static
external variable declaration (sinput = static input). It means that the following declaration in an
Expert Advisor code

sinput int layers=6; // Number of layers

will be equivalent to the full declaration


static input int layers=6; // Number of layers

The variable declared with sinput modifier is an input parameter of MQL5 program. The value of this
parameter can be changed when launching the program. However, this variable is not used in the
optimization of input parameters. In other words, its values are not enumerated when searching for
the best set of parameters fitting a specified condition.

The Expert Advisor shown above has 5 external parameters. "Number of layers " is declared to be
sinput and equal to 6. This parameter cannot be changed during a trading strategy optimization. W e
can specify the necessary value for it to be used further on. S tart, S tep and S top fields are not
available for such a variable.
Therefore, users will not be able to optimize this parameter after we specify sinput modifier for the
variable. In other words, the terminal users will not be able to set initial and final values for it in the
S trategy Tester for automatic enumeration in the specified range during optimization.

H owever, there is one exception to this rule: sinput variables can be varied in optimization tas ks
using ParameterS etRange() function. This function has been introduced specifically for the program
control of available values sets for any input variable including the ones declared as static input

© 2000-2025, MetaQuotes Ltd.


245 Language Basics

(sinput). The ParameterGetRange() function allows to receive input variables values when
optimization is launched (in OnTesterInit() handler) and to reset a change step value and a range,
within which an optimized parameter values will be enumerated.
In this way, combining the sinput modifier and two functions that work with input parameters, allows
to create a flexible rules for setting optimization intervals of input parameters that depend on values
of another input parameters.

Arranging input parameters


For the convenience of working with MQL5 programs, the input parameters can be divided into named
blocks using the group keyword. This allows for visual separation of some parameters from others
based on the logic embedded in them.
input group "Group name"
input int variable1 = ...
input double variable2 = ...
input double variable3= ...

After such a declaration, all input parameters are visually joined into a specified group simplifying
parameters configuration for MQL5 users when launching on a chart or in the strategy tester.
S pecification of each group is valid till a new group declaration appears :

input group "Group name #1"


input int group1_var1 = ...
input double group1_var2 = ...
input double group1_var3 = ...

input group "Group name #2


input int group2_var1 = ...
input double group2_var2 = ...
input double group2_var3 = ...

A sample EA featuring the block of inputs separated by their purpose:


input group "Signal"
input int ExtBBPeriod = 20; // Bollinger Bands period
input double ExtBBDeviation= 2.0; // deviation
input ENUM_TIMEFRAMES ExtSignalTF=PERIOD_M15; // BB timeframe

input group "Trend"


input int ExtMAPeriod = 13; // Moving Average period
input ENUM_TIMEFRAMES ExtTrendTF=PERIOD_M15; // MA timeframe

input group "ExitRules"


input bool ExtUseSL = true; // use StopLoss
input int Ext_SL_Points = 50; // StopLoss in points
input bool ExtUseTP = false; // use TakeProfit
input int Ext_TP_Points = 100; // TakeProfit in points

© 2000-2025, MetaQuotes Ltd.


246 Language Basics

input bool ExtUseTS = true; // use Trailing Stop


input int Ext_TS_Points = 30; // Trailing Stop in points

input group "MoneyManagement"


sinput double ExtInitialLot = 0.1; // initial lot value
input bool ExtUseAutoLot = true; // automatic lot calculation

input group "Auxiliary"


sinput int ExtMagicNumber = 123456; // EA Magic Number
sinput bool ExtDebugMessage= true; // print debug messages

W hen launching such an EA in the strategy tester, you can double-click a group name to
collapse/expand the inputs block, as well as click the group checkbox to select all its parameters for
optimization.

See also
iCustom, Enumerations, Properties of Programs

© 2000-2025, MetaQuotes Ltd.


247 Language Basics

Extern Variables
The extern keyword is used for declaring variable identifiers as identifiers of the static storage class
with global lifetime. These variables exist from the start of the program and memory for them is
allocated and initialized immediately after the start of the program.
You can create programs that consist of multiple source files ; in this case a directive to the
preprocessor #include is used. Variables declared as an extern with the same type and identifier can
exist in different source files of one project.
W hen compiling the whole project, all the extern variables with the same type and an identifier are
associated with one part of memory of the global variable pool. Extern variables are useful for
separate compilation of source files. Extern variables can be initialized, but only once - existence of
several initialized extern variables of the same type and with the same identifier is prohibited.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility S cope and
Lifetime of Variables, Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


248 Language Basics

Initialization of Variables
Any variable can be initialized during definition. If a variable is not initialized explicitly, the value
stored in this variable can be any. Implicit initialization is not used.
Global and static variablescan be initialized only by a constant of the corresponding type or a 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};
//--- initialization of all fields of the structure with zero values
MqlTradeRequest request={};

List of values of the array elements must be enclosed in curly brackets. Missed initializing sequences
are considered equal to 0.
If the size of the initialized array is not specified, it is determined by a compiler, based on the size of
the initialization sequence.
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},{},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]);

© 2000-2025, MetaQuotes Ltd.


249 Language Basics

Print("4. s10_3.d1[0] = ",s10_3.d1[0]);


}

For structure type variable partial initialization is allowed, as well as for static arrays (with an
implicitly set size). You can initialize one or more first elements of a structure or array, the other
elements will be initialized with zeroes in this case.
See also
Data Types, Encapsulation and Extensibility of Types, Visibility S cope and Lifetime of Variables,
Creating and Deleting Objects

© 2000-2025, MetaQuotes Ltd.


250 Language Basics

Visibility Scope and Lifetime of Variables


There are two basic types of scope: local scope and global scope.
A variable declared outside all functions is located into the global scope. Access to such variables can
be done from anywhere in the program.These variables are located in the global pool of memory, so
their lifetime coincides with the lifetime of the program.
A variable declared inside a block (part of code enclosed incurly brackets) belongs to the local scope.
S uch a variable is not visible (and therefore not available)
outside the block, in which it is declared.
The most common case of local declaration is a variable declared within a function. A variable declared
locally, is located on the stack, and the lifetime of such a variable is equal to the lifetime of the
function.
S ince the scope of a local variable is the block in which it is declared, it is possible to declare variables
with the same name, as those of variables declared in other blocks ; as well as of those declared at
upper levels, up to the global level.
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;

© 2000-2025, MetaQuotes Ltd.


251 Language Basics

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 is only the for loop; outside of this loop there is another variable with the same name,
declared at the beginning of the function. In addition, the k variable is declared in the loop body, its
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 is equal to the
lifetime of the program. Here the scope of such a variable is limited to the block in which it is
declared.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Creating and
Deleting Objects

© 2000-2025, MetaQuotes Ltd.


252 Language Basics

Creating and Deleting Objects


After a MQL5 program is loaded for execution, memory is allocated to each variable according to its
type. According to the access level, all variables are divided into two types - global variables and local
variables. According to the memory class, they can be input parameters of a MQL5 program, static and
automatic. If necessary, each variable is initialized by a corresponding value. After being used a
variable is unintialized and memory used by it is returned to the MQL5 executable system.

Initialization and Deinitialization of Global Variables


Global variables are initialized automatically right after a MQL5 program is loaded and before any of
function is called. During initialization initial values are assigned to variables of simple types and a
constructor (if there is any) is called for objects. Input variables are always declared at a global level,
and are initialized by values set by a user in the dialog during the program start.
Despite the fact that static variables are usually declared at a local level, the memory for these
variables is pre-allocated, and initialization is performed right after a program is loaded, the same as
for global variables.
The initialization order corresponds to the variable declaration order in the program. Deinitialization is
performed in the reverse order. This rule is true only for the variables that were not created by the
new operator. S uch variables are created and initialized automatically right after loading, and are
deinitialized before the program unloading.

Initialization and Deinitialization of Local Variables


If a variable declared on a local level is not a static one, memory is allocated automatically for such a
variable. Local variables, as well as global ones, are initialized automatically at the moment when the
program execution meets their declaration. Thus the initialization order corresponds to the order of
declaration.
Local variables are deinitialized at the end of the program block, in which they were declared, and in
the order opposite to their declaration. A program block is a compound operator that can be a part of
selection operator switch, loop operator (for, while, do-while), a function body or a part of the if-else
operator.
Local variables are initialized only at the moment when the program execution meets the variable
declaration. If during the program execution the block, in which the variable is declared, was not
executed, such a variable is not initialized.

Initialization and Deinitialization of Objects Placed


A special case is that with object pointers, because declaration of a pointer does not entail
initialization of a corresponding objects. Dynamically placed objects are initialized only at the moment
when the class sample is created by the new operator. Initialization of objects presupposes call of a
constructor of a corresponding class. If there is no corresponding constructor in the class, its members
of a simple type will not be automatically initialized; members of types string, dynamic array and
complex object will be automatically initialized.
Pointers can be declared on a local or global level; and they can be initialized by the empty value of
NULL or by the value of the pointer of the same or inherited type. If the new operator is called for a

© 2000-2025, MetaQuotes Ltd.


253 Language Basics

pointer declared on a local level, the delete operator for this pointer must be performed before exiting
the level. Otherwise the pointer will be lost and the explicit deletion of the object will fail.
All objectscreated by the expression of object_pointer=new Class_name, must be then deleted by the
delete(object_pointer) operator. If for some reasons such a variable is not deleted by the delete
operator when the program is completed, the corresponding entry will appear in the "Experts " journal.
One can declare several variables and assign a pointer of one object to all of them.
If a dynamically created object has a constructor, this constructor will be called at the moment of the
new operator execution. If an object has a destructor, it will be called during the execution of the

delete operator.

Thus dynamically placed objects are created only at the moment when the corresponding new operator
is invoked, and are assuredly deleted either by the delete operator or automatically by the executing
system of MQL5 during the program unloading. The order of declaration of pointers of dynamically
created object doesn't influence the order of their initialization. The order of initialization and
deinitialization is fully controlled by the programmer.

Dynamic memory allocation in MQL5


W hen working with dynamic arrays, released memory is immediately returned back to the operating
system.
W hen work ing with dynamic class objects using the new operator, first memory is requested from the
class memory pool the memory manager is working with. If there is not enough memory in the pool,
memory is requested from the operating system. W hen deleting the dynamic object using the delete
operator, released memory is immediately returned back to the class memory pool.
Memory manager releases memory back to the operating system immediately after exiting the
following event handling functions : OnInit(), OnDeinit(), OnS tart(), OnTick(), OnCalculate(),
OnTimer(), OnTrade(), OnTester(), OnTesterInit(), OnTesterPass(), OnTesterDeinit(),
OnChartEvent(), OnBookEvent().

Brief Characteristics of Variables


The main information about the order of creation, deletion, about calls of constructors and destructors
is given in the below table.

Global automatic Local automatic Dynamically created


variable variable object

Initialization right after a mql5 when the code line at the execution of
program is loaded where it is declared is the new operator
reached during
execution
Initialization order in the order of in the order of irrespective of the
declaration declaration order of declaration
Deinitialization before a mql5 when execution exits when the delete
program is unloaded the declaration block operator is executed

© 2000-2025, MetaQuotes Ltd.


254 Language Basics

Global automatic Local automatic Dynamically created


variable variable object

or before a mql5
program is unloaded
Deinitialization order in the order opposite in the order opposite irrespective of the
to the initialization to the initialization initialization order
order order
Constructor call at mql5 program at initialization at the execution of
loading the new operator
Destructor call at mql5 program when exiting the block at the execution of
unloading where the variable the delete operator
was initialized
Error logs log message in the log message in the log message in the
"Experts " journal "Experts " journal "Experts " journal
about the attempt to about the attempt to about undeleted
delete an delete an dynamically created
automatically created automatically created objects at the unload
object object of a mql5 program

See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Visibility S cope and
Lifetime of Variables

© 2000-2025, MetaQuotes Ltd.


255 Language Basics

Preprocessor
Preprocessor is a special subsystem of the MQL5 compiler that is intended for preparation of the
program source code immediately before the program is compiled.
Preprocessor allows enhancement of the source code readability. The code can be structured by
including of specific files containing source codes of mql5-programs. The possibility to assign
mnemonic names to specific constants contributes to enhancement of the code readability.
Preprocessor also allows determining specific parameters of mql5-programs :
· Declare constants
· S et program properties
· Include files in program text
· Import functions
· Conditional Compilation
The preprocessor directives are used by the compiler to preprocess the source code before compiling
it. The directive always begins with #, therefore the compiler prohibits using the symbol in names of
variables, functions etc.
Each directive is described by a separate entry and is valid until the line break. You cannot use several
directives in one entry. If the directive entry is too big, it can be broken into several lines using the '\'
symbol. In this case, the next line is considered a continuation of the directive entry.
//+------------------------------------------------------------------+
//| foreach pseudo-operator |
//+------------------------------------------------------------------+
#define ForEach(index, array) for (int index = 0, \
max_##index=ArraySize((array)); \
index<max_##index; index++)
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string array[]={"12","23","34","45"};
//--- bypass the array using ForEach
ForEach(i,array)
{
PrintFormat("%d: array[%d]=%s",i,i,array[i]);
}
}
//+------------------------------------------------------------------+
/* Output result
0: array[0]=12
1: array[1]=23
2: array[2]=34
3: array[3]=45
*/

© 2000-2025, MetaQuotes Ltd.


256 Language Basics

For the compiler, all these three #define directive lines look like a single long line. The example above
also applies ## character which is a merge operator used in the #define macros to merge the two
macro tokens into one. The tokens merge operator cannot be the first or last one in a macro
definition.

© 2000-2025, MetaQuotes Ltd.


257 Language Basics

Macro substitution (#define)


The preprocessor directives are used by the compiler to preprocess the source code before compiling
it. The directive always begins with #, therefore the compiler prohibits using the symbol in names of
variables, functions etc.
Each directive is described by a separate entry and is valid until the line break. You cannot use several
directives in one entry. If the directive entry is too big, it can be broken into several lines using the '\'
symbol. In this case, the next line is considered a continuation of the directive entry.
The #define directive can be used to assign mnemonic names to constants. There are two forms :
#define identifier expression // parameter-free form
#define identifier(par1,... par8) expression // parametric form

The #define directive substitutes expression for all further found entries of identifier in the source
text. The identifier is replaced only if it is a separate token. The identifier is not replaced if it is part
of a comment, part of a string, or part of another longer identifier.
The constant identifier is governed by the same rules as variable names. The value can be of any type:
#define ABC 100
#define PI 3.14
#define COMPANY_NAME "MetaQuotes Software Corp."
...
void ShowCopyright()
{
Print("Copyright 2001-2009, ",COMPANY_NAME);
Print("https://www.metaquotes.net");
}

expression can consist of several tokens, such as keywords, constants, constant and non-constant
expressions. expression ends with the end of the line and can't be transferred 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

Parametric Form #define

© 2000-2025, MetaQuotes Ltd.


258 Language Basics

W ith the parametric form, all the subsequent found entries of identifier will be replaced by expression
taking into account the actual parameters. For example:
// example with two parameters a and b
#define A 2+3
#define B 5-1
#define MUL(a, b) ((a)*(b))

double c=MUL(A,B);
Print("c=",c);
/*
expression double c=MUL(A,B);
is equivalent to double c=((2+3)*(5-1));
*/
// Result
// c=20

Be sure to enclose parameters in parentheses when using the parameters in expression, as this will
help avoid non-obvious errors that are hard to find. If we rewrite the code without using the brackets,
the result will be different:
// example with two parameters a and b
#define A 2+3
#define B 5-1
#define MUL(a, b) a*b

double c=MUL(A,B);
Print("c=",c);
/*
expression double c=MUL(A,B);
is equivalent to double c=2+3*5-1;
*/
// Result
// c=16

W hen using the parametric form, maximum 8 parameters are allowed.


// correct parametric form
#define LOG(text) Print(__FILE__,"(",__LINE__,") :",text) // one parameter - 'text'

// incorrect parametric form


#define WRONG_DEF(p1, p2, p3, p4, p5, p6, p7, p8, p9) p1+p2+p3+p4 // more than 8 parameters from

The #undef directive

The #undef directive cancels declaration of the macro substitution, defined before.
Example:

#define MACRO

© 2000-2025, MetaQuotes Ltd.


259 Language Basics

void func1()
{
#ifdef MACRO
Print("MACRO is defined in ",__FUNCTION__);
#else
Print("MACRO is not defined in ",__FUNCTION__);
#endif
}

#undef MACRO

void func2()
{
#ifdef MACRO
Print("MACRO is defined in ",__FUNCTION__);
#else
Print("MACRO is not defined in ",__FUNCTION__);
#endif
}

void OnStart()
{
func1();
func2();
}

/* Result:
MACRO is defined in func1
MACRO is not defined in func2
*/

See also
Identifiers, Character Constants

© 2000-2025, MetaQuotes Ltd.


260 Language Basics

Program Properties (#property)


Every mql5-program allows to specify additional specific parameters named #property that help client
terminal in proper servicing for programs without the necessity to launch them explicitly. This
concerns external settings of indicators, first of all. Properties described in included files are
completely ignored. Properties must be specified in the main mq5-file.
#property identifier value

The compiler will write declared values in the configuration of the module executed.

Constant Type Description

icon string Path to the file of an image that will be used as an


icon of the EX5 program. Path specification rules
are the same as for resources. The property must
be specified in the main module with the MQL5
source code. The icon file must be in the ICO
format.
link string Link to the company website
copyright string The company name
version string Program version, maximum 31 characters
description string Brief text description of a mql5-program. S everal
description can be present, each of them describes
one line of the text. The total length of all
description can not exceed 511 characters including

line feed.
stacksize int MQL5 program stack size. The stack of sufficient
size is necessary when executing function recursive
calls.
W hen launching a script or an Expert Advisor on the
chart, the stack of at least 8 M B is allocated. In
case of indicators, the stack size is always fixed
and equal to 1 M B.
W hen a program is launched in the strategy tester,
the stack of 16 M B is always allocated for it.
library A library; no start function is assigned, functions
with the export modifier can be imported in other
mql5-programs
indicator_applied_price int S pecifies the default value for the "Apply to" field.
You can specify one of the values of
ENUM _APPLIED_PR ICE. If the property is not
specified, the default value is PRICE_CLOSE
indicator_chart_window S how the indicator in the chart window
indicator_separate_window S how the indicator in a separate window

© 2000-2025, MetaQuotes Ltd.


261 Language Basics

Constant Type Description

indicator_height int Fixed height of the indicator subwindow in pixels


(property INDICATOR_HEIGHT)
indicator_buffers int Number of buffers for indicator calculation
indicator_plots int Number of graphic series in the indicator
indicator_minimum double The bottom scaling limit for a separate indicator
window
indicator_maximum double The top scaling limit for a separate indicator
window
indicator_labelN string S ets a label for the N-th graphic series displayed in
DataW indow. For graphic series requiring multiple
indicator buffers (DRAW_CANDLES , DRAW_FILLING
and others), the label names are defined using the
separator ';'.
indicator_colorN color The color for displaying line N, where N is the
number of graphic series ; numbering starts from 1
indicator_widthN int Line thickness in graphic series, where N is the
number of graphic series ; numbering starts from 1
indicator_styleN int Line style in graphic series, specified by the values
of ENUM _LINE_S TYLE. N is the number of graphic
series ; numbering starts from 1
indicator_typeN int Type of graphical plotting, specified by the values
of ENUM _DRAW_TYPE. N is the number of graphic
series ; numbering starts from 1
indicator_levelN double H orizontal level of N in a separate indicator window
indicator_levelcolor color Color of horizontal levels of the indicator
indicator_levelwidth int Thickness of horizontal levels of the indicator
indicator_levelstyle int S tyle of 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
tester_indicator string Name of a custom indicator in the format of
" indicator_name.ex5". Indicators that require
testing are defined automatically from the call of
the iCustom() function, if the corresponding
parameter is set through a constant string. For all
other cases (use of the IndicatorCreate() function
or use of a non-constant string in the parameter

© 2000-2025, MetaQuotes Ltd.


262 Language Basics

Constant Type Description

that sets the indicator name) this property is


required
tester_file string File name for a tester with the indication of
extension, in double quotes (as a constant string).
The specified file will be passed to tester. Input
files to be tested, if there are necessary ones, must
always be specified.
tester_library string Library name with the extension, in double quotes.
A library can have 'dll' or 'ex5' as file extension.
Libraries that require testing are defined
automatically. However, if any of libraries is used
by a custom indicator, this property is required
tester_set string Name of the set file with the values ​and the step of
the input parameters. The file is passed to tester
before testing and optimization. The file name is
specified with an extension and double quotes as a
constant string.

If you specify the EA name and the version number


as "<expert_name>_<number>.set" in a set file
name, then it is automatically added to the
parameter versions download menu under the
<number> version number. For example, the name
" M ACD S ample_4.set" means that this is a set file
for the " M ACD S ample.mq5" EA with the version
number equal to 4.

To study the format, we recommend that you


manually save the test/optimization settings in the
strategy tester and then open the set file created in
this way.
tester_no_cache string W hen performing optimization, the strategy tester
saves all results of executed passes to the
optimization cache, in which the test result is
saved for each set of the input parameters. This
allows using the ready-made results during re-
optimization on the same parameters without
wasting time on re-calculation.

But in some tas ks (for example, in math


calculations), it may be necessary to carry out
calculations regardless of the availability of ready-
made results in the optimization cache. In this
case, the file should include the tester_no_cache
property. The test results are still stored in the

© 2000-2025, MetaQuotes Ltd.


263 Language Basics

Constant Type Description

cache, so that you can see all the data on


performed passes in the strategy tester.
tester_everytick_calculate string In the S trategy Tester, indicators are only
calculated when their data are accessed, i.e. when
the values of indicator buffers are requested. This
provides a significantly faster testing and
optimization speed, if you do not need to obtain
indicator values on each tick.

By specifying the tester_everytick_calculate


property, you can enable the forced calculation of
the indicator on every tick.

Indicators in the S trategy Tester are also forcibly


calculated on every tick in the following cases :
· when testing in the visual mode;

· if the indicator has any of the following


functions : EventChartCustom, OnChartEvent,
OnTimer;
· if the indicator was created using the
compiler with build number below 1916.

This feature only applies in the S trategy Tester,


while in the terminal indicators are always
calculated on each received tick.
optimization_chart_mode string S pecifiesthe chart type and the names of two input
parameters which will be used for the visualization
of optimization results. For example, "3d, InpX,
InpY" means that the results will be shown in a 3D
chart with the coordinate axes based on the tested
InpX and InpY parameter values. Thus, the property
enables the specification of parameters that will be
used to display the optimization chart and the chart
type, directly in the program code.
Possible options :
· "3d, input_parameter_name1,
input_parameter_name2" means a 3D
visualization chart, which can be rotated,
zoomed in and out. The chart is built using
two parameters.
· "2d, input_parameter_name1,
input_parameter_name2" means a 2D grid
chart, in which each cell is painted in a
certain color depending on the result. The
chart is built using two parameters.

© 2000-2025, MetaQuotes Ltd.


264 Language Basics

Constant Type Description

· "1d, input_parameter_name1,
input_parameter_name2" means a linear
chart, in which the results are sorted by the
specified parameter. Each pass is displayed
as a point. The chart is built based on one
parameter.
· "0d, input_parameter_name1,
input_parameter_name2" means a regular
chart with results sorted by the pass result
arrival time. Each pass is displayed as a
point in the chart. Parameter indication is
not required, but the specified parameters
can be used for the manual switch to other
chart types.
Optionally, you can indicate only the chart type,
without specifying one or two input parameters. In
this case, the terminal will select the required
parameters to show the optimization chart.

Sample Task of Description and Version Number

#property version "3.70" // Current version of the Expert Advisor


#property description "ZigZag universal with Pesavento Patterns"
#property description "At the moment in the indicator several ZigZags with different algorithms are
#property description "It is possible to embed a large number of other indicators showing the highs
#property description "lows and automatically build from these highs and lows various graphical too

Examples of Specifying a Separate Label for Each Indicator Buffer ( " C open; C high; C low; C
close" )

© 2000-2025, MetaQuotes Ltd.


265 Language Basics

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

© 2000-2025, MetaQuotes Ltd.


266 Language Basics

Including Files (#include)


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

Examples:

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

The preprocessor replaces the line #include <file_name> with the content of the file W inUser32.mqh.
Angle brack ets indicate that the W inUser32.mqh file will be tak en from the standard directory (usually
it is terminal_installation_directory\MQL5\Include). The current directory is not included in the
search.
If the file name is enclosed in quotation marks, the search is made in the current directory (which
contains the main source file). The standard directory is not included in the search.
See also
S tandard Library, Importing Functions

© 2000-2025, MetaQuotes Ltd.


267 Language Basics

Importing Function (#import)


Functions are imported from compiled MQL5 modules (*.ex5 files) and from operating system modules
(*.dll files). The module name is specified in the #import directive. For compiler to be able to correctly
form the imported function call and organize proper transmission parameters, the full description of
functions is needed. Function descriptions immediately follow the #import "module name" directive.
New command #import (can be without parameters) completes the block of imported function
descriptions.
#import "file_name"
func1 define;
func2 define;
...
funcN define;
#import

Imported functions can have any names. Functions having the same names but from different modules
can be imported at the same time. Imported functions can have names that coincide with the names
of built-in functions. Operation of scope resolution defines which of the functions should be called.
The order of searching for a file specified after the #import keyword is described in Call of Imported
Functions.

S ince the imported functionsare outside the compiled module, the compiler can not verify the validity
of passed parameters. Therefore, to avoid run-time errors, one must accurately describe the
composition and order of parameters passed to imported functions. Parameters passed to imported
functions (both from EX5, and from the DLL-module) can have default values.
The following can't be used for parameters in imported functions :
· pointers (*);
· link s to objects that contain dynamic arrays and/or pointers.

Classes, string arrays or complex objects that contain strings and/or dynamic arrays of any types
cannot be passed as a parameter to functions imported from DLL.
Examples:

#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);
#import

© 2000-2025, MetaQuotes Ltd.


268 Language Basics

To import functions during execution of a mql5 program, early binding is used. This means that the
library is loaded during the loading of a program using its ex5 program.
It's not recommended to use a fully qualified name of the loadable module of type Drive:
\Directory\FileName.Ext. MQL5 libraries are loaded from the terminal_dir\MQL5\Libraries folder.

If the imported function has different call versions for 32- and 64-bit W indows versions, both of them
should be imported, and the right function version should be called explicitly using the _Is X64
variable.
Example:

#import "user32.dll"
//--- For the 32-bit system
int MessageBoxW(uint hWnd,string lpText,string lpCaption,uint uType);
//--- For the 64-bit system
int MessageBoxW(ulong hWnd,string lpText,string lpCaption,uint uType);
#import
//+------------------------------------------------------------------+
//| MessageBox_32_64_bit uses the proper version of MessageBoxW() |
//+------------------------------------------------------------------+
int MessageBox_32_64_bit()
{
int res=-1;
//--- If we are using the 64-bit Windows
if(_IsX64)
{
ulong hwnd=0;
res=MessageBoxW(hwnd,"64-bit MessageBoxW call example","MessageBoxW 64 bit",MB_OK|MB_ICONINFO
}
else // We are using the 32-bit Windows
{
uint hwnd=0;
res=MessageBoxW(hwnd,"32-bit MessageBoxW call example","MessageBoxW 32 bit",MB_OK|MB_ICONINFO
}
return (res);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int ans=MessageBox_32_64_bit();
PrintFormat("MessageBox_32_64_bit returned %d",ans);
}

Importing functions from .NET libraries

© 2000-2025, MetaQuotes Ltd.


269 Language Basics

To work with .NET library functions, simply import DLL itself without defining specific functions.
MetaEditor automatically imports all functions it is possible to work with:
· S imple structures (POD, plain old data) — structures that contain only simple data types.
· Public static functions having parameters, in which only simple types and POD structures or their
arrays are used
To call functions from the library, simply import it:
#import "TestLib.dll"
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
int x=41;
TestClass::Inc(x);
Print(x);
}

The C# code of the Inc function of the TestClass looks as follows :


public class TestClass
{
public static void Inc(ref int x)
{
x++;
}
}

As a result of execution, the script returns the value of 42.


See also
Including Files

© 2000-2025, MetaQuotes Ltd.


270 Language Basics

Conditional Compilation (#ifdef, #ifndef, #else, #endif)


The preprocessor directives are used by the compiler to preprocess the source code before compiling
it. The directive always begins with #, therefore the compiler prohibits using the symbol in names of
variables, functions etc.
Each directive is described by a separate entry and is valid until the line break. You cannot use several
directives in one entry. If the directive entry is too big, it can be broken into several lines using the '\'
symbol. In this case, the next line is considered a continuation of the directive entry.
Preprocessor conditional compilation directives allow compiling or s kipping a part of the program
depending on the fulfillment of a certain condition.
That condition can take one of the following forms.
#ifdef identifier
// the code located here is compiled if the identifier has already been defined for the preproce
#endif

#ifndef identifier
// the code located here is compiled if the identifier is not currently defined by #define prepr
#endif

Any of the conditional compilation directives can be followed by any number of lines possibly
containing #else directive and ending with #endif. If the verified condition is true, the lines between
#else and #endif are ignored. If the verified condition is not fulfilled, all lines between check ing and
#else directive (or #endif directive if the former is absent) are ignored.

Example:

#ifndef TestMode
#define TestMode
#endif
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
#ifdef TestMode
Print("Test mode");
#else
Print("Normal mode");
#endif
}

Depending on the program type and compilation mode, the standard macros are defined the following
way:
__MQL5__ macro is defined when compiling *.mq5 file, __MQL 4__ macro is defined when compiling
*.mq4 one.
_DEBUG macro is defined when compiling in debug mode.
_REL EASE macro is defined when compiling in release mode.

© 2000-2025, MetaQuotes Ltd.


271 Language Basics

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
#ifdef __MQL5__
#ifdef _DEBUG
Print("Hello from MQL5 compiler [DEBUG]");
#else
#ifdef _RELEASE
Print("Hello from MQL5 compiler [RELEASE]");
#endif
#endif
#else
#ifdef __MQL4__
#ifdef _DEBUG
Print("Hello from MQL4 compiler [DEBUG]");
#else
#ifdef _RELEASE
Print("Hello from MQL4 compiler [RELEASE]");
#endif
#endif
#endif
#endif
}

© 2000-2025, MetaQuotes Ltd.


272 Language Basics

Object-Oriented Programming
Object-oriented programming (OOP) is programming primarily focused on data, while data and
behavior are being inseparably linked. Data and behavior together constitute a class, while objects are
class instances.
The components of the object-oriented approach are:
· Encapsulation and type extensibility
· Inheritance
· Polymorphism
· Overloading
· Virtual functions

OOP considers computation as modeling of behavior. The modeled item is the object represented by
computational abstractions. S uppose we want to write a well known game " Tetris " . To do this, we
must learn how to model the appearance of random shapes composed of four s quares joined together
by edges. Also we need to regulate the falling speed of shapes, define operations of rotation and shift
of shapes. Moving of shapes on the screen is limited by the well's boundaries, this requirement must
also be modeled. Besides that, filled rows of cubes must be destroyed and achieved points must be
counted.
Thus, this easy-to-understand game requires the creation of several models - shape model, well
model, shape movement model and so on. All these models are abstractions, represented by
calculations in the computer. To describe these models, the concept of Abstract Data Type, ADT (or
complex data type) is used. S trictly speaking, the model of the " shapes " motion in the DOM is not a
data type, but it is a set of operations on the " shape" data type, using the restrictions of the " well"
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 benefit of inheritance is in the
fact that it allows obtaining derivative types from data types already defined by a user.
For example, to create Tetris shapes, it's convenient to create a base class S hape first. The other
classes representing all seven possible shape types can be derived on its basis. Behavior of shapes is
defined in the base class, while implementation of behavior of each separate shape is defined in
derivative classes.
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 tas k of programming for the user of this
object.
If we want to draw a shape on the screen, we need to know where the center will be and how to draw
it. If a separate shape knows how to draw itself, the programmer should send a " draw" message when
using such a shape.
The MQL5 Language is a C++ like, and it also has the encapsulation mechanism for the implementation
of ADT. On the one hand encapsulation combines the internal details of the implementation of a
particular type, and on the other hand it combines externally accessible functions that can influence
objects of this type. Implementation details may be inaccessible for a program that uses this type.

© 2000-2025, MetaQuotes Ltd.


273 Language Basics

The concept of OOP has a set of related concepts, including the following:
· S imulation of actions from the real world
· User-defined data types

· H iding the implementation details

· Possibility of the code reuse through inheritance

· Interpretation of function calls during execution

S ome of these concepts are rather vague, some are abstract, others are general.

© 2000-2025, MetaQuotes Ltd.


274 Language Basics

Encapsulation and Extensibility of Types


OOP is a balanced approach to writing software. Data and behavior are packed together. This
encapsulation creates user-defined data types, extending the language data types and interacting with
them. Types extensibility is an opportunity to add to the language user-defined data types, which are
also easy to use, as well as basic types.
An abstract data type, for example, a 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 print operations are called methods.
A certain implementation of ADT may have some restrictions, for example, strings can be limited in
length. These limitations affect the 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 is the ability to hide the implementation details when the open interfaces to user-
defined type is provided. In MQL5, as well as in C++, class and structure definitions (class and struct)
are used for the encapsulation provisions in combination with access keywords private, protected and
public.
The public keyword shows that access to the members that stand behind it is open without
restrictions. W ithout this keyword, class members are locked by default. Private members are
accessible only by member functions only of its class.
Protected class functions are available to class functions not only in its class, but also in its inheritor
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 unexpected
changes in the structure of data. Access restriction or data hiding is a feature of the object-oriented
programming.
Usually, class functions are protected and declared 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 public access modifier.

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

© 2000-2025, MetaQuotes Ltd.


275 Language Basics

This approach offers several advantages. First, by function name we can understand what it does -
sets or gets the value of a class member. S econdly, perhaps in the future we will need to change the
type of the m_name variable in the CPerson class or in any of its derivative classes.
In this case, we'll need just to change the implementation of functions S etName() and GetName(),
while objects of the CPerson class will be available for using in a program without any code changes
because the user will not even know that the 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) StringSetCharacter(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=StringSubstr(full_name,pos+1);
else ret_string=full_name;
return(ret_string);
}

© 2000-2025, MetaQuotes Ltd.


276 Language Basics

See also
Data Types

© 2000-2025, MetaQuotes Ltd.


277 Language Basics

Inheritance
The characteristic feature of OOP is the encouragement of code reuse through inheritance. A new
class is made from the existing, which is 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 a new code for each of
them. In addition, the new code implies new errors. The derived class inherits the description of the
base class, thus any re-development and re-testing of code is unnecessary. The inheritance
relationships are hierarchical.
H ierarchy 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 to all periodic elements.
Inert gases constitute the next important subclass. The hierarchy is that the inert gas, such as argon
is a gas, and gas, in its turn, is part of the system. S uch a hierarchy allows to interpret behaviour of
inert gases easily. W e know that their atoms contain protons and electrons, that is true for all other
elements.
W e k now that they are in a gaseous state at room temperature, like all the gases. W e know that no
gas from inert gas subclass enters usual chemical reaction with other elements, and it is a property of
all inert gases.
Consider an example of the inheritance of geometric shapes. To describe the whole variety of simple
shapes (circle, triangle, rectangle, s quare etc.), the best way is to create a base class (ADT), which is
the ancestor of all the derived classes.
Let's create a base class CS hape, which contains just the most common members describing the
shape. These members describe properties that are characteristic of any shape - the type of the shape
and 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 new classes derived from the base class, in which we will add necessary fields, each
specifying a certain class. For the Circle shape it is necessary to add a member that contains the
radius value. The Square shape is characterized by the side value. Therefore, derived classes,
inherited from the base class CS hape will be declared as follows :

© 2000-2025, MetaQuotes Ltd.


278 Language Basics

//--- 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 is similar:


//--- 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 is called first, and then the
constructor of the derived class is called. W hen an object is destroyed first the destructor of the
derived class is called, and then a base class destructor is called.
Thus, by declaring the most general members in the base class, we can add an additional members in
derived classes, which specify a particular class. Inheritance allows creating powerful code libraries
that can be reused many times.
The syntax for creating a derived class from an already existing one is as follows :
class class_name :
(public | protected | private) opt base_class_name
{
class members declaration
};

One of aspects of the derived class is the visibility (openness) 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 one. The public keyword after a colon in the header of a derived
class indicates that the protected and public members of the base class CS hape 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 the derived class. The public
inheritance also means that derived classes (CCircle and CSquare) are CS hapes. That is, the Square
(CSquare) is a shape (CS hape), but the shape does not necessarily have to be a s quare.

© 2000-2025, MetaQuotes Ltd.


279 Language Basics

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, new members are added in a derivative class.
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, the public and protected members of base class become private
members of the derived class.
In 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 types are rare, and each of them needs
to be used carefully.
It should be understood that the type of inheritance (public, protected or private) does not affect the
ways of accessing the members of base classes in the hierarchy of inheritance from a derived
class. W ith any type of inheritance, only base class members declared with public and protected access
specifiers will be available out of the derived classes. Let's consider it in the following example:
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
//+------------------------------------------------------------------+
//| Example class with a few access types |
//+------------------------------------------------------------------+
class CBaseClass
{
private: //--- The private member is not available from derived classes
int m_member;
protected: //--- The protected method is available from the base class and its derived cl
int Member(){return(m_member);}
public: //--- Class constructor is available to all members of classes
CBaseClass(){m_member=5;return;};
private: //--- A private method for assigning a value to m_member
void Member(int value) { m_member=value;};

};
//+------------------------------------------------------------------+
//| Derived class with errors |
//+------------------------------------------------------------------+
class CDerived: public CBaseClass // specification of public inheritance can be omitted, since it i
{
public:
void Func() // In the derived class, define a function with calls to base class members
{
//--- An attempt to modify a private member of the base class
m_member=0; // Error, the private member of the base class is not available
Member(0); // Error, the private method of the base class is not available in derived

© 2000-2025, MetaQuotes Ltd.


280 Language Basics

//--- Reading the member of the base class


Print(m_member); // Error, the private member of the base class is not available
Print(Member()); // No error, protected method is available from the base class and its der
}
};

In the above example, CBaseClass has only a public method – the constructor. Constructors are called
automatically when creating a class object. Therefore, the private member m_member and the
protected methods Member() cannot be called from the outside. But in case of public inheritance, the
Member() method of the base class will be available from the derived classes.
In case of protected inheritance, all the members of the base class with public and protected access
become protected. It means that if public data members and methods of the base class were
accessible from the outside, with protected inheritance they are available only from the classes of the
derived class and its further derivatives.
//+------------------------------------------------------------------+
//| Example class with a few access types |
//+------------------------------------------------------------------+
class CBaseMathClass
{
private: //--- The private member is not available from derived classes
double m_Pi;
public: //--- Getting and setting a value for m_Pi
void SetPI(double v){m_Pi=v;return;};
double GetPI(){return m_Pi;};
public: // The class constructor is available to all members
CBaseMathClass() {SetPI(3.14); PrintFormat("%s",__FUNCTION__);};
};
//+------------------------------------------------------------------+
//| Derived class, in which m_Pi cannot be modified |
//+------------------------------------------------------------------+
class CProtectedChildClass: protected CBaseMathClass // Protected inheritance
{
private:
double m_radius;
public: //--- Public methods in the derived class
void SetRadius(double r){m_radius=r; return;};
double GetCircleLength(){return GetPI()*m_radius;};
};
//+------------------------------------------------------------------+
//| Script starting function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- When creating a derived class, the constructor of the base class will be called automatically
CProtectedChildClass pt;
//--- Specify radius
pt.SetRadius(10);
PrintFormat("Length=%G",pt.GetCircleLength());

© 2000-2025, MetaQuotes Ltd.


281 Language Basics

//--- If we uncomment the line below, we will get an error at the stage of compilation, since SetPI
// pt.SetPI(3);

//--- Now declare a variable of the base class and try to set the Pi constant equal to 10
CBaseMathClass bc;
bc.SetPI(10);
//--- Here is the result
PrintFormat("bc.GetPI()=%G",bc.GetPI());
}

The example shows that methods S etPI() and GetPi() in the base class CBaseMathClass are open and
available for calling from any place of the program. But at the same time, for CProtectedChildClass
which is derived from it these methods can be called only from the methods of the
CProtectedChildClass class or its derived classes.
In case of private inheritance, all the members of the basic class with the public and protected access
become private, and calling them becomes impossible in further inheritance.
MQL5 has no multiple inheritance.
See also
S tructures and Classes

© 2000-2025, MetaQuotes Ltd.


282 Language Basics

Polymorphism
Polymorphism is an opportunity for different classes of objects, related through inheritance, to
respond in various ways when calling the same function element. It helps to create a universal
mechanism describing the behavior of not only the base class, but also descendant classes.
Let's continue to develop a base class CS hape, and define a member function GetArea(), designed to
calculate the area of a shape. In all the descendant classes, produced by inheritance from the base
class, we redefine this function in accordance with rules of calculating the area of a particular shape.
For a s quare (class CSquare), the area is calculated through its sides, for a circle (class CCircle), area
is expressed through its radius etc. W e can create an array to store objects of CS hape type, in which
both objects of a base class and those of all descendant classes can be stored. 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 descendant will vary.
//--- The derived class Circle
class CCircle : public CShape // After a colon we define the base class
{ // from which inheritance is made
private:
double 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

© 2000-2025, MetaQuotes Ltd.


283 Language Basics

private:
double 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 thearea of the s quare and circle, we need the corresponding values of m_radius and
m_s quare_side, so we have added the functions S etRadius() and S etS ide() in the declaration of the
corresponding class.
It is assumed that object of different types (CCircle and CSquare) derived from one base type CS hape
are used in our program. Polymorphism allows creating an array of objects of the base CS hape class,
but when declaring this array, these objects are yet unknown and their type is undefined.
The decision on what type of object will be contained in each element of the array will be taken
directly during program execution. This involves the dynamic creation of objects of the appropriate
classes, and hence the necessity to use object pointers instead of objects.
The new operator is used for dynamic creation of objects. Each such object must be individually and
explicitly deleted using the delete operator. Therefore we will declare an array of pointers of CS hape
type, and create an object of a proper type for each element (new Class_Name), as shown in the
following script example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Declare an array of object pointers of the base type
CShape *shapes[5]; // An array of pointers to CShape object

//--- Here fill in the array with derived objects


//--- Declare a pointer to the object of CCircle type
CCircle *circle=new CCircle();
//--- Set object properties at the circle pointer
circle.SetRadius(2.5);
//--- Place the pointer value in shapes[0]
shapes[0]=circle;

//--- Create another CCircle object and write down its pointer in shapes[1]
circle=new CCircle();
shapes[1]=circle;
circle.SetRadius(5);

//--- Here we intentionally "forget" to set a value for shapes[2]


//circle=new CCircle();
//circle.SetRadius(10);
//shapes[2]=circle;

© 2000-2025, MetaQuotes Ltd.


284 Language Basics

//--- Set NULL for the element that is not used


shapes[2]=NULL;

//--- Create a CSquare object and write down its pointer to shapes[3]
CSquare *square=new CSquare();
square.SetSide(5);
shapes[3]=square;

//--- Create a CSquare object and write down its pointer to shapes[4]
square=new CSquare();
square.SetSide(10);
shapes[4]=square;

//--- We have an array of pointers, get its size


int total=ArraySize(shapes);
//--- Pass in a loop through all pointers in the array
for(int i=0; i<5;i++)
{
//--- If the pointer at the specified index is valid
if(CheckPointer(shapes[i])!=POINTER_INVALID)
{
//--- Log the type and square of the shape
PrintFormat("The object of type %d has the square %G",
shapes[i].GetType(),
shapes[i].GetArea());
}
//--- If the pointer has type POINTER_INVALID
else
{
//--- Notify of an error
PrintFormat("Object shapes[%d] has not been initialized! Its pointer is %s",
i,EnumToString(CheckPointer(shapes[i])));
}
}

//--- We must delete all created dynamic objects


for(int i=0;i<total;i++)
{
//--- We can delete only the objects with pointers of POINTER_DYNAMIC type
if(CheckPointer(shapes[i])==POINTER_DYNAMIC)
{
//--- Notify of deletion
PrintFormat("Deleting shapes[%d]",i);
//--- Delete an object by its pointer
delete shapes[i];
}
}
}

© 2000-2025, MetaQuotes Ltd.


285 Language Basics

Please note that when deleting an object using the delete operator, the type of its pointer must be
checked. Only objects with the POINTER_DYNAMIC pointer can be deleted using delete. For pointers of
other type, an error will be returned.
But besides the redefining of functions during inheritance, polymorphism also includes the
implementation of one and the same functions with different sets of parameters within a class. This
means that the class may have several functions with the same name but with a different type and/or
set of parameters. In this case, polymorphism is implemented through the function overload.
See also
S tandard Library

© 2000-2025, MetaQuotes Ltd.


286 Language Basics

Overload
W ithin one class it is possible to define two or more methods that use the same name, but have
different numbers of parameters. W hen this occurs, methods are called overloaded and such a process
is referred to as method overloading.
Method overloading is one of ways of polymorphism realization. Overloading of methods is performed
according to the same rules as the function overloading.
If the called function has no exact match, the compiler searches for a suitable function on three levels
sequentially:
1. search within class methods.
2. search within the base class methods, consistently from the nearest ancestor to the very first.
3. search among other functions.

If there is no exact correspondence at all levels, but several suitable functions at different levels have
been found, the function found at the least level is used. W ithin one level, there can't be more than
one suitable function.
See also
Function Overloading

© 2000-2025, MetaQuotes Ltd.


287 Language Basics

Virtual Functions
The virtual keyword is the function specifier, which provides a mechanism to select dynamically at
runtime an appropriate function-member among the functions of basic and derived classes. S tructures
cannot have virtual functions. It can be used to change the declarations for function-members only.
The virtual function, like an ordinary function, must have an executable body. W hen called, its
semantic is the same as that of other functions.
A virtual function may be overridden in a derived class. The choice of what function definition should
be called for a virtual function is made dynamically (at runtime). A typical case is when a 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 to call will be performed at runtime and will depend on the type of
the object, not the type of the pointer. If there is no member of a derived type, the virtual function of
the base class is used by default.
Destructors are always virtual, regardless of whether they are declared with the virtual keyword or not.
Let's consider the use of virtual functions on the example of MT5_Tetris.mq5. The base class
CTetris S hape with the virtual function Draw is defined in the included file MT5_Tetris S hape.mqh.
//+------------------------------------------------------------------+
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[]);

© 2000-2025, MetaQuotes Ltd.


288 Language Basics

virtual bool CheckRight(int& side_row[]);


};

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

class CTetrisShape1 : public CTetrisShape


{
public:
//--- shape drawing
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 CTetris S hape6 and has its own implementation of the Draw()
method:
class CTetrisShape6 : public CTetrisShape
{
public:
//--- Shape drawing
virtual void Draw()
{
int i;
string name;

© 2000-2025, MetaQuotes Ltd.


289 Language Basics

//---
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 class, to which the created object belongs, it calls the virtual function of this or that
derived class.
void CTetrisField::NewShape()
{
//--- creating 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();
//---
}

Modifier 'override'
The 'override' modifier means that the declared function must override the method of a parent class.
Use of this method allows you to avoid overriding errors, for example it allows you to avoid accidental
modification of the method signature. S uppose, the 'func' method is defined in the base class. The
method accepts an int variable as an argument:
class CFoo
{
void virtual func(int x) const { }
};

Next, the method is overridden in the child class :

© 2000-2025, MetaQuotes Ltd.


290 Language Basics

class CBar : public CFoo


{
void func(short x) { }
};

H owever, the argument type is mistakenly changed from int to short. In fact, this is not method
overriding, but it is method overloading. Acting in accordance with the overloaded function defining
algorithm, the compiler can in certain situations choose a method defined in the base class instead of
the overridden method.
In order to avoid such errors, you should explicitly add the 'override' modifier to the method you want
to override.
class CBar : public CFoo
{
void func(short x) override { }
};

If the method signature is changed during overriding, the compiler will not be able to find a method
with the same signature in the parent class, and it will return a compilation error:
'CBar::func' method is declared with 'override' specifier but does not override any base class meth

Modifier 'final'
The 'final' modifier does the opposite — it prohibits method overriding in child classes. If a method
implementation is sufficient and fully complete, declare this method with the 'final' modifier so as to
make sure that it will not be modified later.
class CFoo
{
void virtual func(int x) final { }
};

class CBar : public CFoo


{
void func(int) { }
};

If you try to override a method with the 'final' modifier as shown in the above example, the compiler
will return an error:
'CFoo::func' method declared as 'final' cannot be overridden by 'CBar::func'
see declaration of 'CFoo::func'

See also
S tandard Library

© 2000-2025, MetaQuotes Ltd.


291 Language Basics

Static members of a Class/Structure


Static Members
The members of a class can be declared using the storage class modifier static. These data members
are shared by all instances of this class and are stored in one place. Non-static data members are
created for each class object variable.
The inability to declare static members of a class would have led to the need to declare these data on
the the global level of the program. It would break the relationship between the data and their class,
and is not consistent with the basic paradigm of the OOP - joining data and methods for handling them
in a class. The static member allows class data that are not specific to a particular instance to exist in
the class scope.
S ince a static class member does not depend on the particular instance, the reference to it is as
follows :
class_name::variable

where class_name is the name of the class, and variable is the name of the class member.
As you see, to access the static member of a class, context resolution operator :: is used. W hen you
access a static member within class methods, the context operator is optional.
S tatic member of a class has to be explicitly initialized with desired value. For this it must be declared
and initialized in global scope. The sequence of static members initialization will correspond to the
sequence of their declaration in global scope.
For example, we have a class CParser used for parsing the text, and we need to count the total
number of processed words and characters. W e only need to declare the necessary class members as
static and initialize them at the global level. Then all instances of the class will use common counters
of words and characters.
//+------------------------------------------------------------------+
//| Class "Text analyzer" |
//+------------------------------------------------------------------+
class CParser
{
public:
static int s_words;
static int s_symbols;
//--- Constructor and destructor
CParser(void);
~CParser(void){};
};
...
//--- Initialization of static members of the Parser class at the global level
int CParser::s_words=0;
int CParser::s_symbols=0;

A static class member can be declared with the const keyword. S uch static constants must be
initialized at the global level with the const keyword:

© 2000-2025, MetaQuotes Ltd.


292 Language Basics

//+------------------------------------------------------------------+
//| Class "Stack" for storing processed data |
//+------------------------------------------------------------------+
class CStack
{
public:
CStack(void);
~CStack(void){};
...
private:
static const int s_max_length; // Maximum stack capacity
};

//--- Initialization of the static constant of the CStack class


const int CStack::s_max_length=1000;

Pointer this
The keyword this denotes an implicitly declared pointer to itself – to a specific instance of the class, in
the context of which the method is executed. It can be used only in non-static methods of the class.
Pointer this is an implicit non-static member of any class.
In static functions you can access only static members /methods of a class.

Static Methods
In MQL5 member functions of type static can be used. The static modifier must precede the return
type of a function in the declaration inside a class.
class CStack
{
public:
//--- Constructor and destructor
CStack(void){};
~CStack(void){};
//--- Maximum stack capacity
static int Capacity();
private:
int m_length; // The number of elements in the stack
static const int s_max_length; // Maximum stack capacity
};
//+------------------------------------------------------------------+
//| Returns the maximum number of elements to store in the stack |
//+------------------------------------------------------------------+
int CStack::Capacity(void)
{
return(s_max_length);
}
//--- Initialization of the static constant of the CStack class
const int CStack::s_max_length=1000;

© 2000-2025, MetaQuotes Ltd.


293 Language Basics

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare CStack type variable
CStack stack;
//--- call the object's static method
Print("CStack.s_max_length=",stack.Capacity());
//--- it can also be called the following way, as the method is static and does not require the pre
Print("CStack.s_max_length=",CStack::Capacity());
}

A method with the const modifier is called constant and cannot modify implicit members of its class.
Declaration of constant functions of a class and constant parameters is called const-correctness
control. Through this control you can be sure that the compiler will ensure the consistency of values of
objects and will return an error during compilation if there is something wrong.
The const modifier is placed after the list of arguments inside a class declaration. Definition outside a
class should also include the const modifier:
//+------------------------------------------------------------------+
//| Class "Rectangle" |
//+------------------------------------------------------------------+
class CRectangle
{
private:
double m_width; // Width
double m_height; // Height
public:
//--- Constructors and destructor
CRectangle(void):m_width(0),m_height(0){};
CRectangle(const double w,const double h):m_width(w),m_height(h){};
~CRectangle(void){};
//--- Calculating the area
double Square(void) const;
static double Square(const double w,const double h);// { return(w*h); }
};
//+------------------------------------------------------------------+
//| Returns the area of the "Rectangle" object |
//+------------------------------------------------------------------+
double CRectangle::Square(void) const
{
return(Square(m_width,m_height));
}
//+------------------------------------------------------------------+
//| Returns the product of two variables |
//+------------------------------------------------------------------+
static double CRectangle::Square(const double w,const double h)
{

© 2000-2025, MetaQuotes Ltd.


294 Language Basics

return(w*h);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Create a rectangle rect with the sides equal to 5 and 6
CRectangle rect(5,6);
//--- Find the rectangle area using a constant method
PrintFormat("rect.Square()=%.2f",rect.Square());
//--- Find the product of numbers using the static method of class CRectangle
PrintFormat("CRectangle::Square(2.0,1.5)=%f",CRectangle::Square(2.0,1.5));
}

An additional argument in favor of using the constancy control is the fact that in this case, the
compiler generates a special optimization, for example, places a constant object in read-only memory.
A static function cannot be determined with the const modifier, because this modifier ensures the
constancy of the instance members when calling this function. But, as mentioned above, the static
function cannot access non-static class members.
See also
S tatic Variables, Variables, R eferences. Modifier & and Keyword this

© 2000-2025, MetaQuotes Ltd.


295 Language Basics

Function templates
Overloaded functions are commonly used to perform similar operations on various data types.
ArrayS ize() is a simple example of such function in MQL5. It returns size of any type of array. In fact,
this system function is overloaded and the entire implementation of such an overload is hidden from
MQL5 application developers :
int ArraySize(
void& array[] // checked array
);

It means that MQL5 language compiler inserts necessary implementation for each call of this function.
For example, that is how it can be done for integer type arrays :

int ArraySize(
int& array[] // array with int type elements
);

ArrayS ize() function can be displayed the following way for M qlRates type array for working with
quotations in historical data format:

int ArraySize(
MqlRates& array[] // array filled with MqlRates type values
);

Thus, it is very convenient to use the same function for working with different types. However, all
preliminary work should be carried out – the necessary function should be overloaded for all data types
it should correctly work with.
There is a convenient solution. If similar operations should be executed for each data type, it is
possible to use function templates. In this case, a programmer needs to write only one function
template description. W hen describing the template in such a way, we should specify only some formal
parameter instead of some definite data type the function should work with. The compiler will
automatically generate various functions for the appropriate handling of each type based on the types
of the arguments used when calling the function.
Function template definition starts with the template keyword followed by the list of formal
parameters in angle brackets. Each formal parameter is preceded by the typename keyword. Formal
parameter types are built-in or user-defined types. They are used:
· to specify the types of function arguments,
· to specify the types of function's return value,
· to declare the variables inside the function definition

Number of template parameters cannot exceed eight. Each formal parameter in the template
definition should appear in the list of function parameters at least once. Each name of the formal
parameter should be unique.
Below is an example of a function template for searching the highest value in the array of any numeric
type (integer and real numbers):

© 2000-2025, MetaQuotes Ltd.


296 Language Basics

template<typename T>
T ArrayMax(T &arr[])
{
uint size=ArraySize(arr);
if(size==0) return(0);

T max=arr[0];
for(uint n=1;n<size;n++)
if(max<arr[n]) max=arr[n];
//---
return(max);
}

This template defines the function that finds the highest value in the passed array and returns this
value as a result. Keep in mind that the ArrayMaximum() function built in MQL5 returns only the
highest value index that can be used to find the value itself. For example:
//--- create an array
double array[];
int size=50;
ArrayResize(array,size);
//--- fill with random values
for(int i=0;i<size;i++)
{
array[i]=MathRand();
}

//--- find position of the highest value in the array


int max_position=ArrayMaximum(array);
//--- now, get the highest value itself in the array
double max=array[max_position];
//--- display the found value
Print("Max value = ",max);

Thus, we have performed two steps to get the highest value in the array. W ith ArrayMax() function
template, we can get the result of the necessary type just by passing the array of an appropriate type
into this function. It means that instead of two last lines
//--- find position of the highest value in the array
int max_position=ArrayMaximum(array);
//--- now, get the highest value itself in the array
double max=array[max_position];

we now can use only one line, in which the returned result has the same type as the array passed into
function:
//--- find the highest value
double max=ArrayMax(array);

In this case, the type of result returned by the ArrayMax() function will automatically match the type of
array.

© 2000-2025, MetaQuotes Ltd.


297 Language Basics

Use the typename keyword to get the argument type as a string in order to create general purpose
methods of working with various data types. Let's consider a specific example of the function that
returns data type as a string:
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnStart()
{
//---
CTrade trade;
double d_value=M_PI;
int i_value=INT_MAX;
Print("d_value: type=",GetTypeName(d_value), ", value=", d_value);
Print("i_value: type=",GetTypeName(i_value), ", value=", i_value);
Print("trade: type=",GetTypeName(trade));
//---
}
//+------------------------------------------------------------------+
//| Type is returned as a line |
//+------------------------------------------------------------------+
template<typename T>
string GetTypeName(const T &t)
{
//--- return the type as a line
return(typename(T));
//---
}

Function templates can also be used for class methods, for example:
class CFile
{
...
public:
...
template<typename T>
uint WriteStruct(T &data);
};

template<typename T>
uint CFile::WriteStruct(T &data)
{
...
return(FileWriteStruct(m_handle,data));
}

© 2000-2025, MetaQuotes Ltd.


298 Language Basics

Function templates should not be declared with export, virtual and #import keywords.

Template function overload


A template function overload may be necessary sometimes. For example, we have a template function
that writes the value of the second parameter to the first one using typecasting. MQL5 does not allow
typecasting string to bool. W e can do that ourselves – let's create an overload of a template function.
For example:

//+------------------------------------------------------------------+
//| Template function |
//+------------------------------------------------------------------+
template<typename T1,typename T2>
string Assign(T1 &var1,T2 var2)
{
var1=(T1)var2;
return(__FUNCSIG__);
}
//+------------------------------------------------------------------+
//| Special overload for bool+string |
//+------------------------------------------------------------------+
string Assign(bool &var1,string var2)
{
var1=(StringCompare(var2,"true",false) || StringToInteger(var2)!=0);
return(__FUNCSIG__);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
int i;
bool b;
Print(Assign(i,"test"));
Print(Assign(b,"test"));
}

As a result of the code execution, we can see that the Assign() template function has been used for
the int+string pair, while the overloaded version has already been used for the bool+string pair during
the second call.
string Assign<int,string>(int&,string)
string Assign(bool&,string)

See also
Overload

© 2000-2025, MetaQuotes Ltd.


299 Language Basics

Template advantages
Function templates are used when you need to perform similar operations on various data types, for
example, searching for a maximum element in the array. The main advantage of applying the
templates is that you do not have to code a separate overload for each type. Instead of declaring
multiple overloads of each type
double ArrayMax(double array[])
{
...
}
int ArrayMax(int array[])
{
...
}
uint ArrayMax(uint array[])
{
...
}
long ArrayMax(long array[])
{
...
}
datetime ArrayMax(datetime array[])
{
...
}

we need to write only one template function


template<typename T>
T ArrayMax(T array[])
{
if(ArraySize()==0)
return(0);
uint max_index=ArrayMaximum(array);
return(array[max_index]);
}

to use it in your code:


double high[];
datetime time[];
....
double max_high=ArrayMax(high);
datetime lasttime=ArrayMax(time);

H ere,the T formal parameter specifying a type of used data is replaced with an actually applied type
during compilation, i.e. the compiler automatically generates a separate function for each type –
double, datetime, etc. MQL5 also allows you to develop class templates using all the advantages of the
approach.

© 2000-2025, MetaQuotes Ltd.


300 Language Basics

Class templates
A class template is declared using the template keyword followed by angle brackets <> enumerating the
list of formal parameters with the typename keyword. This entry informs the compiler that it deals
with a generic class with the T formal parameter defining a real variable type when implementing a
class. For example, let's create a vector class for storing an array with T type elements :
#define TOSTR(x) #x+" " // macro for displaying an object name
//+------------------------------------------------------------------+
//| Vector class for storing T-type elements |
//+------------------------------------------------------------------+
template <typename T>
class TArray
{
protected:
T m_array[];
public:
//--- constructor creates an array for 10 elements by default
void TArray(void){ArrayResize(m_array,10);}
//--- constructor for creating a vector with a specified array size
void TArray(int size){ArrayResize(m_array,size);}
//--- return a type and amount of data stored in the TArray type object
string Type(void){return(typename(m_array[0])+":"+(string)ArraySize(m_array));};
};

Next, let's apply different methods to create three TArray objects in the program for working with
various types
void OnStart()
{
TArray<double> double_array; // vector has a default size of 10
TArray<int> int_array(15); // vector has a size of 15
TArray<string> *string_array; // pointer to TArray<string> vector
//--- create a dynamic object
string_array=new TArray<string>(20);
//--- display an object name, data type and vector size in the Journal
PrintFormat("%s (%s)",TOSTR(double_array),double_array.Type());
PrintFormat("%s (%s)",TOSTR(int_array),int_array.Type());
PrintFormat("%s (%s)",TOSTR(string_array),string_array.Type());
//--- remove a dynamic object before completing the program
delete(string_array);
}

S cript execution results :

double_array (double:10)
int_array (int:15)
string_array (string:20)

Now, we have 3 vectors with different data types : double, int and string.

© 2000-2025, MetaQuotes Ltd.


301 Language Basics

Class templates are well suited for developing containers – objects designed for encapsulating other
objects of any type. Container objects are collections already containing objects of one certain type.
Usually, work ing with stored data is instantly built into the container.

For example, you can create a class template that does not allow accessing an element outside the
array, thus avoiding the " out of range" critical error.
//+------------------------------------------------------------------+
//| Class for a free access to an array element |
//+------------------------------------------------------------------+
template<typename T>
class TSafeArray
{
protected:
T m_array[];
public:
//--- default constructor
void TSafeArray(void){}
//--- constructor for creating the array of a specified size
void TSafeArray(int size){ArrayResize(m_array,size);}
//--- array size
int Size(void){return(ArraySize(m_array));}
//--- change the array size
int Resize(int size,int reserve){return(ArrayResize(m_array,size,reserve));}
//--- release the array
void Erase(void){ZeroMemory(m_array);}
//--- operator for accessing the array element by index
T operator[](int index);
//--- assignment operator for receiving all elements from the array at once
void operator=(const T &array[]); // T type array
};
//+------------------------------------------------------------------+
//| Receiving an element by index |
//+------------------------------------------------------------------+
template<typename T>
T TSafeArray::operator[](int index)
{
static T invalid_value;
//---
int max=ArraySize(m_array)-1;
if(index<0 || index>=ArraySize(m_array))
{
PrintFormat("%s index %d is not in range (0-%d)!",__FUNCTION__,index,max);
return(invalid_value);
}
//---
return(m_array[index]);
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


302 Language Basics

//| Assigning for the array |


//+------------------------------------------------------------------+
template<typename T>
void TSafeArray::operator=(const T &array[])
{
int size=ArraySize(array);
ArrayResize(m_array,size);
//--- T type should support the copying operator
for(int i=0;i<size;i++)
m_array[i]=array[i];
//---
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
int copied,size=15;
MqlRates rates[];
//--- copy the array of quotes
if((copied=CopyRates(_Symbol,_Period,0,size,rates))!=size)
{
PrintFormat("CopyRates(%s,%s,0,%d) returned %d error code",
_Symbol,EnumToString(_Period),size,GetLastError());
return;
}
//--- create a container and insert the MqlRates value array to it
TSafeArray<MqlRates> safe_rates;
safe_rates=rates;
//--- index within the array
int index=3;
PrintFormat("Close[%d]=%G",index,safe_rates[index].close);
//--- index outside the array
index=size;
PrintFormat("Close[%d]=%G",index,safe_rates[index].close);
}

Please note that template declaration should also be used when describing methods outside the class
declaration:
template<typename T>
T TSafeArray::operator[](int index)
{
...
}
template<typename T>
void TSafeArray::operator=(const T &array[])
{
...

© 2000-2025, MetaQuotes Ltd.


303 Language Basics

Class and function templates allow you to define multiple comma-separated formal parameters, for
example, Map collection for storing "key – value" pairs :
template<typename Key, template Value>
class TMap
{
...
}

See also
Function templates, Overload

© 2000-2025, MetaQuotes Ltd.


304 Language Basics

Abstract Classes and Pure Virtual Functions


Abstract classes are used for creating generic entities, that you expect to use for creating more
specific derived classes. An abstract class can only be used as the base class for some other class, that
is why it is impossible to create an object of the abstract class type.
A class which contains at least one pure virtual function in it is abstract. Therefore, classes derived
from the abstract class must implement all its pure virtual functions, otherwise they will also be
abstract classes.
A virtual function is declared as " pure" by using the pure-specifier syntax. Consider the example of the
CAnimal class, which is only created to provide common functions – the objects of the CAnimal type
are too general for practical use. Thus, CAnimal is a good example for an abstract class :
class CAnimal
{
public:
CAnimal(); // Constructor
virtual void Sound() = 0; // A pure virtual function
private:
double m_legs_count; // The number of the animal's legs
};

H ere S ound() is a pure virtual function, because it is declared with the specifier of the pure virtual
function PURE (=0).
Pure virtual functions are only the virtual functions for which the PURE specifier is set: (=NULL) or
(=0). Example of abstract class declaration and use:
class CAnimal
{
public:
virtual void Sound()=NULL; // PURE method, should be overridden in the derived class, CA
};
//--- Derived from an abstract class
class CCat : public CAnimal
{
public:
virtual void Sound() { Print("Myau"); } // PURE is overridden, CCat is not abstract and ca
};

//--- Examples of wrong use


new CAnimal; // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract
CAnimal some_animal; // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract

//--- Examples of proper use


new CCat; // No error - the CCat class is not abstract
CCat cat; // No error - the CCat class is not abstract

© 2000-2025, MetaQuotes Ltd.


305 Language Basics

Restrictions on abstract classes


If the constructor for an abstract class calls a pure virtual function (either directly or indirectly), the
result is undefined.
//+------------------------------------------------------------------+
//| An abstract base class |
//+------------------------------------------------------------------+
class CAnimal
{
public:
//--- A pure virtual function
virtual void Sound(void)=NULL;
//--- Function
void CallSound(void) { Sound(); }
//--- Constructor
CAnimal()
{
//--- An explicit call of the virtual method
Sound();
//--- An implicit call (using a third function)
CallSound();
//--- A constructor and/or destructor always calls its own functions,
//--- even if they are virtual and overridden by a called function in a derived class
//--- If the called function is pure virtual,
//--- its call will cause a critical runtime error: "pure virtual function call"
}
};

H owever, constructors and destructors for abstract classes can call other member functions.

© 2000-2025, MetaQuotes Ltd.


306 Language Basics

Namespaces
A namespace is a specially declared area, within which various IDs are defined: variables, functions,
classes, etc. It is set using the namespace keyword:
namespace name of_space {
// list of function, class and variable definitions
}

Applying 'namespace' allows splitting the global namespace into subspaces. All IDs within the
namespace are available to each other without a specification. The :: operator (context resolution
operation) is used to access namespace members from the outside.
namespace ProjectData
{
class DataManager
{
public:
void LoadData() {}
};
void Func(DataManager& manager) {}
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- working with ProjectData namespace
ProjectData::DataManager mgr;
mgr.LoadData();
ProjectData::Func(mgr);
}

Namespaces are used to arrange a code in the form of logical groups and to avoid name conflicts that
may occur when several libraries are used in a program. In such cases, each library can be declared in
its namespace to explicitly access the necessary functions and classes of each library.
A namespace can be declared in several blocks in one or several files. The compiler combines all parts
together during a preprocessing and the resulting namespace contains all the members declared in all
parts. S uppose that we have A class implemented in the S ample.mqh include file:
//+------------------------------------------------------------------+
//| Sample.mqh |
//+------------------------------------------------------------------+
class A
{
public:
A() {Print(__FUNCTION__);}
};

© 2000-2025, MetaQuotes Ltd.


307 Language Basics

W e want to use this class in our project, but we already have A class. To be able to use both classes
and avoid ID conflict, simply wrap the included file in a namespace:
//--- declare the first A class
class A
{
public:
A() {Print(__FUNCTION__);}
};
//--- wrap the A class from the Sample.mqh file in the Library namespace to avoid a conflict
namespace Library
{
#include "Sample.mqh"
}
//--- add yet another class to the Library namespace
namespace Library
{
class B
{
public:
B() {Print(__FUNCTION__);}
};
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- use the A class from the global namespace
A a1;
//--- use the A and B classes from the Library namespace
Library::A a2;
Library::B b;
}
//+------------------------------------------------------------------+

/*
Result:
A::A
Library::A::A
Library::B::B
*/

Namespaces can be nested. A nested namespace has unlimited access to members of its parent space,
but members of the parent space do not have unlimited access to the nested namespace.
namespace General
{
int Func();

© 2000-2025, MetaQuotes Ltd.


308 Language Basics

namespace Details
{
int Counter;
int Refresh() {return Func(); }
}

int GetBars() {return(iBars(Symbol(), Period()));};


int Size(int i) {return Details::Counter;}
}

Global namespace
If the ID is not explicitly declared in the namespace, it is considered to be an implicit part of the global
namespace. To set the global ID explicitly, use the scope resolution operator without a name. This will
allow you to distinguish this ID from any other element with the same name located in a different
namespace. For example, when importing a function:
#import "lib.dll"
int Func();
#import
//+------------------------------------------------------------------+
//| Some function |
//+------------------------------------------------------------------+
int Func()
{
return(0);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//+--- call the imported function
Print(lib::Func());
//+--- call our function
Print(::Func());
}

In this case, all the functions imported from the DLL function were included in the namespace of the
same name. This allowed the compiler to clearly determine the function to be called.
See also
Global Variables, Local Variables, Visibility S cope and Lifetime of Variables, Creating and Deleting
Objects

© 2000-2025, MetaQuotes Ltd.


309 Constants, Enumerations and Structures

Constants, Enumerations and Structures


To simplify the program writing and to make program texts more convenient for perception, the MQL5
language provides predefined standard constants and enumerations. Besides that, service structures
are used for storing information.
S tandard constants are similar to macros and are of int type.
The constants are grouped by their purposes :
· Chart constants are used when working with price charts : opening, navigation, setting parameters ;
· Objects constants are intended for processing graphical objects that can be created and displayed in
charts ;
· Indicators constants are used for working with standard and custom indicators ;
· Environment state constants describe properties of a MQL5-program, show information about a
client terminal, financial instrument and current account;
· Trade constants allow to specify a variety of information in the course of trading;
· Named constants are constants of the MQL5 language;
· Data structures describe data storage formats used;
· Codes of errors and warnings describe compiler messages and trading server answers to trade
requests ;
· In/out constants are designed for working with file functions and displaying messages on the screen
by the MessageBox() function.

© 2000-2025, MetaQuotes Ltd.


310 Constants, Enumerations and Structures

Chart Constants
Constants describing various properties of charts are divided into the following groups :
· Types of events – events that occur when working with charts ;
· Chart timeframes – standard built-in periods ;
· Properties of chart – identifiers that are used as parameters of chart functions ;
· Positioning constants - value of a parameter of the ChartNavigate() function;
· Displaying charts - setting the chart appearance.

© 2000-2025, MetaQuotes Ltd.


311 Constants, Enumerations and Structures

Types of Chart Events


There are 11 types of events that can be processed using the predefined function OnChartEvent(). For
custom events 65535 identifiers are provided in the range of CHARTEVENT_CUS TOM to
CHARTEVENT_CUS TOM _LAS T inclusive. To generate a custom event, the EventChartCustom() function
should be used.
ENUM_CHART_EVENT

ID Description

CHARTEVENT_KEYDOWN Keystrok es

CHARTEVENT_MOUSE_MOVE Mouse move, mouse clicks (if


CHART_EVENT_MOUSE_MOVE=true is set for the
chart)
CHARTEVENT_MOUSE_WHEEL Pressing or scrolling the mouse wheel (if
CHART_EVENT_MOUSE_WHEEL=True for the
chart)
CHARTEVENT_OBJECT_CREATE Graphical object created (if
CHART_EVENT_OBJECT_CREATE=true is set for
the chart)
CHARTEVENT_OBJECT_CHANGE Graphical object property changed via the
properties dialog
CHARTEVENT_OBJECT_DELETE Graphical object deleted (if
CHART_EVENT_OBJECT_DELETE=true is set for
the chart)
CHARTEVENT_CLICK Clicking on a chart
CHARTEVENT_OBJECT_CLICK Clicking on a graphical object
CHARTEVENT_OBJECT_DRAG Drag and drop of a graphical object
CHARTEVENT_OBJECT_ENDEDIT End of text editing in the graphical object Edit
CHARTEVENT_CHART_CHANGE Change of the chart size or modification of chart
properties through the Properties dialog
CHARTEVENT_CUS TOM Initial number of an event from a range of
custom events
CHARTEVENT_CUS TOM _LAS T The final number of an event from a range of
custom events

For each type of event, the input parameters of the OnChartEvent() function have definite values that
are required for the processing of this event. The events and values passed through this parameters
are listed in the below table.

© 2000-2025, MetaQuotes Ltd.


312 Constants, Enumerations and Structures

Event Value of the id Value of the Value of the Value of the


parameter lparam dparam sparam
parameter parameter parameter

Event of a CHARTEVENT_KE code of a R epeat count The string value


k eystrok e YDOWN pressed key (the number of of a bit mas k
times the describing the
k eystrok e is status of
repeated as a k eyboard buttons
result of the user
holding down the
k ey)

Mouse events (if CHARTEVENT_MO the X coordinate the Y coordinate The string value
CHART_EVENT_ USE_MOVE of a bit mas k
MOUSE_MOVE=tr describing the
ue is set for the status of mouse
chart) buttons
Mouse wheel CHARTEVENT_MO Flags of states of The Delta value —
event (if USE_WHEEL k eys and mouse of the mouse
CHART_EVENT_ buttons, the X wheel scroll
MOUSE_WHEEL= and Y
true for the coordinates of
chart) the mouse
pointer. S ee
description in
the example
below
event of CHARTEVENT_OB — — Name of the
graphical object JECT _CREAT E created graphical
creation (if object
CHART_EVENT_O
BJECT _CREAT E=t
rue is set for the
chart)
Event of change CHARTEVENT_OB — — Name of the
of an object JECT _CHANGE modified
property via the graphical object
properties dialog
Event of CHARTEVENT_OB — — Name of the
graphical object JECT _DEL ET E deleted graphical
deletion (if object
CHART_EVENT_O
BJECT _DEL ET E=t
rue is set for the
chart)
Event of a CHARTEVENT_C the X coordinate the Y coordinate —
mouse click on LICK

© 2000-2025, MetaQuotes Ltd.


313 Constants, Enumerations and Structures

Event Value of the id Value of the Value of the Value of the


parameter lparam dparam sparam
parameter parameter parameter

the chart
Event of a CHARTEVENT_OB the X coordinate the Y coordinate Name of the
mouse click in a JECT _CLICK graphical object,
graphical object on which the
belonging to the event occurred
chart
Event of a CHARTEVENT_OB — — Name of the
graphical object JECT _DRAG moved graphical
dragging using object
the mouse
Event of the CHARTEVENT_OB — — Name of the
finished text JECT _ENDEDIT LabelEdit
editing in the graphical object,
entry box of the in which text
LabelEdit editing has
graphical object completed
Event of change CHARTEVENT_C — — —
of the chart size HAR T _CHANGE
or modification
of chart
properties
through the
Properties dialog
ID of the user CHARTEVENT_CU Value set by the Value set by the Value set by the
event under the S TOM+N EventChartCusto EventChartCusto EventChartCusto
N number m() function m() function m() function

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
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()

© 2000-2025, MetaQuotes Ltd.


314 Constants, Enumerations and Structures

{
//---
Print("The expert with name ",MQL5InfoString(MQL5_PROGRAM_NAME)," is running");
//--- enable object create events
ChartSetInteger(ChartID(),CHART_EVENT_OBJECT_CREATE,true);
//--- enable object delete events
ChartSetInteger(ChartID(),CHART_EVENT_OBJECT_DELETE,true);
//--- forced updating of chart properties ensures readiness for event processing
ChartRedraw();
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, // Event identifier
const long& lparam, // Event parameter of long type
const double& dparam, // Event parameter of double type
const string& sparam // Event parameter of string type
)
{
//--- the left mouse button has been pressed on the chart
if(id==CHARTEVENT_CLICK)
{
Print("The coordinates of the mouse click on the chart are: x = ",lparam," y = ",dparam);
}
//--- the mouse has been clicked on the graphic object
if(id==CHARTEVENT_OBJECT_CLICK)
{
Print("The mouse has been clicked on the object with name '"+sparam+"'");
}
//--- the key has been pressed
if(id==CHARTEVENT_KEYDOWN)
{
switch(lparam)
{
case KEY_NUMLOCK_LEFT: Print("The KEY_NUMLOCK_LEFT has been pressed"); break;
case KEY_LEFT: Print("The KEY_LEFT has been pressed"); break;
case KEY_NUMLOCK_UP: Print("The KEY_NUMLOCK_UP has been pressed"); break;
case KEY_UP: Print("The KEY_UP has been pressed"); break;
case KEY_NUMLOCK_RIGHT: Print("The KEY_NUMLOCK_RIGHT has been pressed"); break;
case KEY_RIGHT: Print("The KEY_RIGHT has been pressed"); break;
case KEY_NUMLOCK_DOWN: Print("The KEY_NUMLOCK_DOWN has been pressed"); break;
case KEY_DOWN: Print("The KEY_DOWN has been pressed"); break;
case KEY_NUMPAD_5: Print("The KEY_NUMPAD_5 has been pressed"); break;
case KEY_NUMLOCK_5: Print("The KEY_NUMLOCK_5 has been pressed"); break;
default: Print("Some not listed key has been pressed");
}
ChartRedraw();

© 2000-2025, MetaQuotes Ltd.


315 Constants, Enumerations and Structures

}
//--- the object has been deleted
if(id==CHARTEVENT_OBJECT_DELETE)
{
Print("The object with name ",sparam," has been deleted");
}
//--- the object has been created
if(id==CHARTEVENT_OBJECT_CREATE)
{
Print("The object with name ",sparam," has been created");
}
//--- the object has been moved or its anchor point coordinates has been changed
if(id==CHARTEVENT_OBJECT_DRAG)
{
Print("The anchor point coordinates of the object with name ",sparam," has been changed");
}
//--- the text in the Edit of object has been changed
if(id==CHARTEVENT_OBJECT_ENDEDIT)
{
Print("The text in the Edit field of the object with name ",sparam," has been changed");
}
}

For CHAR T EVENT _MOUSE_MOVE event the sparam string parameter contains information about state
of the keyboard and mouse buttons :

Bit Description

1 S tate of the left mouse button


2 S tate of the right mouse button
3 S tate of the SHIFT button
4 S tate of the CTRL button
5 S tate of the middle mouse button
6 S tate of the first extra mouse button
7 S tate of the second extra mouse button

Example:

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- enable CHART_EVENT_MOUSE_MOVE messages
ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,1);
//--- disable the context menu of the chart (on the right)

© 2000-2025, MetaQuotes Ltd.


316 Constants, Enumerations and Structures

ChartSetInteger(0,CHART_CONTEXT_MENU,0);
//--- disable the crosshair (by the middle button)
ChartSetInteger(0,CHART_CROSSHAIR_TOOL,0);
//--- forced updating of chart properties ensures readiness for event processing
ChartRedraw();
}
//+------------------------------------------------------------------+
//| MouseState |
//+------------------------------------------------------------------+
string MouseState(uint state)
{
string res;
res+="\nML: " +(((state& 1)== 1)?"DN":"UP"); // mouse left
res+="\nMR: " +(((state& 2)== 2)?"DN":"UP"); // mouse right
res+="\nMM: " +(((state&16)==16)?"DN":"UP"); // mouse middle
res+="\nMX: " +(((state&32)==32)?"DN":"UP"); // mouse first X key
res+="\nMY: " +(((state&64)==64)?"DN":"UP"); // mouse second X key
res+="\nSHIFT: "+(((state& 4)== 4)?"DN":"UP"); // shift key
res+="\nCTRL: " +(((state& 8)== 8)?"DN":"UP"); // control key
return(res);
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
{
if(id==CHARTEVENT_MOUSE_MOVE)
Comment("POINT: ",(int)lparam,",",(int)dparam,"\n",MouseState((uint)sparam));
}

For the CHARTEVENT_MOUSE_WHEEL event, parameters lparam and dparam contain information
about the states of the Ctrl and Shift keys, of mouse buttons, cursor coordinates and the mouse wheel
scroll value. For a better understanding, run this Expert Advisor on a chart and scroll the mouse wheel,
while pressing different buttons and holding down the keys described in the code.
Example of CHAR T EVENT _MOUSE_WHEEL event processing:
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
init OnInit()
{
//--- Enabling mouse wheel scrolling messages
ChartSetInteger(0,CHART_EVENT_MOUSE_WHEEL,1);
//--- Forced updating of chart properties ensures readiness for event processing
ChartRedraw();
//---
return(INIT_SUCCEEDED);

© 2000-2025, MetaQuotes Ltd.


317 Constants, Enumerations and Structures

}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
{
if(id==CHARTEVENT_MOUSE_WHEEL)
{
//--- Consider the state of mouse buttons and wheel for this event
int flg_keys = (int)(lparam>>32); // The flag of states of the Ctrl and Shift keys,
int x_cursor = (int)(short)lparam; // the X coordinate where the mousse wheel event o
int y_cursor = (int)(short)(lparam>>16); // the Y coordinate where the mousse wheel event o
int delta = (int)dparam; // the total value of mouse scroll, triggers when
//--- Processing the flag
string str_keys="";
if((flg_keys&0x0001)!=0) str_keys+="LMOUSE ";
if((flg_keys&0x0002)!=0) str_keys+="RMOUSE ";
if((flg_keys&0x0004)!=0) str_keys+="SHIFT ";
if((flg_keys&0x0008)!=0) str_keys+="CTRL ";
if((flg_keys&0x0010)!=0) str_keys+="MMOUSE ";
if((flg_keys&0x0020)!=0) str_keys+="X1MOUSE ";
if((flg_keys&0x0040)!=0) str_keys+="X2MOUSE ";

if(str_keys!="")
str_keys=", keys='"+StringSubstr(str_keys,0,StringLen(str_keys)-1) + "'";
PrintFormat("%s: X=%d, Y=%d, delta=%d%s",EnumToString(CHARTEVENT_MOUSE_WHEEL),x_cursor,y_curs
}
}
//+------------------------------------------------------------------+ /*
Example of the output
CHARTEVENT_MOUSE_WHEEL: Ctrl pressed: X=193, Y=445, delta=-120
CHARTEVENT_MOUSE_WHEEL: Shift pressed: X=186, Y=446, delta=120
CHARTEVENT_MOUSE_WHEEL: X=178, Y=447, delta=-120
CHARTEVENT_MOUSE_WHEEL: X=231, Y=449, delta=120
CHARTEVENT_MOUSE_WHEEL: MiddleButton pressed: X=231, Y=449, delta=120
CHARTEVENT_MOUSE_WHEEL: LeftButton pressed: X=279, Y=320, delta=-120
CHARTEVENT_MOUSE_WHEEL: RightButton pressed: X=253, Y=330, delta=120 */

See also
Event H andling Functions, W ork ing with events

© 2000-2025, MetaQuotes Ltd.


318 Constants, Enumerations and Structures

Chart Timeframes
Allpredefined timeframes of charts have unique identifiers. The PERIOD_CURRENT identifier means
the current period of a chart, at which a mql5-program is running.
ENUM_TIMEFRAMES

ID Description

PERIOD_CURRENT Current timeframe


PERIOD_M 1 1 minute
PERIOD_M 2 2 minutes
PERIOD_M 3 3 minutes
PERIOD_M 4 4 minutes
PERIOD_M5 5 minutes
PERIOD_M 6 6 minutes
PERIOD_M 10 10 minutes
PERIOD_M 12 12 minutes
PERIOD_M 15 15 minutes
PERIOD_M 20 20 minutes
PERIOD_M 30 30 minutes
PERIOD_H1 1 hour
PERIOD_H2 2 hours
PERIOD_H3 3 hours
PERIOD_H4 4 hours
PERIOD_H6 6 hours
PERIOD_H8 8 hours
PERIOD_H12 12 hours
PERIOD_D1 1 day
PERIOD_W1 1 week
PERIOD_M N1 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 exist - create it
if(ObjectFind(0,chart_name)<0)ObjectCreate(0,chart_name,OBJ_CHART,0,0,0,0,0);

© 2000-2025, MetaQuotes Ltd.


319 Constants, Enumerations and Structures

//--- Define symbol


ObjectSetString(0,chart_name,OBJPROP_SYMBOL,"EURUSD");
//--- Set X coordinate of the anchor point
ObjectSetInteger(0,chart_name,OBJPROP_XDISTANCE,100);
//--- Set Y coordinate of the 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)
ObjectSetDouble(0,chart_name,OBJPROP_SCALE,4);
//--- Disable selection by a mouse
ObjectSetInteger(0,chart_name,OBJPROP_SELECTABLE,false);

Timeseries identifiers

The identifiers of timeseries are used in the iHighest() and iLowest() functions. They can be equal to
a value the enumeration
ENUM_SERIESMODE

Identifier Description

MODE_OPEN Opening price


MODE_LOW Low price
MODE_HIGH H igh price

MODE_CLOSE Close price


MODE_VOLUM E Tick volume
MODE_REAL_VOLUM E R eal volume

MODE_S PREAD S pread

See also

PeriodS econds, Period, Date and Time, Visibility of objects

© 2000-2025, MetaQuotes Ltd.


320 Constants, Enumerations and Structures

Chart Properties
Identifiers of ENUM _CHART_PROPERTY enumerations are used as parameters of functions for working
with charts. The abbreviation of r/o in the " Property Type" column means that this property is read-
only and cannot be changed. The w/o abbreviation in the " Property Type" column means that this
property is write-only and it cannot be received. W hen accessing certain properties, it's necessary to
specify an additional parameter-modifier (modifier), which serves to indicate the number of chart
subwindows. 0 means the main window.
The functions defining the chart properties are actually used for sending change commands to the
chart. If these functions are executed successfully, the command is included in the common queue of
the chart events. The changes are implemented to the chart when handling the queue of the chart
events.
Thus, do not expect an immediate visual update of the chart after calling these functions. Generally,
the chart is updated automatically by the terminal following the change events - a new quote arrival,
resizing the chart window, etc. Use ChartRedraw() function to forcefully update the chart.
For functions ChartS etInteger() and ChartGetInteger()
ENUM_CHART_PROPERTY _INTEGER

ID Description Property Type

CHART_SHOW Price chart drawing. If false, drawing any bool


price chart attributes is disabled and all
chart border indents are eliminated,
including time and price scales, quick
navigation bar, Calendar event labels,
trade labels, indicator and bar tooltips,
indicator subwindows, volume histograms,
etc.
Disabling the drawing is a perfect solution
for creating a custom program interface
using the graphical resources.
The graphical objects are always drawn
regardless of the CHART_SHOW property
value.
CHART_IS_OBJECT Identifying " Chart" (OBJ_CHART) object – bool r/o
returns true for a graphical object.
R eturns false for a real chart

CHART_BRING_TO_TO S how chart on top of other charts bool


P
CHART_CONTEXT_M E Enabling /disablingaccess to the context bool (default is true)
NU menu using the right click.
W hen CHAR T _CONT EXT _M ENU=false, only
the chart context menu is disabled. The
context menu of objects on the chart
remains available.

© 2000-2025, MetaQuotes Ltd.


321 Constants, Enumerations and Structures

ID Description Property Type

CHART_CROSSHAIR_T Enabling/disabling access to the Crosshair bool (default is true)


OOL tool using the middle click.
CHART_MOUSE_S CRO S crollingthe chart horizontally using the bool
LL left mouse button. Vertical scrolling is also
available if the value of any following
properties is set to true:
CHART_S CALEFIX, CHART_S CALEFIX_11 or
CHART_S CALE_PT_PER_BAR
W hen CHAR T _MOUSE_S CR OLL =false, chart
scrolling with the mouse wheel is
unavailable
CHART_EVENT_MOUS S ending messages about mouse wheel bool (default is true)
E_WHEEL events (CHARTEVENT_MOUSE_WHEEL) to
all mql5 programs on a chart
CHART_EVENT_MOUS S end notifications of mouse move and bool
E_MOVE mouse click events
(CHARTEVENT_MOUSE_MOVE) to all mql5
programs on a chart
CHART_EVENT_OBJEC S end a notification of an event of new bool
T_CREATE object creation
(CHARTEVENT_OBJECT_CREATE) to all
mql5-programs on a chart
CHART_EVENT_OBJEC S end a notification of an event of object bool
T_DELETE deletion (CHARTEVENT_OBJECT_DELETE)
to all mql5-programs on a chart
CHART_MODE Chart type (candlesticks, bars or line) enum
ENUM _CHAR T _MODE

CHART_FOREGROUND Price chart in the foreground bool


CHART_SHIFT Mode of price chart indent from the right bool
border
CHART_AUTOS CROLL Mode of automatic moving to the right bool
border of the chart
CHART_KEYBOARD_C Allow managing the chart using a k eyboard bool
ONTROL ("Home" , "End" , " PageUp" , " +" , " -" , "Up
arrow" , etc.). S etting
CHART_KEYBOARD_CONTROL to false
disables chart scrolling and scaling while
leaving intact the ability to receive the
k eys pressing events in OnChartEvent().

CHART_QUICK_NAVIG Allow the chart to intercept S pace and bool


ATION Enter k ey strokes to activate the quick
navigation bar. The quick navigation bar

© 2000-2025, MetaQuotes Ltd.


322 Constants, Enumerations and Structures

ID Description Property Type

automatically appears at the bottom of the


chart after double-clicking the mouse or
pressing S pace/Enter. It allows you to
quick ly change a symbol, timeframe and
first visible bar date.
CHART_S CALE S cale int from 0 to 5
CHART_S CALEFIX Fixed scale mode bool
CHART_S CALEFIX_11 S cale 1:1 mode bool
CHART_S CALE_PT_PE S cale to be specified in points per bar bool
R_BAR

CHART_SHOW_TICKE Display a symbol ticker in the upper left bool


R corner. S etting CHART_SHOW_TICKER to
'false' also sets CHAR T _SH OW_OH LC to
'false' and disables OH LC

CHART_SHOW_OHLC Display OHLC values in the upper left bool


corner. S etting CHART_SHOW_OHLC to
'true' also sets CHAR T _SH OW_TICKER to
'true' and enables the tick er

CHART_SHOW_BID_LI Display Bid values as a horizontal line in a bool


NE chart
CHART_SHOW_ASK_LI Display As k values as a horizontal line in a bool
NE chart
CHART_SHOW_LAS T_ Display Last values as a horizontal line in a bool
LINE chart
CHART_SHOW_PERIO Display vertical separators between bool
D_SEP adjacent periods
CHART_SHOW_GRID Display grid in the chart bool
CHART_SHOW_VOLU Display volume in the chart enum
M ES ENUM _CHAR T _VOL UM E_MOD
E

CHART_SHOW_OBJEC Display textual descriptions of objects (not bool


T_DES CR available for all objects)
CHART_SHOW_TRADE Display trades from the trading history as bool
_H IS TORY entry/exit arrows on a chart. S ee the
"S how trading history" option descriptions
in the platform settings.
CHART_VIS IBLE_BARS The number of bars on the chart that can int r/o
be displayed

© 2000-2025, MetaQuotes Ltd.


323 Constants, Enumerations and Structures

ID Description Property Type

CHART_W INDOWS_TO The total number of chart windows, int r/o


T AL including indicator subwindows
CHART_W INDOW_IS_ Visibility of subwindows bool r/o modifier -
VIS IBL E subwindow number
CHART_W INDOW_HA Chart window handle (HWND) int r/o
NDL E

CHART_W INDOW_YDI The distance between the upper frame of int r/o modifier -
S T ANCE the indicator subwindow and the upper subwindow number
frame of the main chart window, along the
vertical Y axis, in pixels. In case of a
mouse event, the cursor coordinates are
passed in terms of the coordinates of the
main chart window, while the coordinates
of graphical objects in an indicator
subwindow are set relative to the upper
left corner of the subwindow.
The value is required for converting the
absolute coordinates of the main chart to
the local coordinates of a subwindow for
correct work with the graphical objects,
whose coordinates are set relative to the
upper left corner of the subwindow frame.
CHART_FIRS T_VIS IBLE Number of the first visible bar in the int r/o
_BAR chart. Indexing of bars is the same as for
timeseries.
CHART_W IDTH_IN_BA Chart width in bars int r/o
RS

CHART_W IDTH_IN_PI Chart width in pixels int r/o


XEL S

CHART_HEIGHT_IN_PI Chart height in pixels int modifier - subwindow


XEL S number
CHART_COLOR_BACK Chart background color color
GR OUND

CHART_COLOR_FORE Color of axes, scales and OHLC line color


GR OUND

CHART_COLOR_GRID Grid color color


CHART_COLOR_VOLU Color of volumes and position opening color
ME levels
CHART_COLOR_CHAR Color for the up bar, shadows and body color
T_UP borders of bull candlesticks

© 2000-2025, MetaQuotes Ltd.


324 Constants, Enumerations and Structures

ID Description Property Type

CHART_COLOR_CHAR Color for the down bar, shadows and body color
T_DOWN borders of bear candlesticks
CHART_COLOR_CHAR Line chart color and color of "Doji" color
T_LINE Japanese candlestick s

CHART_COLOR_CAND Body color of a bull candlestick color


LE_BULL
CHART_COLOR_CAND Body color of a bear candlestick color
LE_BEAR
CHART_COLOR_BID Bid price level color color
CHART_COLOR_ASK As k price level color color
CHART_COLOR_LAS T Line color of the last executed deal price color
(Last)
CHART_COLOR_S TOP Color of stop order levels (S top Loss and color
_L EVEL Take Profit)
CHART_SHOW_TRADE Displaying trade levels in the chart (levels bool
_L EVEL S of open positions, S top Loss, Take Profit
and pending orders)
CHART_DRAG_TRADE Permission to drag trading levels on a bool
_L EVEL S chart with a mouse. The drag mode is
enabled by default (true value)
CHART_SHOW_DATE_ S howing the time scale on a chart bool
S CA L E

CHART_SHOW_PRICE S howing the price scale on a chart bool


_S CAL E

CHART_SHOW_ONE_C S howing the " One click trading" panel on a bool


LICK chart
CHART_IS_M AXIMIZED Chart window is maximized bool r/o
CHART_IS_MINIMIZED Chart window is minimized bool r/o
CHART_IS_DOCKED The chart window is docked. If set to bool
false, the chart can be dragged outside the
terminal area
CHART_FLOAT_LEFT The left coordinate of the undocked chart int
window relative to the virtual screen
CHART_FLOAT_TOP The top coordinate of the undocked chart int
window relative to the virtual screen
CHART_FLOAT_RIGHT The right coordinate of the undocked chart int
window relative to the virtual screen

© 2000-2025, MetaQuotes Ltd.


325 Constants, Enumerations and Structures

ID Description Property Type

CHART_FLOAT_BOTT The bottom coordinate of the undocked int


OM chart window relative to the virtual screen

For functions ChartS etDouble() and ChartGetDouble()


ENUM_CHART_PROPERTY _DOUBLE

ID Description Property Type

CHART_SHIFT_S IZE The size of the double (from 10 to 50 percents)


zero bar indent
from the right
border in
percents
CHART_FIXED_POS ITION Chart fixed double
position from the
left border in
percent value.
Chart fixed
position is
marked by a small
gray triangle on
the horizontal
time axis. It is
displayed only if
the automatic
chart scrolling to
the right on tick
incoming is
disabled (see
CHART_AUTOS CR
OLL property).
The bar on a
fixed position
remains in the
same place when
zooming in and
out.
CHART_FIXED_M AX Fixed chart double
maximum
CHART_FIXED_MIN Fixed chart double
minimum
CHART_POINTS_PER_BAR S cale in points double
per bar
CHART_PRICE_MIN Chart minimum double r/o modifier - subwindow number
CHART_PRICE_M AX Chart maximum double r/o modifier - subwindow number

© 2000-2025, MetaQuotes Ltd.


326 Constants, Enumerations and Structures

For functions ChartS etS tring() and ChartGetS tring()


ENUM_CHART_PROPERTY _STRING

ID Description Property Type

CHART_COMM ENT Text of a string


comment in a
chart
CHART_EXPERT_NAM E The name of the string r/o
Expert Advisor
running on the
chart with the
specified chart_id
CHART_S CRIPT_NAM E The name of the string r/o
script running on
the chart with the
specified chart_id
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);
}

© 2000-2025, MetaQuotes Ltd.


327 Constants, Enumerations and Structures

See also

Examples of W orking with the Chart

© 2000-2025, MetaQuotes Ltd.


328 Constants, Enumerations and Structures

Positioning Constants
Three identifiers from the ENUM _CHART_POS ITION list are the possible values of the position

parameter for the ChartNavigate() function.


ENUM_CHART_POSITION

ID Description

CHART_BEGIN Chart beginning (the oldest prices)


CHART_CURRENT_POS Current position
CHART_END Chart end (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();
}

© 2000-2025, MetaQuotes Ltd.


329 Constants, Enumerations and Structures

Chart Representation
Price charts can be displayed in three ways :
· as bars ;
· as candlesticks ;
· as a line.
The specific way of displaying the price chart is set by the function
ChartS etInteger(chart_handle,CHART_MODE, chart_mode), where chart_mode is one of the values of
the ENUM _CHART_MODE enumeration.
ENUM_CHART_MODE

ID Description

CHART_BARS Display as a sequence of bars


CHART_CANDLES Display as Japanese candlestick s

CHART_LINE Display as a line drawn by Close prices


To specify the mode of displaying volumes in the price chart the function
ChartS etInteger(chart_handle, CHART_SHOW_VOLUM ES , volume_mode) is used, where volume_mode
is one of values of the ENUM _CHART_VOLUM E_MODE enumeration.

ENUM_CHART_VOLUME_MODE

ID Description

CHART_VOLUM E_HIDE Volumes are not shown


CHART_VOLUM E_TICK Tick volumes
CHART_VOLUM E_REAL Trade volumes
Example:

//--- Get the handle of the current chart


long handle=ChartID();
if(handle>0) // If it succeeded, additionally customize
{
//--- Disable autoscroll
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
//--- Set the indent of the right border of the chart
ChartSetInteger(handle,CHART_SHIFT,true);
//--- Display as candlesticks
ChartSetInteger(handle,CHART_MODE,CHART_CANDLES);
//--- Scroll by 100 bars from the beginning of history
ChartNavigate(handle,CHART_CURRENT_POS,100);
//--- Set the tick volume display mode
ChartSetInteger(handle,CHART_SHOW_VOLUMES,CHART_VOLUME_TICK);

© 2000-2025, MetaQuotes Ltd.


330 Constants, Enumerations and Structures

See also

ChartOpen, ChartID

© 2000-2025, MetaQuotes Ltd.


331 Constants, Enumerations and Structures

Examples of Working with the Chart


This section contains examples of working with chart properties. One or two complete functions are
displayed for each property. These functions allow setting/receiving the value of the property. These
functions can be used " as is " in custom mql5 applications.
The screenshot below demonstrates the graphic panel illustrating how changing of the chart property
changes its appearance. Clicking Next button allows setting the new value of the appropriate property
and view the changes in the chart window.

The panel's source code is located below.

Chart Properties and Sample Functions for Working with Them


· CHART_IS_OBJECT defines if an object is a real chart or a graphic object.

© 2000-2025, MetaQuotes Ltd.


332 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
//| Checks if an object is a chart. If it is a graphic object, |
//| the result is true. If it is a real chart, the result variable |
//| has the value of false. |
//+------------------------------------------------------------------+
bool ChartIsObject(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- get the chart property
if(!ChartGetInteger(chart_ID,CHART_IS_OBJECT,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
//--- return false
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}

· CHART_BRING_TO_TOP shows the chart on top of all others.


//+----------------------------------------------------------------------+
//| Sends command to the terminal to display the chart above all others |
//+----------------------------------------------------------------------+
bool ChartBringToTop(const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- show the chart on top of all others
if(!ChartSetInteger(chart_ID,CHART_BRING_TO_TOP,0,true))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

© 2000-2025, MetaQuotes Ltd.


333 Constants, Enumerations and Structures

· CHART_MOUSE_SCROLL is a property for scrolling the chart using left mouse button.
//+--------------------------------------------------------------------------+
//| Checks if scrolling of chart using left mouse button is enabled |
//+--------------------------------------------------------------------------+
bool ChartMouseScrollGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_MOUSE_SCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------+
//| Enables/disables scrolling of chart using left mouse button |
//+--------------------------------------------------------------------+
bool ChartMouseScrollSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_MOUSE_SCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_EVENT_MOUSE_MOVE is a property of sending messages concerning move events and


mouse clicks to mql5 applications (CHARTEVENT_MOUSE_MOVE).
//+------------------------------------------------------------------+
//| Checks if messages concerning move events and mouse clicks |
//| are sent to all MQL5 applications on the chart |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


334 Constants, Enumerations and Structures

bool ChartEventMouseMoveGet(bool &result,const long chart_ID=0)


{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_EVENT_MOUSE_MOVE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------------------+
//| Enables/disables the mode of sending messages concerning move events and |
//| mouse clicks to MQL5 applications on the chart |
//+------------------------------------------------------------------------------+
bool ChartEventMouseMoveSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_EVENT_MOUSE_MOVE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_EVENT_OBJECT_CREATE is a property of sending messages concerning the event of a


graphic object creation to mql5 applications (CHARTEVENT_OBJECT_CREATE).
//+---------------------------------------------------------------------+
//| Checks if messages concerning the event of a graphic |
//| object creation are sent to all MQL5 applications on the chart |
//+---------------------------------------------------------------------+
bool ChartEventObjectCreateGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;

© 2000-2025, MetaQuotes Ltd.


335 Constants, Enumerations and Structures

//--- reset the error value


ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_EVENT_OBJECT_CREATE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| Enables/disables the mode of sending messages concerning the event of a |
//| graphic object creation to all mql5 applications on the chart |
//+--------------------------------------------------------------------------+
bool ChartEventObjectCreateSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_EVENT_OBJECT_CREATE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_EVENT_OBJECT_DELETE is a property of sending messages concerning the event of a


graphic object deletion to mql5 applications (CHARTEVENT_OBJECT_DELETE).
//+---------------------------------------------------------------------+
//| Checks if messages concerning the event of a graphic object |
//| deletion are sent to all mql5 applications on the chart |
//+---------------------------------------------------------------------+
bool ChartEventObjectDeleteGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_EVENT_OBJECT_DELETE,0,value))

© 2000-2025, MetaQuotes Ltd.


336 Constants, Enumerations and Structures

{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| Enables/disables the mode of sending messages concerning the event of a |
//| graphic object deletion to all mql5 applications on the chart |
//+--------------------------------------------------------------------------+
bool ChartEventObjectDeleteSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_EVENT_OBJECT_DELETE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_MODE – type of the chart (candlesticks, bars or line).


//+------------------------------------------------------------------+
//| Gets chart display type (candlesticks, bars or line) |
//+------------------------------------------------------------------+
ENUM_CHART_MODE ChartModeGet(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=WRONG_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_MODE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((ENUM_CHART_MODE)result);

© 2000-2025, MetaQuotes Ltd.


337 Constants, Enumerations and Structures

}
//+------------------------------------------------------------------+
//| Sets chart display type (candlesticks, bars or line) |
//+------------------------------------------------------------------+
bool ChartModeSet(const long value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_MODE,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_FOREGROUND is a property of displaying a price chart in the foreground.


//+------------------------------------------------------------------+
//| Checks if a price chart is displayed in the foreground |
//+------------------------------------------------------------------+
bool ChartForegroundGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_FOREGROUND,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of a price chart on the foreground |
//+------------------------------------------------------------------+
bool ChartForegroundSet(const bool value,const long chart_ID=0)
{
//--- reset the error value

© 2000-2025, MetaQuotes Ltd.


338 Constants, Enumerations and Structures

ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_FOREGROUND,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHIFT – mode of shift of the price chart from the right border.
//+-------------------------------------------------------------------+
//| Checks if shifting a price chart from the right border is enabled |
//+-------------------------------------------------------------------+
bool ChartShiftGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHIFT,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+---------------------------------------------------------------------------------+
//| Enables/disables displaying of a price chart with a shift from the right border |
//+---------------------------------------------------------------------------------+
bool ChartShiftSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHIFT,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);

© 2000-2025, MetaQuotes Ltd.


339 Constants, Enumerations and Structures

}
//--- successful execution
return(true);
}

· CHART_AUTOSCROLL – the mode of automatic shift to the right border of the chart.
//+------------------------------------------------------------------+
//| Checks if automatic scrolling of a chart to the right |
//| on new ticks arrival is enabled |
//+------------------------------------------------------------------+
bool ChartAutoscrollGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_AUTOSCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables automatic scrolling of a chart to the right |
//| on new ticks arrival |
//+------------------------------------------------------------------+
bool ChartAutoscrollSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_AUTOSCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

© 2000-2025, MetaQuotes Ltd.


340 Constants, Enumerations and Structures

· CHART_SCALE – chart scale property.


//+------------------------------------------------------------------+
//| Gets chart scale (from 0 to 5) |
//+------------------------------------------------------------------+
int ChartScaleGet(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
//+------------------------------------------------------------------+
//| Sets chart scale (from 0 to 5) |
//+------------------------------------------------------------------+
bool ChartScaleSet(const long value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SCALEFI X – the mode of fixed chart scale.


//+------------------------------------------------------------------+
//| Checks if the fixed scale mode is enabled |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


341 Constants, Enumerations and Structures

bool ChartScaleFixGet(bool &result,const long chart_ID=0)


{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALEFIX,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables the fixed scale mode |
//+------------------------------------------------------------------+
bool ChartScaleFixSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALEFIX,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SCALEFI X _ 11 – 1:1 chart scale mode.


//+------------------------------------------------------------------+
//| Checks if the "1:1" scale is enabled |
//+------------------------------------------------------------------+
bool ChartScaleFix11Get(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value

© 2000-2025, MetaQuotes Ltd.


342 Constants, Enumerations and Structures

if(!ChartGetInteger(chart_ID,CHART_SCALEFIX_11,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables the "1:1" scale mode |
//+------------------------------------------------------------------+
bool ChartScaleFix11Set(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALEFIX_11,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SCALE_PT_PER_BAR – the mode of specifying the chart scale in points per bar.
//+------------------------------------------------------------------+
//| Checks if the "points per bar" chart scaling mode is enabled |
//+------------------------------------------------------------------+
bool ChartScalePerBarGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALE_PT_PER_BAR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory

© 2000-2025, MetaQuotes Ltd.


343 Constants, Enumerations and Structures

result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables the "points per bar" chart scaling mode |
//+------------------------------------------------------------------+
bool ChartScalePerBarSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALE_PT_PER_BAR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_OHLC – the property of displaying OH LC values in the upper left corner.


//+----------------------------------------------------------------------------------+
//| Checks if displaying of OHLC values in the upper left corner of chart is enabled |
//+----------------------------------------------------------------------------------+
bool ChartShowOHLCGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_OHLC,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------------------+
//| Enables/disables displaying of OHLC values in the upper left corner of chart |
//+------------------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


344 Constants, Enumerations and Structures

bool ChartShowOHLCSet(const bool value,const long chart_ID=0)


{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_OHLC,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_BID_LINE – the property of displaying Bid value as a horizontal line on the chart.
//+------------------------------------------------------------------+
//| Checks if displaying of Bid line on chart is enabled |
//+------------------------------------------------------------------+
bool ChartShowBidLineGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_BID_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of Bid line on chart |
//+------------------------------------------------------------------+
bool ChartShowBidLineSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_BID_LINE,0,value))
{

© 2000-2025, MetaQuotes Ltd.


345 Constants, Enumerations and Structures

//--- display the error message in Experts journal


Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_ASK_LINE – the property of displaying As k value as a horizontal line on a chart.


//+------------------------------------------------------------------+
//| Checks if displaying of Ask line on chart is enabled |
//+------------------------------------------------------------------+
bool ChartShowAskLineGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_ASK_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of Ask line on chart |
//+------------------------------------------------------------------+
bool ChartShowAskLineSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_ASK_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

© 2000-2025, MetaQuotes Ltd.


346 Constants, Enumerations and Structures

· CHART_SHOW_LAST_LINE – the property of displaying Last value as a horizontal line on a chart.


//+-----------------------------------------------------------------------------+
//| Checks if displaying of line for the last performed deal's price is enabled |
//+-----------------------------------------------------------------------------+
bool ChartShowLastLineGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_LAST_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Enables/disables displaying of line for the last performed deal's price |
//+-------------------------------------------------------------------------+
bool ChartShowLastLineSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_LAST_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_PERIOD_SEP – the property of displaying vertical separators between adjacent


periods.
//+---------------------------------------------------------------------------------+
//| Checks if displaying of vertical separators between adjacent periods is enabled |

© 2000-2025, MetaQuotes Ltd.


347 Constants, Enumerations and Structures

//+---------------------------------------------------------------------------------+
bool ChartShowPeriodSeparatorGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_PERIOD_SEP,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+-----------------------------------------------------------------------------+
//| Enables/disables displaying of vertical separators between adjacent periods |
//+-----------------------------------------------------------------------------+
bool ChartShowPeriodSepapatorSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_PERIOD_SEP,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_ GRID – the property of displaying the chart grid.


//+------------------------------------------------------------------+
//| Checks if the chart grid is displayed |
//+------------------------------------------------------------------+
bool ChartShowGridGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


348 Constants, Enumerations and Structures

//--- receive the property value


if(!ChartGetInteger(chart_ID,CHART_SHOW_GRID,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of grid on chart |
//+------------------------------------------------------------------+
bool ChartShowGridSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_GRID,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_VOLUMES – the property of displaying the volumes on a chart.


//+------------------------------------------------------------------+
//| Checks if volumes are displayed on a chart |
//| The flag indicates the volumes showing mode |
//+------------------------------------------------------------------+
ENUM_CHART_VOLUME_MODE ChartShowVolumesGet(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=WRONG_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_VOLUMES,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}

© 2000-2025, MetaQuotes Ltd.


349 Constants, Enumerations and Structures

//--- return the value of the chart property


return((ENUM_CHART_VOLUME_MODE)result);
}
//+------------------------------------------------------------------+
//| Sets mode of displaying volumes on chart |
//+------------------------------------------------------------------+
bool ChartShowVolumesSet(const long value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_VOLUMES,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_OBJECT_DESCR – the property of graphical object pop-up descriptions.


//+-------------------------------------------------------------------+
//| Checks if pop-up descriptions of graphical objects are displayed |
//| when hovering mouse over them |
//+-------------------------------------------------------------------+
bool ChartShowObjectDescriptionGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_OBJECT_DESCR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


350 Constants, Enumerations and Structures

//| Enables/disables displaying of pop-up descriptions of graphical objects |


//| when hovering mouse over them |
//+-------------------------------------------------------------------------+
bool ChartShowObjectDescriptionSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_OBJECT_DESCR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_VISIBLE_BARS defines the number of bars on a chart that are available for display.
//+----------------------------------------------------------------------+
//| Gets the number of bars that are displayed (visible) in chart window |
//+----------------------------------------------------------------------+
int ChartVisibleBars(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_VISIBLE_BARS,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}

· CHART_WINDOWS_TOTAL defines the total number of chart windows including indicator


subwindows.
//+-----------------------------------------------------------------------+
//| Gets the total number of chart windows including indicator subwindows |
//+-----------------------------------------------------------------------+
int ChartWindowsTotal(const long chart_ID=0)
{

© 2000-2025, MetaQuotes Ltd.


351 Constants, Enumerations and Structures

//--- prepare the variable to get the property value


long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOWS_TOTAL,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}

· CHART_WINDOW_IS_VISIBLE defines the subwindow's visibility.


//+------------------------------------------------------------------+
//| Checks if the current chart window or subwindow is visible |
//+------------------------------------------------------------------+
bool ChartWindowsIsVisible(bool &result,const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_IS_VISIBLE,sub_window,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}

· CHART_WINDOW_ HANDLE returns the chart handle.


//+------------------------------------------------------------------+
//| Gets the chart handle |
//+------------------------------------------------------------------+
int ChartWindowsHandle(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;

© 2000-2025, MetaQuotes Ltd.


352 Constants, Enumerations and Structures

//--- reset the error value


ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_HANDLE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}

· CHART_WINDOW_ Y DISTANCE defines the distance in pixels between the upper frame of the
indicator subwindow and the upper frame of the chart's main window.
//+------------------------------------------------------------------+
//| Gets the distance in pixels between the upper border of |
//| subwindow and the upper border of chart's main window |
//+------------------------------------------------------------------+
int ChartWindowsYDistance(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_YDISTANCE,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}

· CHART_FIRST_VISIBLE_BAR returns the number of the first visible bar on the chart (bar indexing
corresponds to the time series).
//+------------------------------------------------------------------------------+
//| Gets the index of the first visible bar on chart. |
//| Indexing is performed like in timeseries: latest bars have smallest indices. |
//+------------------------------------------------------------------------------+
int ChartFirstVisibleBar(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value

© 2000-2025, MetaQuotes Ltd.


353 Constants, Enumerations and Structures

ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_FIRST_VISIBLE_BAR,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}

· CHART_WIDTH_IN_BARS returns the chart width in bars.


//+------------------------------------------------------------------+
//| Gets the width of chart (in bars) |
//+------------------------------------------------------------------+
int ChartWidthInBars(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WIDTH_IN_BARS,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}

· CHART_WIDTH_IN_PI X ELS returns the chart width in pixels.


//+------------------------------------------------------------------+
//| Gets the width of chart (in pixels) |
//+------------------------------------------------------------------+
int ChartWidthInPixels(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WIDTH_IN_PIXELS,0,result))
{
//--- display the error message in Experts journal

© 2000-2025, MetaQuotes Ltd.


354 Constants, Enumerations and Structures

Print(__FUNCTION__+", Error Code = ",GetLastError());


}
//--- return the value of the chart property
return((int)result);
}

· CHART_ HEI GHT_IN_PI X ELS – chart height property in pixels.


//+------------------------------------------------------------------+
//| Gets the height of chart (in pixels) |
//+------------------------------------------------------------------+
int ChartHeightInPixelsGet(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_HEIGHT_IN_PIXELS,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
//+------------------------------------------------------------------+
//| Sets the height of chart (in pixels) |
//+------------------------------------------------------------------+
bool ChartHeightInPixelsSet(const int value,const long chart_ID=0,const int sub_window=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_HEIGHT_IN_PIXELS,sub_window,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_BACKGROUND - chart background color.


//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


355 Constants, Enumerations and Structures

//| Gets the background color of chart |


//+------------------------------------------------------------------+
color ChartBackColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive chart background color
if(!ChartGetInteger(chart_ID,CHART_COLOR_BACKGROUND,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the background color of chart |
//+------------------------------------------------------------------+
bool ChartBackColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the chart background color
if(!ChartSetInteger(chart_ID,CHART_COLOR_BACKGROUND,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_FOREGROUND – color of axes, scale and OH LC line.


//+------------------------------------------------------------------+
//| Gets the color of axes, scale and OHLC line |
//+------------------------------------------------------------------+
color ChartForeColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of axes, scale and OHLC line
if(!ChartGetInteger(chart_ID,CHART_COLOR_FOREGROUND,0,result))

© 2000-2025, MetaQuotes Ltd.


356 Constants, Enumerations and Structures

{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of axes, scale and OHLC line |
//+------------------------------------------------------------------+
bool ChartForeColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of axes, scale and OHLC line
if(!ChartSetInteger(chart_ID,CHART_COLOR_FOREGROUND,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_ GRID – chart grid color.


//+------------------------------------------------------------------+
//| Gets the color of chart grid |
//+------------------------------------------------------------------+
color ChartGridColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive chart grid color
if(!ChartGetInteger(chart_ID,CHART_COLOR_GRID,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of chart grid |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


357 Constants, Enumerations and Structures

bool ChartGridColorSet(const color clr,const long chart_ID=0)


{
//--- reset the error value
ResetLastError();
//--- set chart grid color
if(!ChartSetInteger(chart_ID,CHART_COLOR_GRID,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_VOLUME - color of volumes and position opening levels.


//+------------------------------------------------------------------+
//| Gets the color of volumes and market entry levels |
//+------------------------------------------------------------------+
color ChartVolumeColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive color of volumes and market entry levels
if(!ChartGetInteger(chart_ID,CHART_COLOR_VOLUME,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of volumes and market entry levels |
//+------------------------------------------------------------------+
bool ChartVolumeColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set color of volumes and market entry levels
if(!ChartSetInteger(chart_ID,CHART_COLOR_VOLUME,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);

© 2000-2025, MetaQuotes Ltd.


358 Constants, Enumerations and Structures

}
//--- successful execution
return(true);
}

· CHART_COLOR_CHART_UP – color of up bar, its shadow and border of a bullish candlestick's body.
//+-----------------------------------------------------------------------------+
//| Gets the color of up bar, shadow and border of a bullish candlestick's body |
//+-----------------------------------------------------------------------------+
color ChartUpColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of up bar, its shadow and border of bullish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CHART_UP,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of up bar, shadow and border of a bullish candlestick's body |
//+------------------------------------------------------------------+
bool ChartUpColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of up bar, its shadow and border of body of a bullish candlestick
if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_UP,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_CHART_DOWN – color of down bar, its shadow and border of bearish candlestick's
body.
//+-------------------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


359 Constants, Enumerations and Structures

//| Gets the color of down bar, shadow and border of a bearish candlestick's body |
//+-------------------------------------------------------------------------------+
color ChartDownColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of down bar, its shadow and border of bearish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CHART_DOWN,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+-------------------------------------------------------------------------------+
//| Sets the color of down bar, shadow and border of a bearish candlestick's body |
//+-------------------------------------------------------------------------------+
bool ChartDownColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of down bar, its shadow and border of bearish candlestick's body
if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_DOWN,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_CHART_LINE – color of the chart line and Doji candlesticks.


//+------------------------------------------------------------------+
//| Gets the color of chart line and Doji candlesticks |
//+------------------------------------------------------------------+
color ChartLineColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive color of the chart line and Doji candlesticks
if(!ChartGetInteger(chart_ID,CHART_COLOR_CHART_LINE,0,result))

© 2000-2025, MetaQuotes Ltd.


360 Constants, Enumerations and Structures

{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of chart line and Doji candlesticks |
//+------------------------------------------------------------------+
bool ChartLineColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set color of the chart line and Doji candlesticks
if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_LINE,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_CANDLE_BULL – color of bullish candlestick's body.


//+------------------------------------------------------------------+
//| Gets the color of bullish candlestick's body |
//+------------------------------------------------------------------+
color ChartBullColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of bullish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CANDLE_BULL,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of bullish candlestick's body |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


361 Constants, Enumerations and Structures

bool ChartBullColorSet(const color clr,const long chart_ID=0)


{
//--- reset the error value
ResetLastError();
//--- set the color of bullish candlestick's body
if(!ChartSetInteger(chart_ID,CHART_COLOR_CANDLE_BULL,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_CANDLE_BEAR – color of bearish candlestick's body.


//+------------------------------------------------------------------+
//| Gets the color of bearish candlestick's body |
//+------------------------------------------------------------------+
color ChartBearColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of bearish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CANDLE_BEAR,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of bearish candlestick's body |
//+------------------------------------------------------------------+
bool ChartBearColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of bearish candlestick's body
if(!ChartSetInteger(chart_ID,CHART_COLOR_CANDLE_BEAR,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);

© 2000-2025, MetaQuotes Ltd.


362 Constants, Enumerations and Structures

}
//--- successful execution
return(true);
}

· CHART_COLOR_BID – Bid price line color.


//+------------------------------------------------------------------+
//| Gets the color of Bid line |
//+------------------------------------------------------------------+
color ChartBidColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of Bid price line
if(!ChartGetInteger(chart_ID,CHART_COLOR_BID,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of Bid line |
//+------------------------------------------------------------------+
bool ChartBidColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of Bid price line
if(!ChartSetInteger(chart_ID,CHART_COLOR_BID,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_ASK – As k price line color.


//+------------------------------------------------------------------+
//| Gets the color of Ask line |

© 2000-2025, MetaQuotes Ltd.


363 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
color ChartAskColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of Ask price line
if(!ChartGetInteger(chart_ID,CHART_COLOR_ASK,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of Ask line |
//+------------------------------------------------------------------+
bool ChartAskColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of Ask price line
if(!ChartSetInteger(chart_ID,CHART_COLOR_ASK,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_LAST – color of the last performed deal's price line (Last).


//+------------------------------------------------------------------+
//| Gets the color of the last performed deal's price line |
//+------------------------------------------------------------------+
color ChartLastColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive color of the last performed deal's price line (Last)
if(!ChartGetInteger(chart_ID,CHART_COLOR_LAST,0,result))
{

© 2000-2025, MetaQuotes Ltd.


364 Constants, Enumerations and Structures

//--- display the error message in Experts journal


Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of the last performed deal's price line |
//+------------------------------------------------------------------+
bool ChartLastColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set color of the last performed deal's price line (Last)
if(!ChartSetInteger(chart_ID,CHART_COLOR_LAST,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_COLOR_STOP_LEVEL – stop order level color (S top Loss and Take Profit).
//+------------------------------------------------------------------+
//| Gets the color of Stop Loss and Take Profit levels |
//+------------------------------------------------------------------+
color ChartStopLevelColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of stop order levels (Stop Loss and Take Profit)
if(!ChartGetInteger(chart_ID,CHART_COLOR_STOP_LEVEL,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| Sets the color of Stop Loss and Take Profit levels |
//+------------------------------------------------------------------+
bool ChartStopLevelColorSet(const color clr,const long chart_ID=0)

© 2000-2025, MetaQuotes Ltd.


365 Constants, Enumerations and Structures

{
//--- reset the error value
ResetLastError();
//--- set the color of stop order levels (Stop Loss and Take Profit)
if(!ChartSetInteger(chart_ID,CHART_COLOR_STOP_LEVEL,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_TRADE_LEVELS – property of displaying trade levels on the chart (levels of open


positions, S top Loss, Take Profit and pending orders).
//+------------------------------------------------------------------+
//| Checks if trading levels are displayed on chart |
//+------------------------------------------------------------------+
bool ChartShowTradeLevelsGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of trading levels |
//+------------------------------------------------------------------+
bool ChartShowTradeLevelsSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_TRADE_LEVELS,0,value))
{

© 2000-2025, MetaQuotes Ltd.


366 Constants, Enumerations and Structures

//--- display the error message in Experts journal


Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_DRAG_TRADE_LEVELS – property of enabling the ability to drag trading levels on a chart


using mouse.
//+----------------------------------------------------------------------+
//| Checks if dragging of trading levels on chart using mouse is allowed |
//+----------------------------------------------------------------------+
bool ChartDragTradeLevelsGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_DRAG_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables dragging of trading levels on chart using mouse |
//+------------------------------------------------------------------+
bool ChartDragTradeLevelsSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_DRAG_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);

© 2000-2025, MetaQuotes Ltd.


367 Constants, Enumerations and Structures

· CHART_SHOW_DATE_SCALE – property of displaying the time scale on a chart.


//+------------------------------------------------------------------+
//| Checks if the time scale is displayed on chart |
//+------------------------------------------------------------------+
bool ChartShowDateScaleGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_DATE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of the time scale on chart |
//+------------------------------------------------------------------+
bool ChartShowDateScaleSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_DATE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_PRICE_SCALE – property of displaying the price scale on a chart.


//+------------------------------------------------------------------+
//| Checks if the price scale is displayed on chart |

© 2000-2025, MetaQuotes Ltd.


368 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
bool ChartShowPriceScaleGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_PRICE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of the price scale on chart |
//+------------------------------------------------------------------+
bool ChartShowPriceScaleSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_PRICE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHOW_ONE_CLICK – property of displaying the " One click trading " panel on a chart.
//+------------------------------------------------------------------+
//| Checks if the "One click trading" panel is displayed on chart |
//+------------------------------------------------------------------+
bool ChartShowOneClickPanelGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


369 Constants, Enumerations and Structures

//--- receive the property value


if(!ChartGetInteger(chart_ID,CHART_SHOW_ONE_CLICK,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Enables/disables displaying of the "One click trading" panel |
//| on chart |
//+------------------------------------------------------------------+
bool ChartShowOneClickPanelSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_ONE_CLICK,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_SHIFT_SI ZE – shift size of the zero bar from the right border in percentage values.
//+-----------------------------------------------------------------+
//| Gets the size of shifting of the zero bar from the right border |
//| of the chart in percentage values (from 10% up to 50%) |
//+-----------------------------------------------------------------+
double ChartShiftSizeGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_SHIFT_SIZE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());

© 2000-2025, MetaQuotes Ltd.


370 Constants, Enumerations and Structures

}
//--- return the value of the chart property
return(result);
}
//+-----------------------------------------------------------------------------+
//| Gets the size of shifting of the zero bar from the right border |
//| of the chart in percentage values (from 10% up to 50%). |
//| To enable the shift mode, CHART_SHIFT property value should be set to true. |
//+-----------------------------------------------------------------------------+
bool ChartShiftSizeSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_SHIFT_SIZE,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_FI X ED_POSITION – chart fixed position from the left border in percentage value.
//+----------------------------------------------------------------------------------------+
//| Gets the location of chart's fixed position from the left border (in percentage value) |
//+----------------------------------------------------------------------------------------+
double ChartFixedPositionGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_FIXED_POSITION,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+-----------------------------------------------------------------------------------------+
//| Gets the location of chart's fixed position from the left border (in percentage value). |
//| To view the location of chart's fixed position, the value of CHART_AUTOSCROLL property |
//| should be set to false. |

© 2000-2025, MetaQuotes Ltd.


371 Constants, Enumerations and Structures

//+-----------------------------------------------------------------------------------------+
bool ChartFixedPositionSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_FIXED_POSITION,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_FI X ED_MAX – property of the chart's fixed maximum.


//+------------------------------------------------------------------+
//| Gets the value of chart's fixed maximum |
//+------------------------------------------------------------------+
double ChartFixedMaxGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_FIXED_MAX,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+------------------------------------------------------------------+
//| Sets the value of chart's fixed maximum. |
//| To change the value of the property, CHART_SCALEFIX property |
//| value should be preliminarily set to true. |
//+------------------------------------------------------------------+
bool ChartFixedMaxSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_FIXED_MAX,value))
{

© 2000-2025, MetaQuotes Ltd.


372 Constants, Enumerations and Structures

//--- display the error message in Experts journal


Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_FI X ED_MIN – property of the chart's fixed minimum.


//+------------------------------------------------------------------+
//| Gets the value of chart's fixed minimum |
//+------------------------------------------------------------------+
double ChartFixedMinGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_FIXED_MIN,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+------------------------------------------------------------------+
//| Sets the value of chart's fixed minimum. |
//| To change the value of the property, CHART_SCALEFIX property |
//| value should be preliminarily set to true. |
//+------------------------------------------------------------------+
bool ChartFixedMinSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_FIXED_MIN,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

© 2000-2025, MetaQuotes Ltd.


373 Constants, Enumerations and Structures

· CHART_POINTS_PER_BAR – value of scale in points per bar.


//+------------------------------------------------------------------+
//| Gets the value of chart scale in points per bar |
//+------------------------------------------------------------------+
double ChartPointsPerBarGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_POINTS_PER_BAR,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+----------------------------------------------------------------------+
//| Sets the value of chart scale in points per bar. |
//| To view the result of this property's value change, the value of |
//| CHART_SCALE_PT_PER_BAR property should be preliminarily set to true. |
//+----------------------------------------------------------------------+
bool ChartPointsPerBarSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_POINTS_PER_BAR,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_PRICE_MIN returns the value of the chart minimum.


//+----------------------------------------------------------------------+
//| Gets the value of chart minimum in the main window or in a subwindow |
//+----------------------------------------------------------------------+
double ChartPriceMin(const long chart_ID=0,const int sub_window=0)

© 2000-2025, MetaQuotes Ltd.


374 Constants, Enumerations and Structures

{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_PRICE_MIN,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}

· CHART_PRICE_MAX returns the value of the chart maximum.


//+----------------------------------------------------------------------+
//| Gets the value of chart maximum in the main window or in a subwindow |
//+----------------------------------------------------------------------+
double ChartPriceMax(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_PRICE_MAX,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}

· CHART_COMMENT – comment on the chart.


//+------------------------------------------------------------------+
//| Gets comment in the upper left corner of chart |
//+------------------------------------------------------------------+
bool ChartCommentGet(string &result,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetString(chart_ID,CHART_COMMENT,result))

© 2000-2025, MetaQuotes Ltd.


375 Constants, Enumerations and Structures

{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Gets comment in the upper left corner of chart |
//+------------------------------------------------------------------+
bool ChartCommentSet(const string str,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetString(chart_ID,CHART_COMMENT,str))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

· CHART_IS_MAX IMI ZED - chart window is maximized.


//+------------------------------------------------------------------+
//| Defines if the current chart window is maximized |
//+------------------------------------------------------------------+
bool ChartWindowsIsMaximized(bool &result,const long chart_ID=0)
{
//--- prepare the variable for receiving the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_IS_MAXIMIZED))
{
//--- display an error message in the Experts log
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the chart property value in the variable
result=value;
//--- successful execution
return(true);
}

© 2000-2025, MetaQuotes Ltd.


376 Constants, Enumerations and Structures

· CHART_IS_MINIMI ZED – chart window is minimized.


//+------------------------------------------------------------------+
//| Defines if the current chart window is minimized |
//+------------------------------------------------------------------+
bool ChartWindowsIsMinimized(bool &result,const long chart_ID=0)
{
//--- prepare the variable for receiving the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_IS_MINIMIZED))
{
//--- display an error message in the Experts log
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the chart property value in the variable
result=value;
//--- successful execution
return(true);
}

Panel for chart properties

//--- connect the library of control elements


#include <ChartObjects\ChartObjectsTxtControls.mqh>
//--- predefined constants
#define X_PROPERTY_NAME_1 10 // x coordinate of the property name in the first column
#define X_PROPERTY_VALUE_1 225 // x coordinate of the property value in the first column
#define X_PROPERTY_NAME_2 345 // x coordinate of the property name in the second and third colum
#define X_PROPERTY_VALUE_2 550 // x coordinate of the property value in the second and third colu
#define X_BUTTON_1 285 // x coordinate of the button in the first column
#define X_BUTTON_2 700 // x coordinate of the button in the second column
#define Y_PROPERTY_1 30 // y coordinate of the beginning of the first and second column
#define Y_PROPERTY_2 286 // y coordinate of the beginning of the third column
#define Y_DISTANCE 16 // y axial distance between the lines
#define LAST_PROPERTY_NUMBER 111 // number of the last graphical property
//--- input parameters
input color InpFirstColor=clrDodgerBlue; // Color of odd lines
input color InpSecondColor=clrGoldenrod; // Color of even lines
//--- variables and arrays
CChartObjectLabel ExtLabelsName[]; // labels for displaying property names
CChartObjectLabel ExtLabelsValue[]; // labels for displaying property values
CChartObjectButton ExtButtons[]; // buttons
int ExtNumbers[]; // property indices
string ExtNames[]; // property names
uchar ExtDataTypes[]; // property data types (integer, double, string)
uint ExtGroupTypes[]; // array that stores the data on belonging of properties to on
uchar ExtDrawTypes[]; // array that stores the data on the type of property display

© 2000-2025, MetaQuotes Ltd.


377 Constants, Enumerations and Structures

double ExtMaxValue[]; // maximum property values that are possible when working with
double ExtMinValue[]; // minimum property values that are possible when working with
double ExtStep[]; // steps for changing properties
int ExtCount; // total number of all properties
color ExtColors[2]; // array of colors for displaying lines
string ExtComments[2]; // array of comments (for CHART_COMMENT property)
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- display a comment on the chart
Comment("SomeComment");
//--- store colors in the array to be able to switch between them later
ExtColors[0]=InpFirstColor;
ExtColors[1]=InpSecondColor;
//--- store comments in the array to be able to switch between them later
ExtComments[0]="FirstComment";
ExtComments[1]="SecondComment";
//--- prepare and display the control panel for managing chart properties
if(!PrepareControls())
return(INIT_FAILED);
//--- successful execution
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Deinitialization function of the expert |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- remove the comment on the chart
Comment("");
}
//+------------------------------------------------------------------+
//| Handler of a chart event |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- check the event of clicking the chart object
if(id==CHARTEVENT_OBJECT_CLICK)
{
//--- divide the object name by separator
string obj_name[];
StringSplit(sparam,'_',obj_name);
//--- check if the object is a button
if(obj_name[0]=="Button")

© 2000-2025, MetaQuotes Ltd.


378 Constants, Enumerations and Structures

{
//--- receive button index
int index=(int)StringToInteger(obj_name[1]);
//--- unpress the button
ExtButtons[index].State(false);
//--- set the new value of the property depending on its type
if(ExtDataTypes[index]=='I')
ChangeIntegerProperty(index);
if(ExtDataTypes[index]=='D')
ChangeDoubleProperty(index);
if(ExtDataTypes[index]=='S')
ChangeStringProperty(index);
}
}
//--- re-draw property values
RedrawProperties();
ChartRedraw();
}
//+------------------------------------------------------------------+
//| Changes an integer property of chart |
//+------------------------------------------------------------------+
void ChangeIntegerProperty(const int index)
{
//--- receive the current property value
long value=ChartGetInteger(0,(ENUM_CHART_PROPERTY_INTEGER)ExtNumbers[index]);
//--- define the following property value
switch(ExtDrawTypes[index])
{
case 'C':
value=GetNextColor((color)value);
break;
default:
value=(long)GetNextValue((double)value,index);
break;
}
//--- set the new property value
ChartSetInteger(0,(ENUM_CHART_PROPERTY_INTEGER)ExtNumbers[index],0,value);
}
//+------------------------------------------------------------------+
//| Changes a double property of chart |
//+------------------------------------------------------------------+
void ChangeDoubleProperty(const int index)
{
//--- receive the current property value
double value=ChartGetDouble(0,(ENUM_CHART_PROPERTY_DOUBLE)ExtNumbers[index]);
//--- define the following property value
value=GetNextValue(value,index);
//--- set the new property value
ChartSetDouble(0,(ENUM_CHART_PROPERTY_DOUBLE)ExtNumbers[index],value);

© 2000-2025, MetaQuotes Ltd.


379 Constants, Enumerations and Structures

}
//+------------------------------------------------------------------+
//| Changes a string property of chart |
//+------------------------------------------------------------------+
void ChangeStringProperty(const int index)
{
//--- static variable for switching inside ExtComments array
static uint comment_index=1;
//--- change index for receiving another comment
comment_index=1-comment_index;
//--- set the new property value
ChartSetString(0,(ENUM_CHART_PROPERTY_STRING)ExtNumbers[index],ExtComments[comment_index]);
}
//+------------------------------------------------------------------+
//| Gets the next property value |
//+------------------------------------------------------------------+
double GetNextValue(const double value,const int index)
{
if(value+ExtStep[index]<=ExtMaxValue[index])
return(value+ExtStep[index]);
else
return(ExtMinValue[index]);
}
//+------------------------------------------------------------------+
//| Gets the next color for color type property |
//+------------------------------------------------------------------+
color GetNextColor(const color clr)
{
//--- return the following color value
switch(clr)
{
case clrWhite: return(clrRed);
case clrRed: return(clrGreen);
case clrGreen: return(clrBlue);
case clrBlue: return(clrBlack);
default: return(clrWhite);
}
}
//+------------------------------------------------------------------+
//| Re-draws property values |
//+------------------------------------------------------------------+
void RedrawProperties(void)
{
//--- property value text
string text;
long value;
//--- loop of the number of properties
for(int i=0;i<ExtCount;i++)
{

© 2000-2025, MetaQuotes Ltd.


380 Constants, Enumerations and Structures

text="";
switch(ExtDataTypes[i])
{
case 'I':
//--- receive the current property value
if(!ChartGetInteger(0,(ENUM_CHART_PROPERTY_INTEGER)ExtNumbers[i],0,value))
break;
//--- integer property text
switch(ExtDrawTypes[i])
{
//--- color property
case 'C':
text=(string)((color)value);
break;
//--- boolean property
case 'B':
text=(string)((bool)value);
break;
//--- ENUM_CHART_MODE enumeration property
case 'M':
text=EnumToString((ENUM_CHART_MODE)value);
break;
//--- ENUM_CHART_VOLUME_MODE enumeration property
case 'V':
text=EnumToString((ENUM_CHART_VOLUME_MODE)value);
break;
//--- int type number
default:
text=IntegerToString(value);
break;
}
break;
case 'D':
//--- double property text
text=DoubleToString(ChartGetDouble(0,(ENUM_CHART_PROPERTY_DOUBLE)ExtNumbers[i]),4);
break;
case 'S':
//--- string property text
text=ChartGetString(0,(ENUM_CHART_PROPERTY_STRING)ExtNumbers[i]);
break;
}
//--- display property value
ExtLabelsValue[i].Description(text);
}
}
//+------------------------------------------------------------------+
//| Creates panel for managing chart properties |
//+------------------------------------------------------------------+
bool PrepareControls(void)

© 2000-2025, MetaQuotes Ltd.


381 Constants, Enumerations and Structures

{
//--- allocate memory for arrays with a reserve
MemoryAllocation(LAST_PROPERTY_NUMBER+1);
//--- variables
int i=0; // loop variable
int col_1=0; // number of properties in the first column
int col_2=0; // number of properties in the second column
int col_3=0; // number of properties in the third column
//--- current number of properties - 0
ExtCount=0;
//--- looking for properties in the loop
while(i<=LAST_PROPERTY_NUMBER)
{
//--- store the current number of the property
ExtNumbers[ExtCount]=i;
//--- increase the value of the loop variable
i++;
//--- check if there is a property with such a number
if(CheckNumber(ExtNumbers[ExtCount],ExtNames[ExtCount],ExtDataTypes[ExtCount],ExtGroupTypes[E
{
//--- create control elements for the property
switch(ExtGroupTypes[ExtCount])
{
case 1:
//--- create labels and a button for the property
if(!ShowProperty(ExtCount,0,X_PROPERTY_NAME_1,X_PROPERTY_VALUE_1,X_BUTTON_1,Y_PROPER
return(false);
//--- number of the elements in the first column has increased
col_1++;
break;
case 2:
//--- create labels and a button for the property
if(!ShowProperty(ExtCount,1,X_PROPERTY_NAME_2,X_PROPERTY_VALUE_2,X_BUTTON_2,Y_PROPER
return(false);
//--- number of the elements in the second column has increased
col_2++;
break;
case 3:
//--- create only labels for the property
if(!ShowProperty(ExtCount,2,X_PROPERTY_NAME_2,X_PROPERTY_VALUE_2,0,Y_PROPERTY_2+col_
return(false);
//--- number of the elements in the third column has increased
col_3++;
break;
}
//--- define maximum and minimum property value and step
GetMaxMinStep(ExtNumbers[ExtCount],ExtMaxValue[ExtCount],ExtMinValue[ExtCount],ExtStep[Ext
//--- increase the number of properties
ExtCount++;

© 2000-2025, MetaQuotes Ltd.


382 Constants, Enumerations and Structures

}
}
//--- free the memory not used by arrays
MemoryAllocation(ExtCount);
//--- re-draw property values
RedrawProperties();
ChartRedraw();
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Allocates memory for arrays |
//+------------------------------------------------------------------+
void MemoryAllocation(const int size)
{
ArrayResize(ExtLabelsName,size);
ArrayResize(ExtLabelsValue,size);
ArrayResize(ExtButtons,size);
ArrayResize(ExtNumbers,size);
ArrayResize(ExtNames,size);
ArrayResize(ExtDataTypes,size);
ArrayResize(ExtGroupTypes,size);
ArrayResize(ExtDrawTypes,size);
ArrayResize(ExtMaxValue,size);
ArrayResize(ExtMinValue,size);
ArrayResize(ExtStep,size);
}
//+------------------------------------------------------------------+
//| Checks if the property index belongs to the one of |
//| ENUM_CHART_PROPERTIES enumerations |
//+------------------------------------------------------------------+
bool CheckNumber(const int ind,string &name,uchar &data_type,uint &group_type,uchar &draw_type)
{
//--- check if the property is of integer type
ResetLastError();
name=EnumToString((ENUM_CHART_PROPERTY_INTEGER)ind);
if(_LastError==0)
{
data_type='I'; // property from ENUM_CHART_PROPERTY_INTEGER enumeration
GetTypes(ind,group_type,draw_type); // define property display parameters
return(true);
}
//--- check if the property is of double type
ResetLastError();
name=EnumToString((ENUM_CHART_PROPERTY_DOUBLE)ind);
if(_LastError==0)
{
data_type='D'; // property from ENUM_CHART_PROPERTY_DOUBLE enumeration
GetTypes(ind,group_type,draw_type); // define property display parameters

© 2000-2025, MetaQuotes Ltd.


383 Constants, Enumerations and Structures

return(true);
}
//--- check if the property is of string type
ResetLastError();
name=EnumToString((ENUM_CHART_PROPERTY_STRING)ind);
if(_LastError==0)
{
data_type='S'; // property from ENUM_CHART_PROPERTY_STRING enumeration
GetTypes(ind,group_type,draw_type); // define property display parameters
return(true);
}
//--- property does not belong to any enumeration
return(false);
}
//+------------------------------------------------------------------+
//| Defines the group in which property should be stored, |
//| as well as its display type |
//+------------------------------------------------------------------+
void GetTypes(const int property_number,uint &group_type,uchar &draw_type)
{
//--- check if the property belongs to the third group
//--- third group properties are displayed in the second column starting from CHART_BRING_TO_TOP
if(CheckThirdGroup(property_number,group_type,draw_type))
return;
//--- check if the property belongs to the second group
//--- second group properties are displayed at the beginning of the second column
if(CheckSecondGroup(property_number,group_type,draw_type))
return;
//--- if you find yourself here, the property belongs to the first group (first column)
CheckFirstGroup(property_number,group_type,draw_type);
}
//+----------------------------------------------------------------------+
//| Checks if property belongs to the third group and |
//| defines its display type in case of a positive answer |
//+----------------------------------------------------------------------+
bool CheckThirdGroup(const int property_number,uint &group_type,uchar &draw_type)
{
//--- check if the property belongs to the third group
switch(property_number)
{
//--- boolean properties
case CHART_IS_OBJECT:
case CHART_WINDOW_IS_VISIBLE:
draw_type='B';
break;
//--- integer properties
case CHART_VISIBLE_BARS:
case CHART_WINDOWS_TOTAL:
case CHART_WINDOW_HANDLE:

© 2000-2025, MetaQuotes Ltd.


384 Constants, Enumerations and Structures

case CHART_WINDOW_YDISTANCE:
case CHART_FIRST_VISIBLE_BAR:
case CHART_WIDTH_IN_BARS:
case CHART_WIDTH_IN_PIXELS:
draw_type='I';
break;
//--- double properties
case CHART_PRICE_MIN:
case CHART_PRICE_MAX:
draw_type='D';
break;
//--- in fact, this property is a command of displaying the chart on top of all the others
//--- there is no need to apply this panel, as the window will always be
//--- on top of other ones before we use it
case CHART_BRING_TO_TOP:
draw_type=' ';
break;
//--- property does not belong to the third group
default:
return(false);
}
//--- property belongs to the third group
group_type=3;
return(true);
}
//+----------------------------------------------------------------------+
//| Checks if property belongs to the second group and |
//| defines its display type in case of a positive answer |
//+----------------------------------------------------------------------+
bool CheckSecondGroup(const int property_number,uint &group_type,uchar &draw_type)
{
//--- check if the property belongs to the second group
switch(property_number)
{
//--- ENUM_CHART_MODE type property
case CHART_MODE:
draw_type='M';
break;
//--- ENUM_CHART_VOLUME_MODE type property
case CHART_SHOW_VOLUMES:
draw_type='V';
break;
//--- string property
case CHART_COMMENT:
draw_type='S';
break;
//--- color property
case CHART_COLOR_BACKGROUND:
case CHART_COLOR_FOREGROUND:

© 2000-2025, MetaQuotes Ltd.


385 Constants, Enumerations and Structures

case CHART_COLOR_GRID:
case CHART_COLOR_VOLUME:
case CHART_COLOR_CHART_UP:
case CHART_COLOR_CHART_DOWN:
case CHART_COLOR_CHART_LINE:
case CHART_COLOR_CANDLE_BULL:
case CHART_COLOR_CANDLE_BEAR:
case CHART_COLOR_BID:
case CHART_COLOR_ASK:
case CHART_COLOR_LAST:
case CHART_COLOR_STOP_LEVEL:
draw_type='C';
break;
//--- property does not belong to the second group
default:
return(false);
}
//--- property belongs to the second group
group_type=2;
return(true);
}
//+-----------------------------------------------------------------------+
//| Called only if it is already known that property does not belong |
//| to the second and third property groups |
//+-----------------------------------------------------------------------+
void CheckFirstGroup(const int property_number,uint &group_type,uchar &draw_type)
{
//--- the property belongs to the first group
group_type=1;
//--- define property display type
switch(property_number)
{
//--- integer properties
case CHART_SCALE:
case CHART_HEIGHT_IN_PIXELS:
draw_type='I';
return;
//--- double properties
case CHART_SHIFT_SIZE:
case CHART_FIXED_POSITION:
case CHART_FIXED_MAX:
case CHART_FIXED_MIN:
case CHART_POINTS_PER_BAR:
draw_type='D';
return;
//--- only boolean properties have remained
default:
draw_type='B';
return;

© 2000-2025, MetaQuotes Ltd.


386 Constants, Enumerations and Structures

}
}
//+------------------------------------------------------------------+
//| Creates label and button for property |
//+------------------------------------------------------------------+
bool ShowProperty(const int ind,const int type,const int x1,const int x2,
const int xb,const int y,const bool btn)
{
//--- static array for switching inside ExtColors color array
static uint color_index[3]={1,1,1};
//--- change index for receiving another color
color_index[type]=1-color_index[type];
//--- display labels and a button (if btn=true) for the property
if(!LabelCreate(ExtLabelsName[ind],"name_"+(string)ind,ExtNames[ind],ExtColors[color_index[type]
return(false);
if(!LabelCreate(ExtLabelsValue[ind],"value_"+(string)ind,"",ExtColors[color_index[type]],x2,y))
return(false);
if(btn && !ButtonCreate(ExtButtons[ind],(string)ind,xb,y+1))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Creates label |
//+------------------------------------------------------------------+
bool LabelCreate(CChartObjectLabel &lbl,const string name,const string text,
const color clr,const int x,const int y)
{
if(!lbl.Create(0,"Label_"+name,0,x,y)) return(false);
if(!lbl.Description(text)) return(false);
if(!lbl.FontSize(10)) return(false);
if(!lbl.Color(clr)) return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Creates button |
//+------------------------------------------------------------------+
bool ButtonCreate(CChartObjectButton &btn,const string name,
const int x,const int y)
{
if(!btn.Create(0,"Button_"+name,0,x,y,50,15)) return(false);
if(!btn.Description("Next")) return(false);
if(!btn.FontSize(10)) return(false);
if(!btn.Color(clrBlack)) return(false);
if(!btn.BackColor(clrWhite)) return(false);
if(!btn.BorderColor(clrBlack)) return(false);
//--- successful execution
return(true);

© 2000-2025, MetaQuotes Ltd.


387 Constants, Enumerations and Structures

}
//+------------------------------------------------------------------+
//| Defines maximum and minimum property value and step |
//+------------------------------------------------------------------+
void GetMaxMinStep(const int property_number,double &max,double &min,double &step)
{
double value;
//--- set values depending on the property type
switch(property_number)
{
case CHART_SCALE:
max=5;
min=0;
step=1;
break;
case CHART_MODE:
case CHART_SHOW_VOLUMES:
max=2;
min=0;
step=1;
break;
case CHART_SHIFT_SIZE:
max=50;
min=10;
step=2.5;
break;
case CHART_FIXED_POSITION:
max=90;
min=0;
step=15;
break;
case CHART_POINTS_PER_BAR:
max=19;
min=1;
step=3;
break;
case CHART_FIXED_MAX:
value=ChartGetDouble(0,CHART_FIXED_MAX);
max=value*1.25;
min=value;
step=value/32;
break;
case CHART_FIXED_MIN:
value=ChartGetDouble(0,CHART_FIXED_MIN);
max=value;
min=value*0.75;
step=value/32;
break;
case CHART_HEIGHT_IN_PIXELS:

© 2000-2025, MetaQuotes Ltd.


388 Constants, Enumerations and Structures

max=700;
min=520;
step=30;
break;
//--- default values
default:
max=1;
min=0;
step=1;
}
}

© 2000-2025, MetaQuotes Ltd.


389 Constants, Enumerations and Structures

Object Constants
There are 44 graphical objects that can be created and displayed in the price chart. All constants for
working with objects are divided into 9 groups :
· Object types – Identifiers of graphical objects ;
· Object properties – setting and getting properties of graphical objects ;
· Methods of object binding – constants of object positioning in the chart;
· Binding corner – setting the corner relative to which an object is positioned on chart;
· Visibility of objects – setting timeframes in which an object is visible;
· Levels of Elliott W aves – gradation of waves ;
· Gann objects – trend constants for Gann fan and Gann grid;
· W eb colors – constants of predefined web colors ;
· W ingdings – codes of characters of the W ingdings font.

© 2000-2025, MetaQuotes Ltd.


390 Constants, Enumerations and Structures

Object Types
W hen a graphical object is created using the ObjectCreate() function, it's necessary to specify the type
of object being created, which can be one of the values of the ENUM _OBJECT enumeration. Further
specifications of object properties are possible using functions for working with graphical objects.
ENUM_OBJECT

ID Description

OBJ_VLINE Vertical Line

OBJ_HLINE H orizontal Line

OBJ_TREND Trend Line


OBJ_TRENDBYANGLE Trend Line By Angle
OBJ_CYCLES Cycle Lines
OBJ_ARROWED_LINE Arrowed Line

OBJ_CHANNEL Equidistant Channel

OBJ_S TDDEVCHANNEL S tandard Deviation Channel

OBJ_REGRESS ION Linear Regression Channel


OBJ_PITCHFORK Andrews ’ Pitchfork
OBJ_GANNLINE Gann Line

OBJ_GANNFAN Gann Fan

OBJ_GANNGRID Gann Grid

OBJ_FIBO Fibonacci R etracement

OBJ_FIBOTIM ES Fibonacci Time Zones


OBJ_FIBOFAN Fibonacci Fan

OBJ_FIBOARC Fibonacci Arcs

OBJ_FIBOCHANNEL Fibonacci Channel


OBJ_EXPANS ION Fibonacci Expansion

OBJ_ELLIOTWAVE5 Elliott Motive W ave

OBJ_ELLIOTWAVE3 Elliott Correction W ave

OBJ_RECTANGLE R ectangle

OBJ_TRIANGLE Triangle
OBJ_ELLIPSE Ellipse

OBJ_ARROW_THUM B_UP Thumbs Up


OBJ_ARROW_THUM B_DOWN Thumbs Down

© 2000-2025, MetaQuotes Ltd.


391 Constants, Enumerations and Structures

ID Description

OBJ_ARROW_UP Arrow Up

OBJ_ARROW_DOWN Arrow Down

OBJ_ARROW_S TOP S top S ign

OBJ_ARROW_CHECK Check S ign


OBJ_ARROW_LEFT_PRICE Left Price Label
OBJ_ARROW_RIGHT_PRICE R ight Price Label

OBJ_ARROW_BUY Buy S ign

OBJ_ARROW_SELL S ell S ign

OBJ_ARROW Arrow

OBJ_TEXT Text
OBJ_LABEL Label
OBJ_BUTTON Button

OBJ_CHART Chart
OBJ_BITM AP Bitmap

OBJ_BITM AP_LABEL Bitmap Label

OBJ_EDIT Edit

OBJ_EVENT The "Event" object corresponding to an event in the


economic calendar
OBJ_RECTANGLE_LABEL The "Rectangle label" object for creating and designing
the custom graphical interface.

© 2000-2025, MetaQuotes Ltd.


392 Constants, Enumerations and Structures

OBJ_VLINE
Vertical Line.

Note

W hen drawing a vertical line, it is possible to set the line display mode for all chart windows
(property OBJPROP_RAY).
Example

The following script creates and moves the vertical line on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.
//--- description
#property description "Script draws \"Vertical Line\" graphical object."
#property description "Anchor point date is set in percentage of"
#property description "the chart window width in bars."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="VLine"; // Line name
input int InpDate=25; // Event date, %
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style
input int InpWidth=3; // Line width
input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpRay=true; // Line's continuation down

© 2000-2025, MetaQuotes Ltd.


393 Constants, Enumerations and Structures

input bool InpHidden=true; // Hidden in the object list


input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the vertical line |
//+------------------------------------------------------------------+
bool VLineCreate(const long chart_ID=0, // chart's ID
const string name="VLine", // line name
const int sub_window=0, // subwindow index
datetime time=0, // line time
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray=true, // line's continuation down
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- if the line time is not set, draw it via the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- create a vertical line
if(!ObjectCreate(chart_ID,name,OBJ_VLINE,sub_window,time,0))
{
Print(__FUNCTION__,
": failed to create a vertical line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of displaying the line in the chart subwindows
ObjectSetInteger(chart_ID,name,OBJPROP_RAY,ray);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart

© 2000-2025, MetaQuotes Ltd.


394 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the vertical line |
//+------------------------------------------------------------------+
bool VLineMove(const long chart_ID=0, // chart's ID
const string name="VLine", // line name
datetime time=0) // line time
{
//--- if line time is not set, move the line to the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the vertical line
if(!ObjectMove(chart_ID,name,0,time,0))
{
Print(__FUNCTION__,
": failed to move the vertical line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the vertical line |
//+------------------------------------------------------------------+
bool VLineDelete(const long chart_ID=0, // chart's ID
const string name="VLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete the vertical line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the vertical line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{

© 2000-2025, MetaQuotes Ltd.


395 Constants, Enumerations and Structures

//--- check correctness of the input parameters


if(InpDate<0 || InpDate>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- array for storing the date values to be used
//--- for setting and changing line anchor point's coordinates
datetime date[];
//--- memory allocation
ArrayResize(date,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- define points for drawing the line
int d=InpDate*(bars-1)/100;
//--- create a vertical line
if(!VLineCreate(0,InpName,0,date[d],InpColor,InpStyle,InpWidth,InpBack,
InpSelection,InpRay,InpHidden,InpZOrder))
return;
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line
//--- loop counter
int h_steps=bars/2;
//--- move the line
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!VLineMove(0,InpName,date[d]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.03 seconds of delay
Sleep(30);
}

© 2000-2025, MetaQuotes Ltd.


396 Constants, Enumerations and Structures

//--- 1 second of delay


Sleep(1000);
//--- delete the channel from the chart
VLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


397 Constants, Enumerations and Structures

OBJ_HLINE
H orizontal Line.

Example

The following script creates and moves the horizontal line on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Horizontal Line\" graphical object."
#property description "Anchor point price is set in percentage of the height of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="HLine"; // Line name
input int InpPrice=25; // Line price, %
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style
input int InpWidth=3; // Line width
input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the horizontal line |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


398 Constants, Enumerations and Structures

bool HLineCreate(const long chart_ID=0, // chart's ID


const string name="HLine", // line name
const int sub_window=0, // subwindow index
double price=0, // line price
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- if the price is not set, set it at the current Bid price level
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- create a horizontal line
if(!ObjectCreate(chart_ID,name,OBJ_HLINE,sub_window,0,price))
{
Print(__FUNCTION__,
": failed to create a horizontal line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move horizontal line |
//+------------------------------------------------------------------+
bool HLineMove(const long chart_ID=0, // chart's ID

© 2000-2025, MetaQuotes Ltd.


399 Constants, Enumerations and Structures

const string name="HLine", // line name


double price=0) // line price
{
//--- if the line price is not set, move it to the current Bid price level
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move a horizontal line
if(!ObjectMove(chart_ID,name,0,0,price))
{
Print(__FUNCTION__,
": failed to move the horizontal line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete a horizontal line |
//+------------------------------------------------------------------+
bool HLineDelete(const long chart_ID=0, // chart's ID
const string name="HLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete a horizontal line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a horizontal line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- price array size
int accuracy=1000;

© 2000-2025, MetaQuotes Ltd.


400 Constants, Enumerations and Structures

//--- array for storing the price values to be used


//--- for setting and changing line anchor point's coordinates
double price[];
//--- memory allocation
ArrayResize(price,accuracy);
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int p=InpPrice*(accuracy-1)/100;
//--- create a horizontal line
if(!HLineCreate(0,InpName,0,price[p],InpColor,InpStyle,InpWidth,InpBack,
InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line
//--- loop counter
int v_steps=accuracy/2;
//--- move the line
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!HLineMove(0,InpName,price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete from the chart
HLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);

© 2000-2025, MetaQuotes Ltd.


401 Constants, Enumerations and Structures

//---
}

© 2000-2025, MetaQuotes Ltd.


402 Constants, Enumerations and Structures

OBJ_TREND
Trend Line.

Note

For Trend Line, it is possible to specify the mode of continuation of its display to the right and/or
left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
Example

The following script creates and moves the trend line on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Trend Line\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Trend"; // Line name
input int InpDate1=35; // 1 st point's date, %
input int InpPrice1=60; // 1 st point's price, %
input int InpDate2=65; // 2 nd point's date, %
input int InpPrice2=40; // 2 nd point's price, %
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style

© 2000-2025, MetaQuotes Ltd.


403 Constants, Enumerations and Structures

input int InpWidth=2; // Line width


input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Line's continuation to the left
input bool InpRayRight=false; // Line's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create a trend line by the given coordinates |
//+------------------------------------------------------------------+
bool TrendCreate(const long chart_ID=0, // chart's ID
const string name="TrendLine", // line name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // line's continuation to the left
const bool ray_right=false, // line's continuation to the right
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeTrendEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a trend line by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_TREND,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create a trend line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter

© 2000-2025, MetaQuotes Ltd.


404 Constants, Enumerations and Structures

//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the line's display to the left
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the line's display to the right
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move trend line anchor point |
//+------------------------------------------------------------------+
bool TrendPointChange(const long chart_ID=0, // chart's ID
const string name="TrendLine", // line name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move trend line's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function deletes the trend line from the chart. |
//+------------------------------------------------------------------+
bool TrendDelete(const long chart_ID=0, // chart's ID
const string name="TrendLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete a trend line

© 2000-2025, MetaQuotes Ltd.


405 Constants, Enumerations and Structures

if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a trend line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of trend line's anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeTrendEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, it is equal to the first point's one
if(!price2)
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);

© 2000-2025, MetaQuotes Ltd.


406 Constants, Enumerations and Structures

//--- price array size


int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create a trend line
if(!TrendCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,InpStyle,
InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line's anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!TrendPointChange(0,InpName,0,date[d1],price[p1]))

© 2000-2025, MetaQuotes Ltd.


407 Constants, Enumerations and Structures

return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- move the second anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2<accuracy-1)
p2+=1;
//--- move the point
if(!TrendPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- half a second of delay
Sleep(500);
//--- loop counter
int h_steps=bars/2;
//--- move both anchor points horizontally at the same time
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2>1)
d2-=1;
//--- shift the points
if(!TrendPointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!TrendPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.03 seconds of delay
Sleep(30);
}
//--- 1 second of delay
Sleep(1000);

© 2000-2025, MetaQuotes Ltd.


408 Constants, Enumerations and Structures

//--- delete a trend line


TrendDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


409 Constants, Enumerations and Structures

OBJ_TRENDBYANGLE
Trend Line By Angle.

Note

ForTrend Line By Angle, it is possible to specify the mode of continuation of its display to the right
and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
Both angle and the second anchor point's coordinates can be used to set the slope of the line.
Example

The following script creates and moves the trend line on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Trend Line By Angle\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Trend"; // Line name
input int InpDate1=50; // 1 st point's date, %
input int InpPrice1=75; // 1 st point's price, %
input int InpAngle=0; // Line's slope angle
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style

© 2000-2025, MetaQuotes Ltd.


410 Constants, Enumerations and Structures

input int InpWidth=2; // Line width


input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Line's continuation to the left
input bool InpRayRight=true; // Line's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create a trend line by angle |
//+------------------------------------------------------------------+
bool TrendByAngleCreate(const long chart_ID=0, // chart's ID
const string name="TrendLine", // line name
const int sub_window=0, // subwindow index
datetime time=0, // point time
double price=0, // point price
const double angle=45.0, // slope angle
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // line's continuation to the left
const bool ray_right=true, // line's continuation to the righ
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- create the second point to facilitate dragging the trend line by mouse
datetime time2=0;
double price2=0;
//--- set anchor points' coordinates if they are not set
ChangeTrendEmptyPoints(time,price,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a trend line using 2 points
if(!ObjectCreate(chart_ID,name,OBJ_TRENDBYANGLE,sub_window,time,price,time2,price2))
{
Print(__FUNCTION__,
": failed to create a trend line! Error code = ",GetLastError());
return(false);
}
//--- change trend line's slope angle; when changing the angle, coordinates of the second
//--- point of the line are redefined automatically according to the angle's new value
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);

© 2000-2025, MetaQuotes Ltd.


411 Constants, Enumerations and Structures

//--- display in the foreground (false) or background (true)


ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the line's display to the left
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the line's display to the right
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change trend line anchor point's coordinates |
//+------------------------------------------------------------------+
bool TrendPointChange(const long chart_ID=0, // chart's ID
const string name="TrendLine", // line name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move trend line's anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change trend line's slope angle |
//+------------------------------------------------------------------+
bool TrendAngleChange(const long chart_ID=0, // chart's ID
const string name="TrendLine", // trend line name

© 2000-2025, MetaQuotes Ltd.


412 Constants, Enumerations and Structures

const double angle=45) // trend line's slope angle


{
//--- reset the error value
ResetLastError();
//--- change trend line's slope angle
if(!ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle))
{
Print(__FUNCTION__,
": failed to change the line's slope angle! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the trend line |
//+------------------------------------------------------------------+
bool TrendDelete(const long chart_ID=0, // chart's ID
const string name="TrendLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete a trend line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a trend line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of trend line's anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeTrendEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- set coordinates of the second, auxiliary point
//--- the second point will be 9 bars left and have the same price
datetime second_point_time[10];
CopyTime(Symbol(),Period(),time1,10,second_point_time);

© 2000-2025, MetaQuotes Ltd.


413 Constants, Enumerations and Structures

time2=second_point_time[0];
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int d1=InpDate1*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create a trend line
if(!TrendByAngleCreate(0,InpName,0,date[d1],price[p1],InpAngle,InpColor,InpStyle,
InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}

© 2000-2025, MetaQuotes Ltd.


414 Constants, Enumerations and Structures

//--- redraw the chart and wait for 1 second


ChartRedraw();
Sleep(1000);
//--- now, move and rotate the line
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor point and change the line's slope angle
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!TrendPointChange(0,InpName,date[d1],price[p1]))
return;
if(!TrendAngleChange(0,InpName,18*(i+1)))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete from the chart
TrendDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


415 Constants, Enumerations and Structures

OBJ_CYCLES
Cycle Lines.

Note

The distance between the lines is set by time coordinates of two anchor points of the object.
Example

The following script creates and moves cycle lines on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script creates cycle lines on the chart."
#property description "Anchor point coordinates are set in percentage"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Cycles"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=45; // 1 st point's price, %
input int InpDate2=20; // 2 nd point's date, %
input int InpPrice2=55; // 2 nd point's price, %
input color InpColor=clrRed; // Color of cycle lines
input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Style of cycle lines
input int InpWidth=1; // Width of cycle lines

© 2000-2025, MetaQuotes Ltd.


416 Constants, Enumerations and Structures

input bool InpBack=false; // Background object


input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create cycle lines |
//+------------------------------------------------------------------+
bool CyclesCreate(const long chart_ID=0, // chart's ID
const string name="Cycles", // object name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // color of cycle lines
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of cycle lines
const int width=1, // width of cycle lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeCyclesEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create cycle lines by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_CYCLES,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create cycle lines! Error code = ",GetLastError());
return(false);
}
//--- set color of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set display style of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the lines by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);

© 2000-2025, MetaQuotes Ltd.


417 Constants, Enumerations and Structures

//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool CyclesPointChange(const long chart_ID=0, // chart's ID
const string name="Cycles", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the cycle lines |
//+------------------------------------------------------------------+
bool CyclesDelete(const long chart_ID=0, // chart's ID
const string name="Cycles") // object name
{
//--- reset the error value
ResetLastError();
//--- delete cycle lines
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete cycle lines! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

© 2000-2025, MetaQuotes Ltd.


418 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
//| Check the values of cycle lines' anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeCyclesEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, it is equal to the first point's one
if(!price2)
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of cycle lines' anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);

© 2000-2025, MetaQuotes Ltd.


419 Constants, Enumerations and Structures

//--- fill the array of dates


ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing cycle lines
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create a trend line
if(!CyclesCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int h_steps=bars/5;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!CyclesPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}

© 2000-2025, MetaQuotes Ltd.


420 Constants, Enumerations and Structures

//--- 1 second of delay


Sleep(1000);
//--- loop counter
h_steps=bars/4;
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1<bars-1)
d1+=1;
//--- move the point
if(!CyclesPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
CyclesDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


421 Constants, Enumerations and Structures

OBJ_ARROWED_LINE
Arrowed line.

Example

The following script creates and moves an arrow line on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Arrowed line\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ArrowedLine"; // Line name
input int InpDate1=35; // 1 st point's date, %
input int InpPrice1=60; // 1 st point's price, %
input int InpDate2=65; // 2 nd point's date, %
input int InpPrice2=40; // 2 nd point's price, %
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style
input int InpWidth=2; // Line width
input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click

© 2000-2025, MetaQuotes Ltd.


422 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
//| Create an arrowed line by the given coordinates |
//+------------------------------------------------------------------+
bool ArrowedLineCreate(const long chart_ID=0, // chart's ID
const string name="ArrowedLine", // line name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeArrowedLineEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create an arrowed line by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_ARROWED_LINE,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create an arrowed line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);

© 2000-2025, MetaQuotes Ltd.


423 Constants, Enumerations and Structures

}
//+------------------------------------------------------------------+
//| Move arrowed line's anchor point |
//+------------------------------------------------------------------+
bool ArrowedLinePointChange(const long chart_ID=0, // chart's ID
const string name="ArrowedLine", // line name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the line's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes the arrowed line from the chart |
//+------------------------------------------------------------------+
bool ArrowedLineDelete(const long chart_ID=0, // chart's ID
const string name="ArrowedLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete an arrowed line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to create an arrowed line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor points' values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


424 Constants, Enumerations and Structures

void ChangeArrowedLineEmptyPoints(datetime &time1,double &price1,


datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, it is equal to the first point's one
if(!price2)
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{

© 2000-2025, MetaQuotes Ltd.


425 Constants, Enumerations and Structures

Print("Failed to copy time values! Error code = ",GetLastError());


return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an arrowed line
if(!ArrowedLineCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line's anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the second anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2<accuracy-1)
p2+=1;
//--- move the point
if(!ArrowedLinePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;

© 2000-2025, MetaQuotes Ltd.


426 Constants, Enumerations and Structures

//--- move the point


if(!ArrowedLinePointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- half a second of delay
Sleep(500);
//--- loop counter
int h_steps=bars/2;
//--- move both anchor points horizontally at the same time
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2>1)
d2-=1;
//--- shift the points
if(!ArrowedLinePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!ArrowedLinePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.03 seconds of delay
Sleep(30);
}
//--- 1 second of delay
Sleep(1000);
//--- delete an arrowed line
ArrowedLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


427 Constants, Enumerations and Structures

OBJ_CHANNEL
Equidistant Channel

Note

For an equidistant channel, it is possible to specify the mode of its continuation to the right and/or
to the left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly). The mode of
filling the channel with color can also be set.
Example

The following script creates and moves an equidistant channel on the chart. S pecial functions have
been developed to create and change graphical object's properties. You can use these functions " as
is " in your own applications.

//--- description
#property description "Script draws \"Equidistant Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Channel"; // Channel name
input int InpDate1=25; // 1 st point's date, %
input int InpPrice1=60; // 1 st point's price, %
input int InpDate2=65; // 2 nd point's date, %
input int InpPrice2=80; // 2 nd point's price, %
input int InpDate3=30; // 3 rd point's date, %

© 2000-2025, MetaQuotes Ltd.


428 Constants, Enumerations and Structures

input int InpPrice3=40; // 3 rd point's price, %


input color InpColor=clrRed; // Channel color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of channel lines
input int InpWidth=2; // Channel line width
input bool InpBack=false; // Background channel
input bool InpFill=false; // Filling the channel with color
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Channel's continuation to the left
input bool InpRayRight=false; // Channel's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create an equidistant channel by the given coordinates |
//+------------------------------------------------------------------+
bool ChannelCreate(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // channel color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel lines
const int width=1, // width of channel lines
const bool fill=false, // filling the channel with color
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // channel's continuation to the left
const bool ray_right=false, // channel's continuation to the right
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeChannelEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_CHANNEL,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create an equidistant channel! Error code = ",GetLastError());
return(false);
}
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);

© 2000-2025, MetaQuotes Ltd.


429 Constants, Enumerations and Structures

//--- set width of the channel lines


ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the channel
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the lef
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the rig
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the channel's anchor point |
//+------------------------------------------------------------------+
bool ChannelPointChange(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

© 2000-2025, MetaQuotes Ltd.


430 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
//| Delete the channel |
//+------------------------------------------------------------------+
bool ChannelDelete(const long chart_ID=0, // chart's ID
const string name="Channel") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the channel! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Check the values of the channel's anchor points and set default values |
//| for empty ones |
//+-------------------------------------------------------------------------+
void ChangeChannelEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the second (right) point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 300 points higher than the second one
if(!price1)
price1=price2+300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the first point's one
if(!time3)
time3=time1;
//--- if the third point's price is not set, it is equal to the second point's one
if(!price3)
price3=price2;

© 2000-2025, MetaQuotes Ltd.


431 Constants, Enumerations and Structures

}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create the equidistant channel
if(!ChannelCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],InpColor,

© 2000-2025, MetaQuotes Ltd.


432 Constants, Enumerations and Structures

InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the channel's anchor points
//--- loop counter
int h_steps=bars/6;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!ChannelPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1>1)
d1-=1;
//--- move the point
if(!ChannelPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter

© 2000-2025, MetaQuotes Ltd.


433 Constants, Enumerations and Structures

int v_steps=accuracy/10;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3>1)
p3-=1;
//--- move the point
if(!ChannelPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
ChannelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


434 Constants, Enumerations and Structures

OBJ_STDDEVCHANNEL
S tandard Deviation Channel.

Note

For S tandard Deviation Channel, it is possible to specify the mode of continuation of its display to
the right and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly). The
mode of filling the channel with color can also be set.
OBJPROP_DEVIATION property is used to change the value of the channel deviation.
Example

The following script creates and moves S tandard Deviation Channel on the chart. S pecial functions
have been developed to create and change graphical object's properties. You can use these functions
" as is " in your own applications.

//--- description
#property description "Script draws \"Standard Deviation Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="StdDevChannel"; // Channel name
input int InpDate1=10; // 1 st point's date, %
input int InpDate2=40; // 2 nd point's date, %
input double InpDeviation=1.0; // Deviation
input color InpColor=clrRed; // Channel color

© 2000-2025, MetaQuotes Ltd.


435 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of channel lines


input int InpWidth=2; // Width of channel lines
input bool InpFill=false; // Filling the channel with color
input bool InpBack=false; // Background channel
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Channel's continuation to the left
input bool InpRayRight=false; // Channel's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create standard deviation channel by the given coordinates |
//+------------------------------------------------------------------+
bool StdDevChannelCreate(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
datetime time2=0, // second point time
const double deviation=1.0, // deviation
const color clr=clrRed, // channel color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel lines
const int width=1, // width of channel lines
const bool fill=false, // filling the channel with color
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // channel's continuation to the
const bool ray_right=false, // channel's continuation to the
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeChannelEmptyPoints(time1,time2);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_STDDEVCHANNEL,sub_window,time1,0,time2,0))
{
Print(__FUNCTION__,
": failed to create standard deviation channel! Error code = ",GetLastError());
return(false);
}
//--- set deviation value affecting the channel width
ObjectSetDouble(chart_ID,name,OBJPROP_DEVIATION,deviation);
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the channel

© 2000-2025, MetaQuotes Ltd.


436 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the lef
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the rig
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the channel's anchor point |
//+------------------------------------------------------------------+
bool StdDevChannelPointChange(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int point_index=0, // anchor point index
datetime time=0) // anchor point time coordinate
{
//--- if point time is not set, move the point to the current bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,0))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the channel's deviation |
//+------------------------------------------------------------------+
bool StdDevChannelDeviationChange(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const double deviation=1.0) // deviation

© 2000-2025, MetaQuotes Ltd.


437 Constants, Enumerations and Structures

{
//--- reset the error value
ResetLastError();
//--- change trend line's slope angle
if(!ObjectSetDouble(chart_ID,name,OBJPROP_DEVIATION,deviation))
{
Print(__FUNCTION__,
": failed to change channel deviation! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel |
//+------------------------------------------------------------------+
bool StdDevChannelDelete(const long chart_ID=0, // chart's ID
const string name="Channel") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the channel! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Check the values of the channel's anchor points and set default values |
//| for empty ones |
//+-------------------------------------------------------------------------+
void ChangeChannelEmptyPoints(datetime &time1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}

© 2000-2025, MetaQuotes Ltd.


438 Constants, Enumerations and Structures

}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
//--- create standard deviation channel
if(!StdDevChannelCreate(0,InpName,0,date[d1],date[d2],InpDeviation,InpColor,InpStyle,
InpWidth,InpFill,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second

© 2000-2025, MetaQuotes Ltd.


439 Constants, Enumerations and Structures

ChartRedraw();
Sleep(1000);
//--- now, move the channel horizontally to the right and expand it
//--- loop counter
int h_steps=bars/2;
//--- move the channel
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2<bars-1)
d2+=1;
//--- move the anchor points
if(!StdDevChannelPointChange(0,InpName,0,date[d1]))
return;
if(!StdDevChannelPointChange(0,InpName,1,date[d2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
double v_steps=InpDeviation*2;
//--- expand the channel
for(double i=InpDeviation;i<v_steps;i+=10.0/accuracy)
{
if(!StdDevChannelDeviationChange(0,InpName,i))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
StdDevChannelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---

© 2000-2025, MetaQuotes Ltd.


440 Constants, Enumerations and Structures

© 2000-2025, MetaQuotes Ltd.


441 Constants, Enumerations and Structures

OBJ_REGRESSION
Linear Regression Channel.

Note

For Linear Regression Channel, it is possible to specify the mode of continuation of its display to the
right and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly). The mode
of filling the channel with color can also be set.
Example

The following script creates and moves Linear Regression Channel on the chart. S pecial functions
have been developed to create and change graphical object's properties. You can use these functions
" as is " in your own applications.

//--- description
#property description "Script draws \"Linear Regression Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Regression"; // Channel name
input int InpDate1=10; // 1 st point's date, %
input int InpDate2=40; // 2 nd point's date, %
input color InpColor=clrRed; // Channel color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of channel lines
input int InpWidth=2; // Width of channel lines

© 2000-2025, MetaQuotes Ltd.


442 Constants, Enumerations and Structures

input bool InpFill=false; // Filling the channel with color


input bool InpBack=false; // Background channel
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Channel's continuation to the left
input bool InpRayRight=false; // Channel's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Linear Regression Channel by the given coordinates |
//+------------------------------------------------------------------+
bool RegressionCreate(const long chart_ID=0, // chart's ID
const string name="Regression", // channel name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
datetime time2=0, // second point time
const color clr=clrRed, // channel color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel lines
const int width=1, // width of channel lines
const bool fill=false, // filling the channel with color
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // channel's continuation to the lef
const bool ray_right=false, // channel's continuation to the rig
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeRegressionEmptyPoints(time1,time2);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_REGRESSION,sub_window,time1,0,time2,0))
{
Print(__FUNCTION__,
": failed to create linear regression channel! Error code = ",GetLastError());
return(false);
}
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the channel
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be

© 2000-2025, MetaQuotes Ltd.


443 Constants, Enumerations and Structures

//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the lef
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the rig
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the channel's anchor point |
//+------------------------------------------------------------------+
bool RegressionPointChange(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int point_index=0, // anchor point index
datetime time=0) // anchor point time coordinate
{
//--- if point time is not set, move the point to the current bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,0))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel |
//+------------------------------------------------------------------+
bool RegressionDelete(const long chart_ID=0, // chart's ID
const string name="Channel") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{

© 2000-2025, MetaQuotes Ltd.


444 Constants, Enumerations and Structures

Print(__FUNCTION__,
": failed to delete the channel! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Check the values of the channel's anchor points and set default values |
//| for empty ones |
//+-------------------------------------------------------------------------+
void ChangeRegressionEmptyPoints(datetime &time1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);

© 2000-2025, MetaQuotes Ltd.


445 Constants, Enumerations and Structures

//--- fill the array of dates


ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
//--- create linear regression channel
if(!RegressionCreate(0,InpName,0,date[d1],date[d2],InpColor,InpStyle,InpWidth,
InpFill,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the channel horizontally to the right
//--- loop counter
int h_steps=bars/2;
//--- move the channel
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2<bars-1)
d2+=1;
//--- move the anchor points
if(!RegressionPointChange(0,InpName,0,date[d1]))
return;
if(!RegressionPointChange(0,InpName,1,date[d2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay

© 2000-2025, MetaQuotes Ltd.


446 Constants, Enumerations and Structures

Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
RegressionDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


447 Constants, Enumerations and Structures

OBJ_PITCHFORK
Andrews ’ Pitchfork.

Note

For Andrews ’ Pitchfork , it is possible to specify the mode of continuation of its display to the right
and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
You can also specify the number of line-levels, their values and color.
Example

The following script creates and moves Andrews ’ Pitchfork on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.
//--- description
#property description "Script draws \"Andrews’ Pitchfork\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Pitchfork"; // Pitchfork name
input int InpDate1=14; // 1 st point's date, %
input int InpPrice1=40; // 1 st point's price, %
input int InpDate2=18; // 2 nd point's date, %
input int InpPrice2=50; // 2 nd point's price, %
input int InpDate3=18; // 3 rd point's date, %
input int InpPrice3=30; // 3 rd point's price, %

© 2000-2025, MetaQuotes Ltd.


448 Constants, Enumerations and Structures

input color InpColor=clrRed; // Pitchfork color


input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Style of pitchfork lines
input int InpWidth=1; // Width of pitchfork lines
input bool InpBack=false; // Background pitchfork
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Pitchfork's continuation to the left
input bool InpRayRight=false; // Pitchfork's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Andrews' Pitchfork by the given coordinates |
//+------------------------------------------------------------------+
bool PitchforkCreate(const long chart_ID=0, // chart's ID
const string name="Pitchfork", // pitchfork name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // color of pitchfork lines
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of pitchfork lines
const int width=1, // width of pitchfork lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // pitchfork's continuation to the le
const bool ray_right=false, // pitchfork's continuation to the ri
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeChannelEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create Andrews' Pitchfork by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_PITCHFORK,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create \"Andrews' Pitchfork\"! Error code = ",GetLastError());
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)

© 2000-2025, MetaQuotes Ltd.


449 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the pitchfork for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the pitchfork's display to the l
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the pitchfork's display to the r
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of Andrews' Pitchfork levels and their parameters |
//+------------------------------------------------------------------+
bool PitchforkLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="Pitchfork") // pitchfork name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);

© 2000-2025, MetaQuotes Ltd.


450 Constants, Enumerations and Structures

//--- level description


ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Andrews' Pitchfork anchor point |
//+------------------------------------------------------------------+
bool PitchforkPointChange(const long chart_ID=0, // chart's ID
const string name="Pitchfork", // channel name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Andrews’ Pitchfork |
//+------------------------------------------------------------------+
bool PitchforkDelete(const long chart_ID=0, // chart's ID
const string name="Pitchfork") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Andrews' Pitchfork\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);

© 2000-2025, MetaQuotes Ltd.


451 Constants, Enumerations and Structures

}
//+----------------------------------------------------------------------+
//| Check the values of Andrews' Pitchfork anchor points and set default |
//| values for empty ones |
//+----------------------------------------------------------------------+
void ChangeChannelEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the second (upper right) point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 200 points below the second one
if(!price1)
price1=price2-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the second point's one
if(!time3)
time3=time2;
//--- if the third point's price is not set, move it 200 points lower than the first one
if(!price3)
price3=price1-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size

© 2000-2025, MetaQuotes Ltd.


452 Constants, Enumerations and Structures

int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Andrews' Pitchfork anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Andrews' Pitchfork
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create the pitchfork
if(!PitchforkCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the pitchfork's anchor points
//--- loop counter
int v_steps=accuracy/10;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point

© 2000-2025, MetaQuotes Ltd.


453 Constants, Enumerations and Structures

if(!PitchforkPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/8;
//--- move the third anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d3<bars-1)
d3+=1;
//--- move the point
if(!PitchforkPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/10;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2>1)
p2-=1;
//--- move the point
if(!PitchforkPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();

© 2000-2025, MetaQuotes Ltd.


454 Constants, Enumerations and Structures

}
//--- 1 second of delay
Sleep(1000);
//--- delete the pitchfork from the chart
PitchforkDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


455 Constants, Enumerations and Structures

OBJ_GANNLINE
Gann Line.

Note

For Gann Line, it is possible to specify the mode of continuation of its display to the right and/or
left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
Both Gann angle with a scale and coordinates of the second anchor point can be used to set the slope
of the line.
Example

The following script creates and moves Gann Line on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Gann Line\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="GannLine"; // Line name
input int InpDate1=20; // 1 st point's date, %
input int InpPrice1=75; // 1 st point's price, %
input int InpDate2=80; // 2 nd point's date, %
input double InpAngle=0.0; // Gann Angle

© 2000-2025, MetaQuotes Ltd.


456 Constants, Enumerations and Structures

input double InpScale=1.0; // Scale


input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int InpWidth=2; // Line width
input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Line's continuation to the left
input bool InpRayRight=true; // Line's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Gann Line by the coordinates, angle and scale |
//+------------------------------------------------------------------+
bool GannLineCreate(const long chart_ID=0, // chart's ID
const string name="GannLine", // line name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
const double angle=1.0, // Gann angle
const double scale=1.0, // scale
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // line's continuation to the left
const bool ray_right=true, // line's continuation to the right
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeGannLineEmptyPoints(time1,price1,time2);
//--- reset the error value
ResetLastError();
//--- create Gann Line by the given coordinates
//--- correct coordinate of the second anchor point is redefined
//--- automatically after Gann angle and/or the scale changes,
if(!ObjectCreate(chart_ID,name,OBJ_GANNLINE,sub_window,time1,price1,time2,0))
{
Print(__FUNCTION__,
": failed to create \"Gann Line\"! Error code = ",GetLastError());
return(false);
}
//--- change Gann angle
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- change the scale (number of pips per bar)
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- set line color

© 2000-2025, MetaQuotes Ltd.


457 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the lines for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the line's display to the left
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the line's display to the right
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Gann Line anchor point |
//+------------------------------------------------------------------+
bool GannLinePointChange(const long chart_ID=0, // chart's ID
const string name="GannLine", // line name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the line's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);

© 2000-2025, MetaQuotes Ltd.


458 Constants, Enumerations and Structures

}
//+------------------------------------------------------------------+
//| Change Gann angle |
//+------------------------------------------------------------------+
bool GannLineAngleChange(const long chart_ID=0, // chart's ID
const string name="GannLine", // line name
const double angle=1.0) // Gann angle
{
//--- reset the error value
ResetLastError();
//--- change Gann angle
if(!ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle))
{
Print(__FUNCTION__,
": failed to change Gann angle! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Line's scale |
//+------------------------------------------------------------------+
bool GannLineScaleChange(const long chart_ID=0, // chart's ID
const string name="GannLine", // line name
const double scale=1.0) // scale
{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))
{
Print(__FUNCTION__,
": failed to change the scale! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes Gann Line from the chart |
//+------------------------------------------------------------------+
bool GannLineDelete(const long chart_ID=0, // chart's ID
const string name="GannLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete Gann line
if(!ObjectDelete(chart_ID,name))

© 2000-2025, MetaQuotes Ltd.


459 Constants, Enumerations and Structures

{
Print(__FUNCTION__,
": failed to delete \"Gann Line\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Gann Line anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeGannLineEmptyPoints(datetime &time1,double &price1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];

© 2000-2025, MetaQuotes Ltd.


460 Constants, Enumerations and Structures

double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Gann Line
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create Gann Line
if(!GannLineCreate(0,InpName,0,date[d1],price[p1],date[d2],InpAngle,InpScale,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line's anchor point and change the angle
//--- loop counter
int v_steps=accuracy/2;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!GannLinePointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();

© 2000-2025, MetaQuotes Ltd.


461 Constants, Enumerations and Structures

}
//--- half a second of delay
Sleep(500);
//--- define the current value of Gann angle (changed
//--- after moving the first anchor point)
double curr_angle;
if(!ObjectGetDouble(0,InpName,OBJPROP_ANGLE,0,curr_angle))
return;
//--- loop counter
v_steps=accuracy/8;
//--- change Gann angle
for(int i=0;i<v_steps;i++)
{
if(!GannLineAngleChange(0,InpName,curr_angle-0.05*i))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the line from the chart
GannLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


462 Constants, Enumerations and Structures

OBJ_GANNFAN
Gann Fan.

Note

For Gann Fan, it is possible to specify trend type from ENUM _GANN_DIRECTION enumeration. By
adjusting the scale value (OBJPROP_S CALE), it is possible to change slope angle of the fan lines.
Example

The following script creates and moves Gann Fan on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Gann Fan\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="GannFan"; // Fan name
input int InpDate1=15; // 1 st point's date, %
input int InpPrice1=25; // 1 st point's price, %
input int InpDate2=85; // 2 nd point's date, %
input double InpScale=2.0; // Scale
input bool InpDirection=false; // Trend direction
input color InpColor=clrRed; // Fan color

© 2000-2025, MetaQuotes Ltd.


463 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of fan lines


input int InpWidth=1; // Width of fan lines
input bool InpBack=false; // Background fan
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Gann Fan |
//+------------------------------------------------------------------+
bool GannFanCreate(const long chart_ID=0, // chart's ID
const string name="GannFan", // fan name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
const double scale=1.0, // scale
const bool direction=true, // trend direction
const color clr=clrRed, // fan color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of fan lines
const int width=1, // width of fan lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeGannFanEmptyPoints(time1,price1,time2);
//--- reset the error value
ResetLastError();
//--- create Gann Fan by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_GANNFAN,sub_window,time1,price1,time2,0))
{
Print(__FUNCTION__,
": failed to create \"Gann Fan\"! Error code = ",GetLastError());
return(false);
}
//--- change the scale (number of pips per bar)
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- change Gann Fan's trend direction (true - descending, false - ascending)
ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction);
//--- set fan color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set display style of the fan lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the fan lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the fan for moving

© 2000-2025, MetaQuotes Ltd.


464 Constants, Enumerations and Structures

//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Gann Fan anchor point |
//+------------------------------------------------------------------+
bool GannFanPointChange(const long chart_ID=0, // chart's ID
const string name="GannFan", // fan name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the fan's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Fan's scale |
//+------------------------------------------------------------------+
bool GannFanScaleChange(const long chart_ID=0, // chart's ID
const string name="GannFan", // fan name
const double scale=1.0) // scale
{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))

© 2000-2025, MetaQuotes Ltd.


465 Constants, Enumerations and Structures

{
Print(__FUNCTION__,
": failed to change the scale! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Fan's trend direction |
//+------------------------------------------------------------------+
bool GannFanDirectionChange(const long chart_ID=0, // chart's ID
const string name="GannFan", // fan name
const bool direction=true) // trend direction
{
//--- reset the error value
ResetLastError();
//--- change Gann Fan's trend direction
if(!ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction))
{
Print(__FUNCTION__,
": failed to change trend direction! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes Gann Fan from the chart |
//+------------------------------------------------------------------+
bool GannFanDelete(const long chart_ID=0, // chart's ID
const string name="GannFan") // fan name
{
//--- reset the error value
ResetLastError();
//--- delete Gann Fan
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Gann Fan\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
// | Check the values of Gann Fan anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


466 Constants, Enumerations and Structures

void ChangeGannFanEmptyPoints(datetime &time1,double &price1,datetime &time2)


{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of fan's anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices

© 2000-2025, MetaQuotes Ltd.


467 Constants, Enumerations and Structures

//--- find the highest and lowest values of the chart


double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Gann Fan
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create Gann Fan
if(!GannFanCreate(0,InpName,0,date[d1],price[p1],date[d2],InpScale,InpDirection,
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the fan's anchor point
//--- loop counter
int v_steps=accuracy/2;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
//--- move the point
if(!GannFanPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- change fan's trend direction to descending one
GannFanDirectionChange(0,InpName,true);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the fan from the chart
GannFanDelete(0,InpName);
ChartRedraw();

© 2000-2025, MetaQuotes Ltd.


468 Constants, Enumerations and Structures

//--- 1 second of delay


Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


469 Constants, Enumerations and Structures

OBJ_GANNGRID
Gann Grid.

Note

For Gann Grid, it is possible to specify trend type from ENUM _GANN_DIRECTION. By adjusting the
scale value (OBJPROP_S CALE), it is possible to change slope angle of the grid lines.
Example

The following script creates and moves Gann Grid on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Gann Grid\" graphical object."
#property description "Anchor point coordinates of the grid are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="GannGrid"; // Grid name
input int InpDate1=15; // 1 st point's date, %
input int InpPrice1=25; // 1 st point's price, %
input int InpDate2=35; // 2 nd point's date, %
input double InpScale=3.0; // Scale
input bool InpDirection=false; // Trend direction
input color InpColor=clrRed; // Grid color

© 2000-2025, MetaQuotes Ltd.


470 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of grid lines


input int InpWidth=1; // Width of fan lines
input bool InpBack=false; // Background grid
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Gann Grid |
//+------------------------------------------------------------------+
bool GannGridCreate(const long chart_ID=0, // chart's ID
const string name="GannGrid", // grid name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
const double scale=1.0, // scale
const bool direction=true, // trend direction
const color clr=clrRed, // grid color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of grid lines
const int width=1, // width of grid lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeGannGridEmptyPoints(time1,price1,time2);
//--- reset the error value
ResetLastError();
//--- create Gann Grid by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_GANNGRID,sub_window,time1,price1,time2,0))
{
Print(__FUNCTION__,
": failed to create \"Gann Grid\"! Error code = ",GetLastError());
return(false);
}
//--- change the scale (number of pips per bar)
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- change Gann Fan's trend direction (true - descending, false - ascending)
ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction);
//--- set grid color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set display style of the grid lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the grid lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the grid for moving

© 2000-2025, MetaQuotes Ltd.


471 Constants, Enumerations and Structures

//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Gann Grid anchor point |
//+------------------------------------------------------------------+
bool GannGridPointChange(const long chart_ID=0, // chart's ID
const string name="GannGrid", // grid name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the grid's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Grid's scale |
//+------------------------------------------------------------------+
bool GannGridScaleChange(const long chart_ID=0, // chart's ID
const string name="GannGrid", // grids
const double scale=1.0) // scale
{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))

© 2000-2025, MetaQuotes Ltd.


472 Constants, Enumerations and Structures

{
Print(__FUNCTION__,
": failed to change the scale! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Grid's trend direction |
//+------------------------------------------------------------------+
bool GannGridDirectionChange(const long chart_ID=0, // chart's ID
const string name="GannGrid", // grid name
const bool direction=true) // trend direction
{
//--- reset the error value
ResetLastError();
//--- change Gann Grid's trend direction
if(!ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction))
{
Print(__FUNCTION__,
": failed to change trend direction! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes Gann Fan from the chart |
//+------------------------------------------------------------------+
bool GannGridDelete(const long chart_ID=0, // chart's ID
const string name="GannGrid") // grid name
{
//--- reset the error value
ResetLastError();
//--- delete Gann Grid
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Gann Grid\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Gann Grid anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


473 Constants, Enumerations and Structures

void ChangeGannGridEmptyPoints(datetime &time1,double &price1,datetime &time2)


{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing grid anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices

© 2000-2025, MetaQuotes Ltd.


474 Constants, Enumerations and Structures

//--- find the highest and lowest values of the chart


double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Gann Grid
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create Gann Grid
if(!GannGridCreate(0,InpName,0,date[d1],price[p1],date[d2],InpScale,InpDirection,
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the grid's anchor points
//--- loop counter
int v_steps=accuracy/4;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
if(!GannGridPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/4;
//--- move the second anchor point horizontally
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
if(!GannGridPointChange(0,InpName,1,date[d2],0))
return;

© 2000-2025, MetaQuotes Ltd.


475 Constants, Enumerations and Structures

//--- check if the script's operation has been forcefully disabled


if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- change grid's trend direction to descending one
GannGridDirectionChange(0,InpName,true);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the grid from the chart
GannGridDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


476 Constants, Enumerations and Structures

OBJ_FIBO
Fibonacci R etracement.

Note

For Fibonacci R etracement, it is possible to specify the mode of continuation of its display to the
right and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
You can also specify the number of line-levels, their values and color.
Example

The following script creates and moves Fibonacci Retracement on the chart. S pecial functions have
been developed to create and change graphical object's properties. You can use these functions " as
is " in your own applications.

//--- description
#property description "Script draws \"Fibonacci Retracement\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboLevels"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=65; // 1 st point's price, %
input int InpDate2=90; // 2 nd point's date, %
input int InpPrice2=85; // 2 nd point's price, %
input color InpColor=clrRed; // Object color

© 2000-2025, MetaQuotes Ltd.


477 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style


input int InpWidth=2; // Line width
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Object's continuation to the left
input bool InpRayRight=false; // Object's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Retracement by the given coordinates |
//+------------------------------------------------------------------+
bool FiboLevelsCreate(const long chart_ID=0, // chart's ID
const string name="FiboLevels", // object name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // object color
const ENUM_LINE_STYLE style=STYLE_SOLID, // object line style
const int width=1, // object line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // object's continuation to the left
const bool ray_right=false, // object's continuation to the righ
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeFiboLevelsEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- Create Fibonacci Retracement by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBO,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Retracement\"! Error code = ",GetLastError());
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be

© 2000-2025, MetaQuotes Ltd.


478 Constants, Enumerations and Structures

//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the object's display to the left
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the object's display to the righ
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboLevels") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],1));
}
//--- successful execution

© 2000-2025, MetaQuotes Ltd.


479 Constants, Enumerations and Structures

return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Retracement anchor point |
//+------------------------------------------------------------------+
bool FiboLevelsPointChange(const long chart_ID=0, // chart's ID
const string name="FiboLevels", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Retracement |
//+------------------------------------------------------------------+
bool FiboLevelsDelete(const long chart_ID=0, // chart's ID
const string name="FiboLevels") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Retracement\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Retracement anchor points and set |
//| default values for empty ones |

© 2000-2025, MetaQuotes Ltd.


480 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
void ChangeFiboLevelsEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 200 points below the second one
if(!price1)
price1=price2-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Retracement anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)

© 2000-2025, MetaQuotes Ltd.


481 Constants, Enumerations and Structures

{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Retracement
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboLevelsCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy*2/5;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!FiboLevelsPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;
//--- move the second anchor point

© 2000-2025, MetaQuotes Ltd.


482 Constants, Enumerations and Structures

for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2>1)
p2-=1;
//--- move the point
if(!FiboLevelsPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboLevelsDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


483 Constants, Enumerations and Structures

OBJ_FIBOTIMES
Fibonacci Time Zones.

Note

For "Fibonacci Time Zones " , it is possible to specify the number of line-levels, their values and
color.
Example

The following script creates and moves Fibonacci Time Zones on the chart. S pecial functions have
been developed to create and change graphical object's properties. You can use these functions " as
is " in your own applications.
//--- description
#property description "Script draws \"Fibonacci Time Zones\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboTimes"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=45; // 1 st point's price, %
input int InpDate2=20; // 2 nd point's date, %
input int InpPrice2=55; // 2 nd point's price, %
input color InpColor=clrRed; // Object color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int InpWidth=2; // Line width

© 2000-2025, MetaQuotes Ltd.


484 Constants, Enumerations and Structures

input bool InpBack=false; // Background object


input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Time Zones by the given coordinates |
//+------------------------------------------------------------------+
bool FiboTimesCreate(const long chart_ID=0, // chart's ID
const string name="FiboTimes", // object name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // object color
const ENUM_LINE_STYLE style=STYLE_SOLID, // object line style
const int width=1, // object line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeFiboTimesEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create Fibonacci Time Zones by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOTIMES,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Time Zones\"! Error code = ",GetLastError());
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);

© 2000-2025, MetaQuotes Ltd.


485 Constants, Enumerations and Structures

//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboTimesLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboTimes") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Time Zones anchor point |
//+------------------------------------------------------------------+
bool FiboTimesPointChange(const long chart_ID=0, // chart's ID
const string name="FiboTimes", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate

© 2000-2025, MetaQuotes Ltd.


486 Constants, Enumerations and Structures

double price=0) // anchor point price coordinate


{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Time Zones |
//+------------------------------------------------------------------+
bool FiboTimesDelete(const long chart_ID=0, // chart's ID
const string name="FiboTimes") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Time Zones\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Time Zones and |
//| set default values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboTimesEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)

© 2000-2025, MetaQuotes Ltd.


487 Constants, Enumerations and Structures

price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 2 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 3 bars
datetime temp[3];
CopyTime(Symbol(),Period(),time1,3,temp);
//--- set the first point 2 bars left from the second one
time2=temp[0];
}
//--- if the second point's price is not set, it is equal to the first point's one
if(!price2)
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Time Zones anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array

© 2000-2025, MetaQuotes Ltd.


488 Constants, Enumerations and Structures

double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Time Zones
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboTimesCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int h_steps=bars*2/5;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!FiboTimesPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
h_steps=bars*3/5;
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1<bars-1)
d1+=1;
//--- move the point
if(!FiboTimesPointChange(0,InpName,0,date[d1],price[p1]))

© 2000-2025, MetaQuotes Ltd.


489 Constants, Enumerations and Structures

return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboTimesDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


490 Constants, Enumerations and Structures

OBJ_FIBOFAN
Fibonacci Fan.

Note

For "Fibonacci Fan" , it is possible to specify the number of line-levels, their values and color.
Example

The following script creates and moves Fibonacci Fan on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Fibonacci Fan\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboFan"; // Fan name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=25; // 1 st point's price, %
input int InpDate2=30; // 2 nd point's date, %
input int InpPrice2=50; // 2 nd point's price, %
input color InpColor=clrRed; // Fan line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int InpWidth=2; // Line width

© 2000-2025, MetaQuotes Ltd.


491 Constants, Enumerations and Structures

input bool InpBack=false; // Background object


input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Fan by the given coordinates |
//+------------------------------------------------------------------+
bool FiboFanCreate(const long chart_ID=0, // chart's ID
const string name="FiboFan", // fan name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // fan line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // fan line style
const int width=1, // fan line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeFiboFanEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create Fibonacci Fan by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOFAN,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Fan\"! Error code = ",GetLastError());
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the fan for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);

© 2000-2025, MetaQuotes Ltd.


492 Constants, Enumerations and Structures

//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboFanLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboFan") // fan name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Fan anchor point |
//+------------------------------------------------------------------+
bool FiboFanPointChange(const long chart_ID=0, // chart's ID
const string name="FiboFan", // fan name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate

© 2000-2025, MetaQuotes Ltd.


493 Constants, Enumerations and Structures

double price=0) // anchor point price coordinate


{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Fan |
//+------------------------------------------------------------------+
bool FiboFanDelete(const long chart_ID=0, // chart's ID
const string name="FiboFan") // fan name
{
//--- reset the error value
ResetLastError();
//--- delete the fan
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Fan\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Fan anchor points and set |
//| default values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboFanEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)

© 2000-2025, MetaQuotes Ltd.


494 Constants, Enumerations and Structures

price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 200 points below the second one
if(!price1)
price1=price2-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Fan anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array

© 2000-2025, MetaQuotes Ltd.


495 Constants, Enumerations and Structures

double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Fan
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboFanCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the fan's anchor points
//--- loop counter
int v_steps=accuracy/2;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
//--- move the point
if(!FiboFanPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/4;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!FiboFanPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled

© 2000-2025, MetaQuotes Ltd.


496 Constants, Enumerations and Structures

if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboFanDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


497 Constants, Enumerations and Structures

OBJ_FIBOARC
Fibonacci Arcs.

Note

For "Fibonacci Arcs " ,


it is possible to specify the display mode of the entire ellipse. Curvature radius
can be specified by changing the scale and coordinates of the anchor points.
You can also specify the number of line-levels, their values and color.
Example

The following script creates and moves Fibonacci Arcs on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Fibonacci Arcs\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboArc"; // Object name
input int InpDate1=25; // 1 st point's date, %
input int InpPrice1=25; // 1 st point's price, %
input int InpDate2=35; // 2 nd point's date, %
input int InpPrice2=55; // 2 nd point's price, %
input double InpScale=3.0; // Scale

© 2000-2025, MetaQuotes Ltd.


498 Constants, Enumerations and Structures

input bool InpFullEllipse=true; // Shape of the arcs


input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int InpWidth=2; // Line width
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Arcs by the given coordinates |
//+------------------------------------------------------------------+
bool FiboArcCreate(const long chart_ID=0, // chart's ID
const string name="FiboArc", // object name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const double scale=1.0, // scale
const bool full_ellipse=false, // shape of the arcs
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeFiboArcEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create Fibonacci Arcs by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOARC,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Arcs\"! Error code = ",GetLastError());
return(false);
}
//--- set the scale
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- set display of the arcs as a full ellipse (true) or a half of it (false)
ObjectSetInteger(chart_ID,name,OBJPROP_ELLIPSE,full_ellipse);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);

© 2000-2025, MetaQuotes Ltd.


499 Constants, Enumerations and Structures

//--- display in the foreground (false) or background (true)


ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the arcs for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboArcLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboArc") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],1));
}

© 2000-2025, MetaQuotes Ltd.


500 Constants, Enumerations and Structures

//--- successful execution


return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Arcs anchor point |
//+------------------------------------------------------------------+
bool FiboArcPointChange(const long chart_ID=0, // chart's ID
const string name="FiboArc", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Arcs |
//+------------------------------------------------------------------+
bool FiboArcDelete(const long chart_ID=0, // chart's ID
const string name="FiboArc") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Arcs\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Arcs anchor points and set default |

© 2000-2025, MetaQuotes Ltd.


501 Constants, Enumerations and Structures

//| values for empty ones |


//+------------------------------------------------------------------+
void ChangeFiboArcEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 300 points below the second one
if(!price1)
price1=price2-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Arcs anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


502 Constants, Enumerations and Structures

if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Arcs
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboArcCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpScale,
InpFullEllipse,InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
//--- move the point
if(!FiboArcPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/5;

© 2000-2025, MetaQuotes Ltd.


503 Constants, Enumerations and Structures

//--- move the second anchor point


for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!FiboArcPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboArcDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


504 Constants, Enumerations and Structures

OBJ_FIBOCHANNEL
Fibonacci Channel.

Note

For Fibonacci Channel, it is possible to specify the mode of continuation of its display to the right
and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
You can also specify the number of line-levels, their values and color.
Example

The following script creates and moves Fibonacci Channel on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Fibonacci Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboChannel"; // Channel name
input int InpDate1=20; // 1 st point's date, %
input int InpPrice1=10; // 1 st point's price, %
input int InpDate2=60; // 2 nd point's date, %
input int InpPrice2=30; // 2 nd point's price, %
input int InpDate3=20; // 3 rd point's date, %

© 2000-2025, MetaQuotes Ltd.


505 Constants, Enumerations and Structures

input int InpPrice3=25; // 3 rd point's price, %


input color InpColor=clrRed; // Channel color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of channel lines
input int InpWidth=2; // Width of channel lines
input bool InpBack=false; // Background channel
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Channel's continuation to the left
input bool InpRayRight=false; // Channel's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Channel by the given coordinates |
//+------------------------------------------------------------------+
bool FiboChannelCreate(const long chart_ID=0, // chart's ID
const string name="FiboChannel", // channel name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // channel color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel lines
const int width=1, // width of channel lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // channel's continuation to the l
const bool ray_right=false, // channel's continuation to the r
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeFiboChannelEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOCHANNEL,sub_window,time1,price1,time2,price2,time3,price3
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Channel\"! Error code = ",GetLastError());
return(false);
}
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);

© 2000-2025, MetaQuotes Ltd.


506 Constants, Enumerations and Structures

//--- display in the foreground (false) or background (true)


ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the lef
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the channel's display to the rig
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboChannelLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboChannel") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width

© 2000-2025, MetaQuotes Ltd.


507 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Channel anchor point |
//+------------------------------------------------------------------+
bool FiboChannelPointChange(const long chart_ID=0, // chart's ID
const string name="FiboChannel", // channel name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel |
//+------------------------------------------------------------------+
bool FiboChannelDelete(const long chart_ID=0, // chart's ID
const string name="FiboChannel") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Channel\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution

© 2000-2025, MetaQuotes Ltd.


508 Constants, Enumerations and Structures

return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Channel anchor points and set |
//| default values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboChannelEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the second (right) point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the second one
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 300 points higher than the second one
if(!price1)
price1=price2+300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the first point's one
if(!time3)
time3=time1;
//--- if the third point's price is not set, it is equal to the second point's one
if(!price3)
price3=price2;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);

© 2000-2025, MetaQuotes Ltd.


509 Constants, Enumerations and Structures

//--- price array size


int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create Fibonacci Channel
if(!FiboChannelCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the channel's anchor points
//--- loop counter
int h_steps=bars/10;
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1>1)
d1-=1;

© 2000-2025, MetaQuotes Ltd.


510 Constants, Enumerations and Structures

//--- move the point


if(!FiboChannelPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/10;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2>1)
p2-=1;
//--- move the point
if(!FiboChannelPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/15;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3<accuracy-1)
p3+=1;
//--- move the point
if(!FiboChannelPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}

© 2000-2025, MetaQuotes Ltd.


511 Constants, Enumerations and Structures

//--- 1 second of delay


Sleep(1000);
//--- delete the channel from the chart
FiboChannelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


512 Constants, Enumerations and Structures

OBJ_EXPANSION
Fibonacci Expansion.

Note

For "Fibonacci Expansion" , it is possible to specify the mode of continuation of its display to the
right and/or left (OBJPROP_RAY_RIGHT and OBJPROP_RAY_LEFT properties accordingly).
You can also specify the number of line-levels, their values and color.
Example

The following script creates and moves Fibonacci Expansion on the chart. S pecial functions have
been developed to create and change graphical object's properties. You can use these functions " as
is " in your own applications.

//--- description
#property description "Script draws \"Fibonacci Expansion\"graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboExpansion"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=55; // 1 st point's price, %
input int InpDate2=30; // 2 nd point's date, %
input int InpPrice2=10; // 2 nd point's price, %
input int InpDate3=80; // 3 rd point's date, %

© 2000-2025, MetaQuotes Ltd.


513 Constants, Enumerations and Structures

input int InpPrice3=75; // 3 rd point's price, %


input color InpColor=clrRed; // Object color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of lines
input int InpWidth=2; // Width of the lines
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpRayLeft=false; // Object's continuation to the left
input bool InpRayRight=false; // Object's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Extension by the given coordinates |
//+------------------------------------------------------------------+
bool FiboExpansionCreate(const long chart_ID=0, // chart's ID
const string name="FiboExpansion", // channel name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // object color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of the lines
const int width=1, // width of the lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_left=false, // object's continuation to th
const bool ray_right=false, // object's continuation to th
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeFiboExpansionEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- Create Fibonacci Extension by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_EXPANSION,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Extension\"! Error code = ",GetLastError());
return(false);
}
//--- set the object's color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);

© 2000-2025, MetaQuotes Ltd.


514 Constants, Enumerations and Structures

//--- display in the foreground (false) or background (true)


ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the object's visualization to th
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);
//--- enable (true) or disable (false) the mode of continuation of the object's visualization to th
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboExpansionLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboExpansion") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width

© 2000-2025, MetaQuotes Ltd.


515 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,"FE "+DoubleToString(100*values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Expansion anchor point |
//+------------------------------------------------------------------+
bool FiboExpansionPointChange(const long chart_ID=0, // chart's ID
const string name="FiboExpansion", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Expansion |
//+------------------------------------------------------------------+
bool FiboExpansionDelete(const long chart_ID=0, // chart's ID
const string name="FiboExpansion") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Expansion\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution

© 2000-2025, MetaQuotes Ltd.


516 Constants, Enumerations and Structures

return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Expansion anchor points and set |
//| default values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboExpansionEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the third (right) point's time is not set, it will be on the current bar
if(!time3)
time3=TimeCurrent();
//--- if the third point's price is not set, it will have Bid value
if(!price3)
price3=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the third one
//--- array for receiving the open time of the last 10 bars
datetime temp[];
ArrayResize(temp,10);
if(!time1)
{
CopyTime(Symbol(),Period(),time3,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it is equal to the third point's one
if(!price1)
price1=price3;
//--- if the second point's time is not set, it is located 7 bars left from the third one
if(!time2)
time2=temp[2];
//--- if the second point's price is not set, move it 250 points lower than the first one
if(!price2)
price2=price1-250*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window

© 2000-2025, MetaQuotes Ltd.


517 Constants, Enumerations and Structures

int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing object anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Expansion
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create Fibonacci Expansion
if(!FiboExpansionCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRayLeft,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/10;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)

© 2000-2025, MetaQuotes Ltd.


518 Constants, Enumerations and Structures

p1-=1;
//--- move the point
if(!FiboExpansionPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/2;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3>1)
p3-=1;
//--- move the point
if(!FiboExpansionPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2<accuracy-1)
p2+=1;
//--- move the point
if(!FiboExpansionPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay

© 2000-2025, MetaQuotes Ltd.


519 Constants, Enumerations and Structures

Sleep(1000);
//--- delete the object from the chart
FiboExpansionDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


520 Constants, Enumerations and Structures

OBJ_ELLIOTWAVE5
Elliott Motive W ave.

Note

For "Elliott Motive W ave" , it is possible to enable/disable the mode of connecting points by lines
(OBJPROP_DRAW LINES property), as well as set the level of wave positioning (from
ENUM _ELLIOT _WAVE_DEGREE enumeration).

Example

The following script creates and moves Elliott motive wave on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Elliott Motive Wave\"."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ElliotWave5"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=90; // 1 st point's price, %
input int InpDate2=20; // 2 nd point's date, %
input int InpPrice2=40; // 2 nd point's price, %
input int InpDate3=30; // 3 rd point's date, %

© 2000-2025, MetaQuotes Ltd.


521 Constants, Enumerations and Structures

input int InpPrice3=60; // 3 rd point's price, %


input int InpDate4=40; // 4 th point's date, %
input int InpPrice4=10; // 4 th point's price, %
input int InpDate5=60; // 5 th point's date, %
input int InpPrice5=40; // 5 th point's price, %
input ENUM_ELLIOT_WAVE_DEGREE InpDegree=ELLIOTT_MINOR; // Level
input bool InpDrawLines=true; // Displaying the lines
input color InpColor=clrRed; // Color of the lines
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of the lines
input int InpWidth=2; // Width of the lines
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create "Elliott Motive Wave" by the given coordinates |
//+------------------------------------------------------------------+
bool ElliotWave5Create(const long chart_ID=0, // chart's ID
const string name="ElliotWave5", // wave name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
datetime time4=0, // fourth point time
double price4=0, // fourth point price
datetime time5=0, // fifth point time
double price5=0, // fifth point price
const ENUM_ELLIOT_WAVE_DEGREE degree=ELLIOTT_MINUETTE, // degree
const bool draw_lines=true, // displaying the lin
const color clr=clrRed, // object color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of the lines
const int width=1, // width of the lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the obje
const long z_order=0) // priority for mouse
{
//--- set anchor points' coordinates if they are not set
ChangeElliotWave5EmptyPoints(time1,price1,time2,price2,time3,price3,time4,price4,time5,price5);
//--- reset the error value
ResetLastError();
//--- Create "Elliott Motive Wave" by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_ELLIOTWAVE5,sub_window,time1,price1,time2,price2,time3,
price3,time4,price4,time5,price5))
{
Print(__FUNCTION__,

© 2000-2025, MetaQuotes Ltd.


522 Constants, Enumerations and Structures

": failed to create \"Elliott Motive Wave\"! Error code = ",GetLastError());


return(false);
}
//--- set degree (wave size)
ObjectSetInteger(chart_ID,name,OBJPROP_DEGREE,degree);
//--- enable (true) or disable (false) the mode of displaying the lines
ObjectSetInteger(chart_ID,name,OBJPROP_DRAWLINES,draw_lines);
//--- set the object's color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move anchor point of Elliott Motive Wave |
//+------------------------------------------------------------------+
bool ElliotWave5PointChange(const long chart_ID=0, // chart's ID
const string name="ElliotWave5", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());

© 2000-2025, MetaQuotes Ltd.


523 Constants, Enumerations and Structures

return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Elliott Motive Wave |
//+------------------------------------------------------------------+
bool ElliotWave5Delete(const long chart_ID=0, // chart's ID
const string name="ElliotWave5") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Elliott Motive Wave\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Elliott Motive Wave's anchor points and |
//| set default values for empty ones |
//+------------------------------------------------------------------+
void ChangeElliotWave5EmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2,
datetime &time3,double &price3,
datetime &time4,double &price4,
datetime &time5,double &price5)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[];
ArrayResize(temp,10);
//--- receive data
CopyTime(Symbol(),Period(),TimeCurrent(),10,temp);
//--- receive the value of one point on the current chart
double point=SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the first point's time is not set, it will be 9 bars left from the last bar
if(!time1)
time1=temp[0];
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it will be 7 bars left from the last bar
if(!time2)
time2=temp[2];

© 2000-2025, MetaQuotes Ltd.


524 Constants, Enumerations and Structures

//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*point;
//--- if the third point's time is not set, it will be 5 bars left from the last bar
if(!time3)
time3=temp[4];
//--- if the third point's price is not set, move it 250 points lower than the first one
if(!price3)
price3=price1-250*point;
//--- if the fourth point's time is not set, it will be 3 bars left from the last bar
if(!time4)
time4=temp[6];
//--- if the fourth point's price is not set, move it 550 points lower than the first one
if(!price4)
price4=price1-550*point;
//--- if the fifth point's time is not set, it will be on the last bar
if(!time5)
time5=temp[9];
//--- if the fifth point's price is not set, move it 450 points lower than the first one
if(!price5)
price5=price1-450*point;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100 ||
InpDate4<0 || InpDate4>100 || InpPrice4<0 || InpPrice4>100 ||
InpDate5<0 || InpDate5>100 || InpPrice5<0 || InpPrice5>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing object anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates

© 2000-2025, MetaQuotes Ltd.


525 Constants, Enumerations and Structures

ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Elliott Motive Wave
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int d4=InpDate4*(bars-1)/100;
int d5=InpDate5*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
int p4=InpPrice4*(accuracy-1)/100;
int p5=InpPrice5*(accuracy-1)/100;
//--- Create Elliott Motive Wave
if(!ElliotWave5Create(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
date[d4],price[p4],date[d5],price[p5],InpDegree,InpDrawLines,InpColor,InpStyle,InpWidth,
InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the fifth anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p5<accuracy-1)
p5+=1;
//--- move the point
if(!ElliotWave5PointChange(0,InpName,4,date[d5],price[p5]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())

© 2000-2025, MetaQuotes Ltd.


526 Constants, Enumerations and Structures

return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/5;
//--- move the second and third anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p2<accuracy-1)
p2+=1;
if(p3>1)
p3-=1;
//--- shift the points
if(!ElliotWave5PointChange(0,InpName,1,date[d2],price[p2]))
return;
if(!ElliotWave5PointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;
//--- move the first and fourth anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1>1)
p1-=1;
if(p4<accuracy-1)
p4+=1;
//--- shift the points
if(!ElliotWave5PointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!ElliotWave5PointChange(0,InpName,3,date[d4],price[p4]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();

© 2000-2025, MetaQuotes Ltd.


527 Constants, Enumerations and Structures

}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
ElliotWave5Delete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


528 Constants, Enumerations and Structures

OBJ_ELLIOTWAVE3
Elliott Correction W ave.

Note

For "Elliott Correction W ave" , it is possible to enable/disable the mode of connecting points by lines
(OBJPROP_DRAW LINES property), as well as set the level of wave positioning (from
ENUM _ELLIOT _WAVE_DEGREE enumeration).

Example

The following script creates and moves Elliott correction wave on the chart. S pecial functions have
been developed to create and change graphical object's properties. You can use these functions " as
is " in your own applications.

//--- description
#property description "Script draws \"Elliott Correction Wave\" graphical object."
#property description "Anchor point coordinates are set in percentage of the chart's window"
#property description "size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ElliotWave3"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=90; // 1 st point's price, %
input int InpDate2=30; // 2 nd point's date, %
input int InpPrice2=10; // 2 nd point's price, %
input int InpDate3=50; // 3 rd point's date, %

© 2000-2025, MetaQuotes Ltd.


529 Constants, Enumerations and Structures

input int InpPrice3=40; // 3 rd point's price, %


input ENUM_ELLIOT_WAVE_DEGREE InpDegree=ELLIOTT_MINOR; // Level
input bool InpDrawLines=true; // Displaying the lines
input color InpColor=clrRed; // Color of the lines
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of the lines
input int InpWidth=2; // Width of the lines
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create "Elliott Correction Wave" by the given coordinates |
//+------------------------------------------------------------------+
bool ElliotWave3Create(const long chart_ID=0, // chart's ID
const string name="ElliotWave3", // wave name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const ENUM_ELLIOT_WAVE_DEGREE degree=ELLIOTT_MINUETTE, // degree
const bool draw_lines=true, // displaying the lin
const color clr=clrRed, // object color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of the lines
const int width=1, // width of the lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the obje
const long z_order=0) // priority for mouse
{
//--- set anchor points' coordinates if they are not set
ChangeElliotWave3EmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- Create "Elliott Correction Wave" by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_ELLIOTWAVE3,sub_window,time1,price1,time2,price2,time3,price3
{
Print(__FUNCTION__,
": failed to create \"Elliott Correction Wave\"! Error code = ",GetLastError());
return(false);
}
//--- set degree (wave size)
ObjectSetInteger(chart_ID,name,OBJPROP_DEGREE,degree);
//--- enable (true) or disable (false) the mode of displaying the lines
ObjectSetInteger(chart_ID,name,OBJPROP_DRAWLINES,draw_lines);
//--- set the object's color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);

© 2000-2025, MetaQuotes Ltd.


530 Constants, Enumerations and Structures

//--- set the line style


ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move anchor point of Elliott Correction Wave |
//+------------------------------------------------------------------+
bool ElliotWave3PointChange(const long chart_ID=0, // chart's ID
const string name="ElliotWave3", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Elliott Correction Wave |
//+------------------------------------------------------------------+
bool ElliotWave3Delete(const long chart_ID=0, // chart's ID

© 2000-2025, MetaQuotes Ltd.


531 Constants, Enumerations and Structures

const string name="ElliotWave3") // object name


{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Elliott Correction Wave\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Elliott Correction Wave's anchor points |
//| and set default values for empty ones |
//+------------------------------------------------------------------+
void ChangeElliotWave3EmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2,
datetime &time3,double &price3)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[];
ArrayResize(temp,10);
//--- receive data
CopyTime(Symbol(),Period(),TimeCurrent(),10,temp);
//--- receive the value of one point on the current chart
double point=SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the first point's time is not set, it will be 9 bars left from the last bar
if(!time1)
time1=temp[0];
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it will be 5 bars left from the last bar
if(!time2)
time2=temp[4];
//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*point;
//--- if the third point's time is not set, it will be 1 bar left from the last bar
if(!time3)
time3=temp[8];
//--- if the third point's price is not set, move it 200 points lower than the first one
if(!price3)
price3=price1-200*point;
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


532 Constants, Enumerations and Structures

//| Script program start function |


//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing object anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Elliott Correction Wave
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- Create Elliott Correction Wave
if(!ElliotWave3Create(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpDegree,InpDrawLines,InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{

© 2000-2025, MetaQuotes Ltd.


533 Constants, Enumerations and Structures

return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3<accuracy-1)
p3+=1;
//--- move the point
if(!ElliotWave3PointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;
//--- move the first and second anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1>1)
p1-=1;
if(p2<accuracy-1)
p2+=1;
//--- shift the points
if(!ElliotWave3PointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!ElliotWave3PointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart

© 2000-2025, MetaQuotes Ltd.


534 Constants, Enumerations and Structures

ElliotWave3Delete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


535 Constants, Enumerations and Structures

OBJ_RECTANGLE
R ectangle.

Note

For rectangle, the mode of filling with color can be set using OBJPROP_FILL property.
Example

The following script creates and moves the rectangle on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script creates rectangle on the chart."
#property description "Anchor point coordinates are set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Rectangle"; // Rectangle name
input int InpDate1=40; // 1 st point's date, %
input int InpPrice1=40; // 1 st point's price, %
input int InpDate2=60; // 2 nd point's date, %
input int InpPrice2=60; // 2 nd point's price, %
input color InpColor=clrRed; // Rectangle color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of rectangle lines
input int InpWidth=2; // Width of rectangle lines

© 2000-2025, MetaQuotes Ltd.


536 Constants, Enumerations and Structures

input bool InpFill=true; // Filling the rectangle with color


input bool InpBack=false; // Background rectangle
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create rectangle by the given coordinates |
//+------------------------------------------------------------------+
bool RectangleCreate(const long chart_ID=0, // chart's ID
const string name="Rectangle", // rectangle name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // rectangle color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of rectangle lines
const int width=1, // width of rectangle lines
const bool fill=false, // filling rectangle with color
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeRectangleEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a rectangle by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create a rectangle! Error code = ",GetLastError());
return(false);
}
//--- set rectangle color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the style of rectangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the rectangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the rectangle
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the rectangle for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object

© 2000-2025, MetaQuotes Ltd.


537 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the rectangle anchor point |
//+------------------------------------------------------------------+
bool RectanglePointChange(const long chart_ID=0, // chart's ID
const string name="Rectangle", // rectangle name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the rectangle |
//+------------------------------------------------------------------+
bool RectangleDelete(const long chart_ID=0, // chart's ID
const string name="Rectangle") // rectangle name
{
//--- reset the error value
ResetLastError();
//--- delete rectangle
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete rectangle! Error code = ",GetLastError());
return(false);

© 2000-2025, MetaQuotes Ltd.


538 Constants, Enumerations and Structures

}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of rectangle's anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeRectangleEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing rectangle anchor points' coordinates
datetime date[];

© 2000-2025, MetaQuotes Ltd.


539 Constants, Enumerations and Structures

double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the rectangle
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create a rectangle
if(!RectangleCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,
InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the rectangle's anchor points
//--- loop counter
int h_steps=bars/2;
//--- move the anchor points
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2>1)
d2-=1;
//--- shift the points
if(!RectanglePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!RectanglePointChange(0,InpName,1,date[d2],price[p2]))
return;

© 2000-2025, MetaQuotes Ltd.


540 Constants, Enumerations and Structures

//--- check if the script's operation has been forcefully disabled


if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1<accuracy-1)
p1+=1;
if(p2>1)
p2-=1;
//--- shift the points
if(!RectanglePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!RectanglePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the rectangle from the chart
RectangleDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


541 Constants, Enumerations and Structures

OBJ_TRIANGLE
Triangle.

Note

For triangle, the mode of filling with color can be set using OBJPROP_FILL property.
Example

The following script creates and moves the triangle on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script creates triangle on the chart."
#property description "Anchor point coordinates are set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Triangle"; // Triangle name
input int InpDate1=25; // 1 st point's date, %
input int InpPrice1=50; // 1 st point's price, %
input int InpDate2=70; // 2 nd point's date, %
input int InpPrice2=70; // 2 nd point's price, %
input int InpDate3=65; // 3 rd point's date, %
input int InpPrice3=20; // 3 rd point's price, %
input color InpColor=clrRed; // Triangle color

© 2000-2025, MetaQuotes Ltd.


542 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of triangle lines


input int InpWidth=2; // Width of triangle lines
input bool InpFill=false; // Filling triangle with color
input bool InpBack=false; // Background triangle
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create triangle by the given coordinates |
//+------------------------------------------------------------------+
bool TriangleCreate(const long chart_ID=0, // chart's ID
const string name="Triangle", // triangle name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // triangle color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of triangle lines
const int width=1, // width of triangle lines
const bool fill=false, // filling triangle with color
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeTriangleEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create triangle by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_TRIANGLE,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create a triangle! Error code = ",GetLastError());
return(false);
}
//--- set triangle color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of triangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of triangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the triangle
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);

© 2000-2025, MetaQuotes Ltd.


543 Constants, Enumerations and Structures

//--- enable (true) or disable (false) the mode of highlighting the triangle for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the triangle anchor point |
//+------------------------------------------------------------------+
bool TrianglePointChange(const long chart_ID=0, // chart's ID
const string name="Triangle", // triangle name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the triangle |
//+------------------------------------------------------------------+
bool TriangleDelete(const long chart_ID=0, // chart's ID
const string name="Triangle") // triangle name
{
//--- reset the error value
ResetLastError();
//--- delete the triangle
if(!ObjectDelete(chart_ID,name))

© 2000-2025, MetaQuotes Ltd.


544 Constants, Enumerations and Structures

{
Print(__FUNCTION__,
": failed to delete the ellipse! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of triangle's anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeTriangleEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2,
datetime &time3,double &price3)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the second point's date
if(!time3)
time3=time2;
//--- if the third point's price is not set, it is equal to the first point's one
if(!price3)
price3=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||

© 2000-2025, MetaQuotes Ltd.


545 Constants, Enumerations and Structures

InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)


{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing triangle anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the triangle
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create a triangle
if(!TriangleCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the triangle anchor points
//--- loop counter

© 2000-2025, MetaQuotes Ltd.


546 Constants, Enumerations and Structures

int v_steps=accuracy*3/10;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!TrianglePointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars*9/20-1;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2>1)
d2-=1;
//--- move the point
if(!TrianglePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/4;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3<accuracy-1)
p3+=1;
//--- move the point
if(!TrianglePointChange(0,InpName,2,date[d3],price[p3]))

© 2000-2025, MetaQuotes Ltd.


547 Constants, Enumerations and Structures

return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete triangle from the chart
TriangleDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


548 Constants, Enumerations and Structures

OBJ_ELLIPSE
Ellipse.

Note

For ellipse, the mode of filling with color can be set using OBJPROP_FILL property.
Example

The following script creates and moves the ellipse on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.
//--- description
#property description "Script creates ellipse on the chart."
#property description "Anchor point coordinates are set"
#property description "in percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Ellipse"; // Ellipse name
input int InpDate1=30; // 1 st point's date, %
input int InpPrice1=20; // 1 st point's price, %
input int InpDate2=70; // 2 nd point's date, %
input int InpPrice2=80; // 2 nd point's price, %
input int InpDate3=50; // 3 rd point's date, %
input int InpPrice3=60; // 3 rd point's price, %
input color InpColor=clrRed; // Ellipse color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of ellipse lines

© 2000-2025, MetaQuotes Ltd.


549 Constants, Enumerations and Structures

input int InpWidth=2; // Width of ellipse lines


input bool InpFill=false; // Filling ellipse with color
input bool InpBack=false; // Background ellipse
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create an ellipse by the given coordinates |
//+------------------------------------------------------------------+
bool EllipseCreate(const long chart_ID=0, // chart's ID
const string name="Ellipse", // ellipse name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // ellipse color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of ellipse lines
const int width=1, // width of ellipse lines
const bool fill=false, // filling ellipse with color
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeEllipseEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create an ellipse by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_ELLIPSE,sub_window,time1,price1,time2,price2,time3,price3))
{
Print(__FUNCTION__,
": failed to create an ellipse! Error code = ",GetLastError());
return(false);
}
//--- set an ellipse color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of ellipse lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of ellipse lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the ellipse
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the ellipse for moving

© 2000-2025, MetaQuotes Ltd.


550 Constants, Enumerations and Structures

//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the ellipse anchor point |
//+------------------------------------------------------------------+
bool EllipsePointChange(const long chart_ID=0, // chart's ID
const string name="Ellipse", // ellipse name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete ellipse |
//+------------------------------------------------------------------+
bool EllipseDelete(const long chart_ID=0, // chart's ID
const string name="Ellipse") // ellipse name
{
//--- reset the error value
ResetLastError();
//--- delete an ellipse
if(!ObjectDelete(chart_ID,name))
{

© 2000-2025, MetaQuotes Ltd.


551 Constants, Enumerations and Structures

Print(__FUNCTION__,
": failed to delete an ellipse! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of ellipse anchor points and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeEllipseEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2,
datetime &time3,double &price3)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the second point's date
if(!time3)
time3=time2;
//--- if the third point's price is not set, it is equal to the first point's one
if(!price3)
price3=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)

© 2000-2025, MetaQuotes Ltd.


552 Constants, Enumerations and Structures

{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing ellipse anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the ellipse
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create an ellipse
if(!EllipseCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price[p3],
InpColor,InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the ellipse anchor points
//--- loop counter
int v_steps=accuracy/5;

© 2000-2025, MetaQuotes Ltd.


553 Constants, Enumerations and Structures

//--- move the first and second anchor points


for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1<accuracy-1)
p1+=1;
if(p2>1)
p2-=1;
//--- shift the points
if(!EllipsePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!EllipsePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/5;
//--- move the third anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d3>1)
d3-=1;
//--- move the point
if(!EllipsePointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete ellipse from the chart
EllipseDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


554 Constants, Enumerations and Structures

OBJ_ARROW_THUMB_UP
Thumbs Up sign.

Note

Anchor point position relative to the sign can be selected from ENUM _ARR OW_ANCH OR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_W IDTH property
value when writing a code in MetaEditor.
Example

The following script creates and moves Thumbs Up sign on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Thumbs Up\" sign."
#property description "Anchor point coordinate is set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ThumbUp"; // Sign name
input int InpDate=75; // Anchor point date in %
input int InpPrice=25; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type
input color InpColor=clrRed; // Sign color

© 2000-2025, MetaQuotes Ltd.


555 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style


input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Thumbs Up sign |
//+------------------------------------------------------------------+
bool ArrowThumbUpCreate(const long chart_ID=0, // chart's ID
const string name="ThumbUp", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=3, // sign size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_THUMB_UP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Thumbs Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);

© 2000-2025, MetaQuotes Ltd.


556 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowThumbUpMove(const long chart_ID=0, // chart's ID
const string name="ThumbUp", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Thumbs Up sign anchor type |
//+------------------------------------------------------------------+
bool ArrowThumbUpAnchorChange(const long chart_ID=0, // chart's ID
const string name="ThumbUp", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}

© 2000-2025, MetaQuotes Ltd.


557 Constants, Enumerations and Structures

//--- successful execution


return(true);
}
//+------------------------------------------------------------------+
//| Delete Thumbs Up sign |
//+------------------------------------------------------------------+
bool ArrowThumbUpDelete(const long chart_ID=0, // chart's ID
const string name="ThumbUp") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Thumbs Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;

© 2000-2025, MetaQuotes Ltd.


558 Constants, Enumerations and Structures

//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Thumbs Up sign on the chart
if(!ArrowThumbUpCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars/4;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d>1)
d-=1;
//--- move the point
if(!ArrowThumbUpMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;

© 2000-2025, MetaQuotes Ltd.


559 Constants, Enumerations and Structures

//--- redraw the chart


ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/4;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!ArrowThumbUpMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- change anchor point location relative to the sign
ArrowThumbUpAnchorChange(0,InpName,ANCHOR_BOTTOM);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowThumbUpDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


560 Constants, Enumerations and Structures

OBJ_ARROW_THUMB_DOWN
Thumbs Down sign.

Note

Anchor point position relative to the sign can be selected from ENUM _ARR OW_ANCH OR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_W IDTH property
value when writing a code in MetaEditor.
Example

The following script creates and moves Thumbs Down sign on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Thumbs Down\" sign."
#property description "Anchor point coordinate is set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ThumbDown"; // Sign name
input int InpDate=25; // Anchor point date in %
input int InpPrice=75; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_BOTTOM; // Anchor type

© 2000-2025, MetaQuotes Ltd.


561 Constants, Enumerations and Structures

input color InpColor=clrRed; // Sign color


input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style
input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Thumbs Down sign |
//+------------------------------------------------------------------+
bool ArrowThumbDownCreate(const long chart_ID=0, // chart's ID
const string name="ThumbDown", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=3, // sign size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object lis
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_THUMB_DOWN,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Thumbs Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object

© 2000-2025, MetaQuotes Ltd.


562 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowThumbDownMove(const long chart_ID=0, // chart's ID
const string name="ThumbDown", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Thumbs Down sign anchor type |
//+------------------------------------------------------------------+
bool ArrowThumbDownAnchorChange(const long chart_ID=0, // chart's ID
const string name="ThumbDown", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);

© 2000-2025, MetaQuotes Ltd.


563 Constants, Enumerations and Structures

}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Thumbs Down sign |
//+------------------------------------------------------------------+
bool ArrowThumbDownDelete(const long chart_ID=0, // chart's ID
const string name="ThumbDown") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Thumbs Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size

© 2000-2025, MetaQuotes Ltd.


564 Constants, Enumerations and Structures

int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Thumbs Down sign on the chart
if(!ArrowThumbDownCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars/4;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowThumbDownMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())

© 2000-2025, MetaQuotes Ltd.


565 Constants, Enumerations and Structures

return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/4;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p>1)
p-=1;
//--- move the point
if(!ArrowThumbDownMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- change anchor point location relative to the sign
ArrowThumbDownAnchorChange(0,InpName,ANCHOR_TOP);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowThumbDownDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


566 Constants, Enumerations and Structures

OBJ_ARROW_UP
Arrow Up sign.

Note

Anchor point position relative to the sign can be selected from ENUM _ARR OW_ANCH OR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_W IDTH property
value when writing a code in MetaEditor.
Example

The following script creates and moves Arrow Up sign on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Arrow Up\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ArrowUp"; // Sign name
input int InpDate=25; // Anchor point date in %
input int InpPrice=25; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type
input color InpColor=clrRed; // Sign color

© 2000-2025, MetaQuotes Ltd.


567 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style


input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Arrow Up sign |
//+------------------------------------------------------------------+
bool ArrowUpCreate(const long chart_ID=0, // chart's ID
const string name="ArrowUp", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=3, // sign size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_UP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Arrow Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);

© 2000-2025, MetaQuotes Ltd.


568 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowUpMove(const long chart_ID=0, // chart's ID
const string name="ArrowUp", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Arrow Down sign anchor type |
//+------------------------------------------------------------------+
bool ArrowUpAnchorChange(const long chart_ID=0, // chart's ID
const string name="ArrowUp", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor point location
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}

© 2000-2025, MetaQuotes Ltd.


569 Constants, Enumerations and Structures

//--- successful execution


return(true);
}
//+------------------------------------------------------------------+
//| Delete Arrow Up sign |
//+------------------------------------------------------------------+
bool ArrowUpDelete(const long chart_ID=0, // chart's ID
const string name="ArrowUp") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Arrow Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;

© 2000-2025, MetaQuotes Ltd.


570 Constants, Enumerations and Structures

//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Arrow Up sign on the chart
if(!ArrowUpCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!ArrowUpMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;

© 2000-2025, MetaQuotes Ltd.


571 Constants, Enumerations and Structures

//--- redraw the chart


ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- change anchor point location relative to the sign
ArrowUpAnchorChange(0,InpName,ANCHOR_BOTTOM);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowUpDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


572 Constants, Enumerations and Structures

OBJ_ARROW_DOWN
Arrow Down sign.

Note

Anchor point position relative to the sign can be selected from ENUM _ARR OW_ANCH OR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_W IDTH property
value when writing a code in MetaEditor.
Example

The following script creates and moves Arrow Down sign on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.
//--- description
#property description "Script draws \"Arrow Down\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ArrowDown"; // Sign name
input int InpDate=75; // Anchor point date in %
input int InpPrice=75; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_BOTTOM; // Anchor type
input color InpColor=clrRed; // Sign color
input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style

© 2000-2025, MetaQuotes Ltd.


573 Constants, Enumerations and Structures

input int InpWidth=5; // Sign size


input bool InpBack=false; // Background sign
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Arrow Down sign |
//+------------------------------------------------------------------+
bool ArrowDownCreate(const long chart_ID=0, // chart's ID
const string name="ArrowDown", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=3, // sign size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_DOWN,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Arrow Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);

© 2000-2025, MetaQuotes Ltd.


574 Constants, Enumerations and Structures

//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowDownMove(const long chart_ID=0, // chart's ID
const string name="ArrowDown", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Arrow Down sign anchor type |
//+------------------------------------------------------------------+
bool ArrowDownAnchorChange(const long chart_ID=0, // chart's ID
const string name="ArrowDown", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor point location
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution

© 2000-2025, MetaQuotes Ltd.


575 Constants, Enumerations and Structures

return(true);
}
//+------------------------------------------------------------------+
//| Delete Arrow Down sign |
//+------------------------------------------------------------------+
bool ArrowDownDelete(const long chart_ID=0, // chart's ID
const string name="ArrowDown") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Arrow Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used

© 2000-2025, MetaQuotes Ltd.


576 Constants, Enumerations and Structures

//--- for setting and changing sign anchor point coordinates


datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Arrow Down sign on the chart
if(!ArrowDownCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p>1)
p-=1;
//--- move the point
if(!ArrowDownMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart

© 2000-2025, MetaQuotes Ltd.


577 Constants, Enumerations and Structures

ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- change anchor point location relative to the sign
ArrowDownAnchorChange(0,InpName,ANCHOR_TOP);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowDownDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


578 Constants, Enumerations and Structures

OBJ_ARROW_STOP
S top sign.

Note

Anchor point position relative to the sign can be selected from ENUM _ARR OW_ANCH OR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_W IDTH property
value when writing a code in MetaEditor.
Example

The following script creates and moves S top sign on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Stop\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ArrowStop"; // Sign name
input int InpDate=10; // Anchor point date in %
input int InpPrice=50; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_BOTTOM; // Anchor type
input color InpColor=clrRed; // Sign color

© 2000-2025, MetaQuotes Ltd.


579 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style


input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Stop sign |
//+------------------------------------------------------------------+
bool ArrowStopCreate(const long chart_ID=0, // chart's ID
const string name="ArrowStop", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=3, // sign size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_STOP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Stop\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);

© 2000-2025, MetaQuotes Ltd.


580 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowStopMove(const long chart_ID=0, // chart's ID
const string name="ArrowStop", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Stop sign anchor type |
//+------------------------------------------------------------------+
bool ArrowStopAnchorChange(const long chart_ID=0, // chart's ID
const string name="ArrowStop", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor point position
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}

© 2000-2025, MetaQuotes Ltd.


581 Constants, Enumerations and Structures

//--- successful execution


return(true);
}
//+------------------------------------------------------------------+
//| Delete Stop sign |
//+------------------------------------------------------------------+
bool ArrowStopDelete(const long chart_ID=0, // chart's ID
const string name="ArrowStop") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Stop\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;

© 2000-2025, MetaQuotes Ltd.


582 Constants, Enumerations and Structures

//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Stop sign on the chart
if(!ArrowStopCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowStopMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;

© 2000-2025, MetaQuotes Ltd.


583 Constants, Enumerations and Structures

//--- redraw the chart


ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- change anchor point location relative to the sign
ArrowStopAnchorChange(0,InpName,ANCHOR_TOP);
//--- redraw the chart
ChartRedraw();
//--- loop counter
h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowStopMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowStopDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


584 Constants, Enumerations and Structures

OBJ_ARROW_CHECK
Check sign.

Note

Anchor point position relative to the sign can be selected from ENUM _ARR OW_ANCH OR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate OBJPROP_W IDTH property
value when writing a code in MetaEditor.
Example

The following script creates and moves Check sign on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Check\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ArrowCheck"; // Sign name
input int InpDate=10; // Anchor point date in %
input int InpPrice=50; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type
input color InpColor=clrRed; // Sign color

© 2000-2025, MetaQuotes Ltd.


585 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style


input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Check sign |
//+------------------------------------------------------------------+
bool ArrowCheckCreate(const long chart_ID=0, // chart's ID
const string name="ArrowCheck", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=3, // sign size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_CHECK,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Check\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);

© 2000-2025, MetaQuotes Ltd.


586 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowCheckMove(const long chart_ID=0, // chart's ID
const string name="ArrowCheck", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Check anchor type |
//+------------------------------------------------------------------+
bool ArrowCheckAnchorChange(const long chart_ID=0, // chart's ID
const string name="ArrowCheck", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}

© 2000-2025, MetaQuotes Ltd.


587 Constants, Enumerations and Structures

//--- successful execution


return(true);
}
//+------------------------------------------------------------------+
//| Delete Check sign |
//+------------------------------------------------------------------+
bool ArrowCheckDelete(const long chart_ID=0, // chart's ID
const string name="ArrowCheck") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Check\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;

© 2000-2025, MetaQuotes Ltd.


588 Constants, Enumerations and Structures

//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Check sign on the chart
if(!ArrowCheckCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowCheckMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;

© 2000-2025, MetaQuotes Ltd.


589 Constants, Enumerations and Structures

//--- redraw the chart


ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- change anchor point location relative to the sign
ArrowCheckAnchorChange(0,InpName,ANCHOR_BOTTOM);
//--- redraw the chart
ChartRedraw();
//--- loop counter
h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowCheckMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowCheckDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


590 Constants, Enumerations and Structures

OBJ_ARROW_LEFT_PRICE
Left Price Label

Example

The following script creates and moves left price label on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script creates the left price label on the chart."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="LeftPrice"; // Price label name
input int InpDate=100; // Anchor point date in %
input int InpPrice=10; // Anchor point price in %
input color InpColor=clrRed; // Price label color
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Border line style
input int InpWidth=2; // Price label size
input bool InpBack=false; // Background label
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the left price label |

© 2000-2025, MetaQuotes Ltd.


591 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
bool ArrowLeftPriceCreate(const long chart_ID=0, // chart's ID
const string name="LeftPrice", // price label name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const color clr=clrRed, // price label color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=1, // price label size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create a price label
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_LEFT_PRICE,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create the left price label! Error code = ",GetLastError());
return(false);
}
//--- set the label color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the label size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


592 Constants, Enumerations and Structures

bool ArrowLeftPriceMove(const long chart_ID=0, // chart's ID


const string name="LeftPrice", // label name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the left price label from the chart |
//+------------------------------------------------------------------+
bool ArrowLeftPriceDelete(const long chart_ID=0, // chart's ID
const string name="LeftPrice") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the left price label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();

© 2000-2025, MetaQuotes Ltd.


593 Constants, Enumerations and Structures

//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing label anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the label
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create the left price label on the chart
if(!ArrowLeftPriceCreate(0,InpName,0,date[d],price[p],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;

© 2000-2025, MetaQuotes Ltd.


594 Constants, Enumerations and Structures

}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point
//--- loop counter
int v_steps=accuracy*4/5;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!ArrowLeftPriceMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the label from the chart
ArrowLeftPriceDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


595 Constants, Enumerations and Structures

OBJ_ARROW_RIGHT_PRICE
R ight Price Label.

Example

The following script creates and moves right price label on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script creates the right price label on the chart."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="RightPrice"; // Price label name
input int InpDate=0; // Anchor point date in %
input int InpPrice=90; // Anchor point price in %
input color InpColor=clrRed; // Price label color
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Border line style
input int InpWidth=2; // Price label size
input bool InpBack=false; // Background label
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the right price label |

© 2000-2025, MetaQuotes Ltd.


596 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
bool ArrowRightPriceCreate(const long chart_ID=0, // chart's ID
const string name="RightPrice", // price label name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const color clr=clrRed, // price label color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=1, // price label size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create a price label
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_RIGHT_PRICE,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create the right price label! Error code = ",GetLastError());
return(false);
}
//--- set the label color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the label size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


597 Constants, Enumerations and Structures

bool ArrowRightPriceMove(const long chart_ID=0, // chart's ID


const string name="RightPrice", // label name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the right price label from the chart |
//+------------------------------------------------------------------+
bool ArrowRightPriceDelete(const long chart_ID=0, // chart's ID
const string name="RightPrice") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the right price label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();

© 2000-2025, MetaQuotes Ltd.


598 Constants, Enumerations and Structures

//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing label anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the label
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create the right price label on the chart
if(!ArrowRightPriceCreate(0,InpName,0,date[d],price[p],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;

© 2000-2025, MetaQuotes Ltd.


599 Constants, Enumerations and Structures

}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point
//--- loop counter
int v_steps=accuracy*4/5;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p>1)
p-=1;
//--- move the point
if(!ArrowRightPriceMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the label from the chart
ArrowRightPriceDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


600 Constants, Enumerations and Structures

OBJ_ARROW_BUY
Buy sign.

Example

The following script creates and moves Buy sign on the chart. S pecial functions have been developed
to create and change graphical object's properties. You can use these functions " as is " in your own
applications.

//--- description
#property description "Script draws \"Buy\" signs in the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input color InpColor=C'3,95,172'; // Color of signs
//+------------------------------------------------------------------+
//| Create Buy sign |
//+------------------------------------------------------------------+
bool ArrowBuyCreate(const long chart_ID=0, // chart's ID
const string name="ArrowBuy", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const color clr=C'3,95,172', // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style (when highlighted)
const int width=1, // line size (when highlighted)
const bool back=false, // in the background
const bool selection=false, // highlight to move

© 2000-2025, MetaQuotes Ltd.


601 Constants, Enumerations and Structures

const bool hidden=true, // hidden in the object list


const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_BUY,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Buy\" sign! Error code = ",GetLastError());
return(false);
}
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set a line style (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a line size (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowBuyMove(const long chart_ID=0, // chart's ID
const string name="ArrowBuy", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))

© 2000-2025, MetaQuotes Ltd.


602 Constants, Enumerations and Structures

{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Buy sign |
//+------------------------------------------------------------------+
bool ArrowBuyDelete(const long chart_ID=0, // chart's ID
const string name="ArrowBuy") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Buy\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double low[]; // array for storing Low prices of visible bars
double high[]; // array for storing High prices of visible bars
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);

© 2000-2025, MetaQuotes Ltd.


603 Constants, Enumerations and Structures

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(low,bars);
ArrayResize(high,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of Low prices
if(CopyLow(Symbol(),Period(),0,bars,low)==-1)
{
Print("Failed to copy the values of Low prices! Error code = ",GetLastError());
return;
}
//--- fill the array of High prices
if(CopyHigh(Symbol(),Period(),0,bars,high)==-1)
{
Print("Failed to copy the values of High prices! Error code = ",GetLastError());
return;
}
//--- create Buy signs in Low point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowBuyCreate(0,"ArrowBuy_"+(string)i,0,date[i],low[i],InpColor))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- move Buy signs to High point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowBuyMove(0,"ArrowBuy_"+(string)i,date[i],high[i]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}

© 2000-2025, MetaQuotes Ltd.


604 Constants, Enumerations and Structures

//--- delete Buy signs


for(int i=0;i<bars;i++)
{
if(!ArrowBuyDelete(0,"ArrowBuy_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//---
}

© 2000-2025, MetaQuotes Ltd.


605 Constants, Enumerations and Structures

OBJ_ARROW_SELL
S ell sign.

Example

The following script creates and moves S ell sign on the chart. S pecial functions have been developed
to create and change graphical object's properties. You can use these functions " as is " in your own
applications.

//--- description
#property description "Script draws \"Sell\" signs in the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input color InpColor=C'225,68,29'; // Color of signs
//+------------------------------------------------------------------+
//| Create Sell sign |
//+------------------------------------------------------------------+
bool ArrowSellCreate(const long chart_ID=0, // chart's ID
const string name="ArrowSell", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const color clr=C'225,68,29', // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style (when highlighted)
const int width=1, // line size (when highlighted)
const bool back=false, // in the background
const bool selection=false, // highlight to move

© 2000-2025, MetaQuotes Ltd.


606 Constants, Enumerations and Structures

const bool hidden=true, // hidden in the object list


const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_SELL,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Sell\" sign! Error code = ",GetLastError());
return(false);
}
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set a line style (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a line size (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowSellMove(const long chart_ID=0, // chart's ID
const string name="ArrowSell", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))

© 2000-2025, MetaQuotes Ltd.


607 Constants, Enumerations and Structures

{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Sell sign |
//+------------------------------------------------------------------+
bool ArrowSellDelete(const long chart_ID=0, // chart's ID
const string name="ArrowSell") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Sell\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double low[]; // array for storing Low prices of visible bars
double high[]; // array for storing High prices of visible bars
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);

© 2000-2025, MetaQuotes Ltd.


608 Constants, Enumerations and Structures

//--- memory allocation


ArrayResize(date,bars);
ArrayResize(low,bars);
ArrayResize(high,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of Low prices
if(CopyLow(Symbol(),Period(),0,bars,low)==-1)
{
Print("Failed to copy the values of Low prices! Error code = ",GetLastError());
return;
}
//--- fill the array of High prices
if(CopyHigh(Symbol(),Period(),0,bars,high)==-1)
{
Print("Failed to copy the values of High prices! Error code = ",GetLastError());
return;
}
//--- create Sell signs in High point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowSellCreate(0,"ArrowSell_"+(string)i,0,date[i],high[i],InpColor))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- move Sell signs to Low point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowSellMove(0,"ArrowSell_"+(string)i,date[i],low[i]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}

© 2000-2025, MetaQuotes Ltd.


609 Constants, Enumerations and Structures

//--- delete Sell signs


for(int i=0;i<bars;i++)
{
if(!ArrowSellDelete(0,"ArrowSell_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//---
}

© 2000-2025, MetaQuotes Ltd.


610 Constants, Enumerations and Structures

OBJ_ARROW
Arrow object.

Note

Anchor point position relative to the object can be selected from ENUM _ARROW_ANCHOR.
Large arrows (more than 5) can only be created by setting the appropriate OBJPROP_W IDTH property
value when writing a code in MetaEditor.
The necessary arrow type can be selected by setting one of the W ingdings font's symbol codes.
Example

The following script creates Arrow object on the chart and changes its type. S pecial functions have
been developed to create and change graphical object's properties. You can use these functions " as
is " in your own applications.

//--- description
#property description "Script creates a random arrow in the chart window."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Arrow"; // Arrow name
input int InpDate=50; // Anchor point date in %
input int InpPrice=50; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type

© 2000-2025, MetaQuotes Ltd.


611 Constants, Enumerations and Structures

input color InpColor=clrDodgerBlue; // Arrow color


input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Border line style
input int InpWidth=10; // Arrow size
input bool InpBack=false; // Background arrow
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the arrow |
//+------------------------------------------------------------------+
bool ArrowCreate(const long chart_ID=0, // chart's ID
const string name="Arrow", // arrow name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const uchar arrow_code=252, // arrow code
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor point position
const color clr=clrRed, // arrow color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=3, // arrow size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create an arrow
if(!ObjectCreate(chart_ID,name,OBJ_ARROW,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create an arrow! Error code = ",GetLastError());
return(false);
}
//--- set the arrow code
ObjectSetInteger(chart_ID,name,OBJPROP_ARROWCODE,arrow_code);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set the arrow color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the arrow's size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the arrow by mouse

© 2000-2025, MetaQuotes Ltd.


612 Constants, Enumerations and Structures

//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowMove(const long chart_ID=0, // chart's ID
const string name="Arrow", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the arrow code |
//+------------------------------------------------------------------+
bool ArrowCodeChange(const long chart_ID=0, // chart's ID
const string name="Arrow", // object name
const uchar code=252) // arrow code
{
//--- reset the error value
ResetLastError();
//--- change the arrow code
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ARROWCODE,code))
{

© 2000-2025, MetaQuotes Ltd.


613 Constants, Enumerations and Structures

Print(__FUNCTION__,
": failed to change the arrow code! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change anchor type |
//+------------------------------------------------------------------+
bool ArrowAnchorChange(const long chart_ID=0, // chart's ID
const string name="Arrow", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete an arrow |
//+------------------------------------------------------------------+
bool ArrowDelete(const long chart_ID=0, // chart's ID
const string name="Arrow") // arrow name
{
//--- reset the error value
ResetLastError();
//--- delete an arrow
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete an arrow! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)

© 2000-2025, MetaQuotes Ltd.


614 Constants, Enumerations and Structures

{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the arrow
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create an arrow on the chart

© 2000-2025, MetaQuotes Ltd.


615 Constants, Enumerations and Structures

if(!ArrowCreate(0,InpName,0,date[d],price[p],32,InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart
ChartRedraw();
//--- consider all cases of creating arrows in the loop
for(int i=33;i<256;i++)
{
if(!ArrowCodeChange(0,InpName,(uchar)i))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// half a second of delay
Sleep(500);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the arrow from the chart
ArrowDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


616 Constants, Enumerations and Structures

OBJ_TEXT
Text object.

Note

Anchor point position relative to the text can be selected from ENUM _ANCH OR_POINT enumeration.
You can also change text slope angle using OBJPR OP_ANGL E property.

Example

The following script creates several Text objects on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script creates \"Text\" graphical object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpFont="Arial"; // Font
input int InpFontSize=10; // Font size
input color InpColor=clrRed; // Color
input double InpAngle=90.0; // Slope angle in degrees
input ENUM_ANCHOR_POINT InpAnchor=ANCHOR_LEFT; // Anchor type
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click

© 2000-2025, MetaQuotes Ltd.


617 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
//| Creating Text object |
//+------------------------------------------------------------------+
bool TextCreate(const long chart_ID=0, // chart's ID
const string name="Text", // object name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const string text="Text", // the text itself
const string font="Arial", // font
const int font_size=10, // font size
const color clr=clrRed, // color
const double angle=0.0, // text slope
const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeTextEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create Text object
if(!ObjectCreate(chart_ID,name,OBJ_TEXT,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Text\" object! Error code = ",GetLastError());
return(false);
}
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the slope angle of the text
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the object by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);

© 2000-2025, MetaQuotes Ltd.


618 Constants, Enumerations and Structures

//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool TextMove(const long chart_ID=0, // chart's ID
const string name="Text", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the object text |
//+------------------------------------------------------------------+
bool TextChange(const long chart_ID=0, // chart's ID
const string name="Text", // object name
const string text="Text") // text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}

© 2000-2025, MetaQuotes Ltd.


619 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
//| Delete Text object |
//+------------------------------------------------------------------+
bool TextDelete(const long chart_ID=0, // chart's ID
const string name="Text") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Text\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeTextEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double low[]; // array for storing Low prices of visible bars
double high[]; // array for storing High prices of visible bars
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(low,bars);
ArrayResize(high,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{

© 2000-2025, MetaQuotes Ltd.


620 Constants, Enumerations and Structures

Print("Failed to copy time values! Error code = ",GetLastError());


return;
}
//--- fill the array of Low prices
if(CopyLow(Symbol(),Period(),0,bars,low)==-1)
{
Print("Failed to copy the values of Low prices! Error code = ",GetLastError());
return;
}
//--- fill the array of High prices
if(CopyHigh(Symbol(),Period(),0,bars,high)==-1)
{
Print("Failed to copy the values of High prices! Error code = ",GetLastError());
return;
}
//--- define how often texts are to be displayed
int scale=(int)ChartGetInteger(0,CHART_SCALE);
//--- define the step
int step=1;
switch(scale)
{
case 0:
step=12;
break;
case 1:
step=6;
break;
case 2:
step=4;
break;
case 3:
step=2;
break;
}
//--- create texts for High and Low bars' values (with gaps)
for(int i=0;i<bars;i+=step)
{
//--- create the texts
if(!TextCreate(0,"TextHigh_"+(string)i,0,date[i],high[i],DoubleToString(high[i],5),InpFont,In
InpColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
if(!TextCreate(0,"TextLow_"+(string)i,0,date[i],low[i],DoubleToString(low[i],5),InpFont,InpFo
InpColor,-InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- check if the script's operation has been forcefully disabled

© 2000-2025, MetaQuotes Ltd.


621 Constants, Enumerations and Structures

if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- half a second of delay
Sleep(500);
//--- delete the texts
for(int i=0;i<bars;i+=step)
{
if(!TextDelete(0,"TextHigh_"+(string)i))
return;
if(!TextDelete(0,"TextLow_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//---
}

© 2000-2025, MetaQuotes Ltd.


622 Constants, Enumerations and Structures

OBJ_LABEL
Label object.

Note

Anchor point position relative to the label can be selected from ENUM _ANCHOR_POINT enumeration.
Anchor point coordinates are set in pixels.
You can also select text label anchoring corner from ENUM _BASE_CORNER enumeration.
Example

The following script creates and moves Edit object on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script creates \"Label\" graphical object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Label"; // Label name
input int InpX=150; // X-axis distance
input int InpY=150; // Y-axis distance
input string InpFont="Arial"; // Font
input int InpFontSize=14; // Font size
input color InpColor=clrRed; // Color
input double InpAngle=0.0; // Slope angle in degrees
input ENUM_ANCHOR_POINT InpAnchor=ANCHOR_CENTER; // Anchor type

© 2000-2025, MetaQuotes Ltd.


623 Constants, Enumerations and Structures

input bool InpBack=false; // Background object


input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create a text label |
//+------------------------------------------------------------------+
bool LabelCreate(const long chart_ID=0, // chart's ID
const string name="Label", // label name
const int sub_window=0, // subwindow index
const int x=0, // X coordinate
const int y=0, // Y coordinate
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner for anchoring
const string text="Label", // text
const string font="Arial", // font
const int font_size=10, // font size
const color clr=clrRed, // color
const double angle=0.0, // text slope
const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- reset the error value
ResetLastError();
//--- create a text label
if(!ObjectCreate(chart_ID,name,OBJ_LABEL,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create text label! Error code = ",GetLastError());
return(false);
}
//--- set label coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the slope angle of the text
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set color

© 2000-2025, MetaQuotes Ltd.


624 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the text label |
//+------------------------------------------------------------------+
bool LabelMove(const long chart_ID=0, // chart's ID
const string name="Label", // label name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the text label
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the label! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change corner of the chart for binding the label |
//+------------------------------------------------------------------+
bool LabelChangeCorner(const long chart_ID=0, // chart's ID
const string name="Label", // label name
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER) // chart corner for anchori
{
//--- reset the error value
ResetLastError();
//--- change anchor corner

© 2000-2025, MetaQuotes Ltd.


625 Constants, Enumerations and Structures

if(!ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner))
{
Print(__FUNCTION__,
": failed to change the anchor corner! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the label text |
//+------------------------------------------------------------------+
bool LabelTextChange(const long chart_ID=0, // chart's ID
const string name="Label", // object name
const string text="Text") // text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete a text label |
//+------------------------------------------------------------------+
bool LabelDelete(const long chart_ID=0, // chart's ID
const string name="Label") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a text label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


626 Constants, Enumerations and Structures

void OnStart()
{
//--- store the label's coordinates in the local variables
int x=InpX;
int y=InpY;
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- check correctness of the input parameters
if(InpX<0 || InpX>x_distance-1 || InpY<0 || InpY>y_distance-1)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- prepare initial text for the label
string text;
StringConcatenate(text,"Upper left corner: ",x,",",y);
//--- create a text label on the chart
if(!LabelCreate(0,InpName,0,InpX,InpY,CORNER_LEFT_UPPER,text,InpFont,InpFontSize,
InpColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for half a second
ChartRedraw();
Sleep(500);
//--- move the label and change its text simultaneously
//--- number of iterations by axes
int h_steps=(int)(x_distance/2-InpX);
int v_steps=(int)(y_distance/2-InpY);
//--- move the label down
for(int i=0;i<v_steps;i++)
{
//--- change the coordinate
y+=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}

© 2000-2025, MetaQuotes Ltd.


627 Constants, Enumerations and Structures

//--- half a second of delay


Sleep(500);
//--- move the label to the right
for(int i=0;i<h_steps;i++)
{
//--- change the coordinate
x+=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- move the label up
for(int i=0;i<v_steps;i++)
{
//--- change the coordinate
y-=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- move the label to the left
for(int i=0;i<h_steps;i++)
{
//--- change the coordinate
x-=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- now, move the point by changing the anchor corner
//--- move to the lower left corner
if(!LabelChangeCorner(0,InpName,CORNER_LEFT_LOWER))
return;
//--- change the label text
StringConcatenate(text,"Lower left corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- move to the lower right corner
if(!LabelChangeCorner(0,InpName,CORNER_RIGHT_LOWER))
return;
//--- change the label text
StringConcatenate(text,"Lower right corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))

© 2000-2025, MetaQuotes Ltd.


628 Constants, Enumerations and Structures

return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- move to the upper right corner
if(!LabelChangeCorner(0,InpName,CORNER_RIGHT_UPPER))
return;
//--- change the label text
StringConcatenate(text,"Upper right corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- move to the upper left corner
if(!LabelChangeCorner(0,InpName,CORNER_LEFT_UPPER))
return;
//--- change the label text
StringConcatenate(text,"Upper left corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- delete the label
LabelDelete(0,InpName);
//--- redraw the chart and wait for half a second
ChartRedraw();
Sleep(500);
//---
}
//+------------------------------------------------------------------+
//| The function moves the object and changes its text |
//+------------------------------------------------------------------+
bool MoveAndTextChange(const int x,const int y,string text)
{
//--- move the label
if(!LabelMove(0,InpName,x,y))
return(false);
//--- change the label text
StringConcatenate(text,text,x,",",y);
if(!LabelTextChange(0,InpName,text))
return(false);
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return(false);
//--- redraw the chart
ChartRedraw();
// 0.01 seconds of delay

© 2000-2025, MetaQuotes Ltd.


629 Constants, Enumerations and Structures

Sleep(10);
//--- exit the function
return(true);
}

© 2000-2025, MetaQuotes Ltd.


630 Constants, Enumerations and Structures

OBJ_BUTTON
Button object.

Note

Anchor point coordinates are set in pixels. You can select button anchoring corner from
ENUM _BASE_CORNER .

Example

The following script creates and moves Button object on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.
//--- description
#property description "Script creates the button on the chart."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Button"; // Button name
input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring
input string InpFont="Arial"; // Font
input int InpFontSize=14; // Font size
input color InpColor=clrBlack; // Text color
input color InpBackColor=C'236,233,216'; // Background color
input color InpBorderColor=clrNONE; // Border color
input bool InpState=false; // Pressed/Released
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move

© 2000-2025, MetaQuotes Ltd.


631 Constants, Enumerations and Structures

input bool InpHidden=true; // Hidden in the object list


input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the button |
//+------------------------------------------------------------------+
bool ButtonCreate(const long chart_ID=0, // chart's ID
const string name="Button", // button name
const int sub_window=0, // subwindow index
const int x=0, // X coordinate
const int y=0, // Y coordinate
const int width=50, // button width
const int height=18, // button height
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner for anchoring
const string text="Button", // text
const string font="Arial", // font
const int font_size=10, // font size
const color clr=clrBlack, // text color
const color back_clr=C'236,233,216', // background color
const color border_clr=clrNONE, // border color
const bool state=false, // pressed/released
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- reset the error value
ResetLastError();
//--- create the button
if(!ObjectCreate(chart_ID,name,OBJ_BUTTON,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create the button! Error code = ",GetLastError());
return(false);
}
//--- set button coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set button size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set text color

© 2000-2025, MetaQuotes Ltd.


632 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set background color
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border color
ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- set button state
ObjectSetInteger(chart_ID,name,OBJPROP_STATE,state);
//--- enable (true) or disable (false) the mode of moving the button by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the button |
//+------------------------------------------------------------------+
bool ButtonMove(const long chart_ID=0, // chart's ID
const string name="Button", // button name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the button
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the button! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the button! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change button size |
//+------------------------------------------------------------------+
bool ButtonChangeSize(const long chart_ID=0, // chart's ID

© 2000-2025, MetaQuotes Ltd.


633 Constants, Enumerations and Structures

const string name="Button", // button name


const int width=50, // button width
const int height=18) // button height
{
//--- reset the error value
ResetLastError();
//--- change the button size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the button width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the button height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change corner of the chart for binding the button |
//+------------------------------------------------------------------+
bool ButtonChangeCorner(const long chart_ID=0, // chart's ID
const string name="Button", // button name
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER) // chart corner for anchor
{
//--- reset the error value
ResetLastError();
//--- change anchor corner
if(!ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner))
{
Print(__FUNCTION__,
": failed to change the anchor corner! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change button text |
//+------------------------------------------------------------------+
bool ButtonTextChange(const long chart_ID=0, // chart's ID
const string name="Button", // button name
const string text="Text") // text
{
//--- reset the error value

© 2000-2025, MetaQuotes Ltd.


634 Constants, Enumerations and Structures

ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the button |
//+------------------------------------------------------------------+
bool ButtonDelete(const long chart_ID=0, // chart's ID
const string name="Button") // button name
{
//--- reset the error value
ResetLastError();
//--- delete the button
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the button! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define the step for changing the button size

© 2000-2025, MetaQuotes Ltd.


635 Constants, Enumerations and Structures

int x_step=(int)x_distance/32;
int y_step=(int)y_distance/32;
//--- set the button coordinates and its size
int x=(int)x_distance/32;
int y=(int)y_distance/32;
int x_size=(int)x_distance*15/16;
int y_size=(int)y_distance*15/16;
//--- create the button
if(!ButtonCreate(0,InpName,0,x,y,x_size,y_size,InpCorner,"Press",InpFont,InpFontSize,
InpColor,InpBackColor,InpBorderColor,InpState,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart
ChartRedraw();
//--- reduce the button in the loop
int i=0;
while(i<13)
{
//--- half a second of delay
Sleep(500);
//--- switch the button to the pressed state
ObjectSetInteger(0,InpName,OBJPROP_STATE,true);
//--- redraw the chart and wait for 0.2 second
ChartRedraw();
Sleep(200);
//--- redefine coordinates and button size
x+=x_step;
y+=y_step;
x_size-=x_step*2;
y_size-=y_step*2;
//--- reduce the button
ButtonMove(0,InpName,x,y);
ButtonChangeSize(0,InpName,x_size,y_size);
//--- bring the button back to the released state
ObjectSetInteger(0,InpName,OBJPROP_STATE,false);
//--- redraw the chart
ChartRedraw();
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- increase the loop counter
i++;
}
//--- half a second of delay
Sleep(500);
//--- delete the button
ButtonDelete(0,InpName);
ChartRedraw();

© 2000-2025, MetaQuotes Ltd.


636 Constants, Enumerations and Structures

//--- wait for 1 second


Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


637 Constants, Enumerations and Structures

OBJ_CHART
Chart object.

Note

" OBJ_CHART" type object is not supported (not displayed) during a visual test.
Anchor point coordinates are set in pixels. You can select anchoring corner from
ENUM _BASE_CORNER enumeration.

S ymbol, period and scale can be selected for Chart object. Price scale and date display mode can
also be enabled/disabled.
Example

The following script creates and moves Chart object on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script creates \"Chart\" object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Chart"; // Object name
input string InpSymbol="EURUSD"; // Symbol
input ENUM_TIMEFRAMES InpPeriod=PERIOD_H1; // Period
input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Anchoring corner
input int InpScale=2; // Scale

© 2000-2025, MetaQuotes Ltd.


638 Constants, Enumerations and Structures

input bool InpDateScale=true; // Time scale display


input bool InpPriceScale=true; // Price scale display
input color InpColor=clrRed; // Border color when highlighted
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style when highlighted
input int InpPointWidth=1; // Point size to move
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Creating Chart object |
//+------------------------------------------------------------------+
bool ObjectChartCreate(const long chart_ID=0, // chart's ID
const string name="Chart", // object name
const int sub_window=0, // subwindow index
const string symbol="EURUSD", // symbol
const ENUM_TIMEFRAMES period=PERIOD_H1, // period
const int x=0, // X coordinate
const int y=0, // Y coordinate
const int width=300, // width
const int height=200, // height
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // anchoring corner
const int scale=2, // scale
const bool date_scale=true, // time scale display
const bool price_scale=true, // price scale display
const color clr=clrRed, // border color when highl
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style when highlig
const int point_width=1, // move point size
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object li
const long z_order=0) // priority for mouse clic
{
//--- reset the error value
ResetLastError();
//--- create Chart object
if(!ObjectCreate(chart_ID,name,OBJ_CHART,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create \"Chart\" object! Error code = ",GetLastError());
return(false);
}
//--- set object coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set object size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the chart's corner, relative to which point coordinates are defined

© 2000-2025, MetaQuotes Ltd.


639 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set the symbol
ObjectSetString(chart_ID,name,OBJPROP_SYMBOL,symbol);
//--- set the period
ObjectSetInteger(chart_ID,name,OBJPROP_PERIOD,period);
//--- set the scale
ObjectSetInteger(chart_ID,name,OBJPROP_CHART_SCALE,scale);
//--- display (true) or hide (false) the time scale
ObjectSetInteger(chart_ID,name,OBJPROP_DATE_SCALE,date_scale);
//--- display (true) or hide (false) the price scale
ObjectSetInteger(chart_ID,name,OBJPROP_PRICE_SCALE,price_scale);
//--- set the border color when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a size of the anchor point for moving an object
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,point_width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Sets the symbol and time frame of the Chart object |
//+------------------------------------------------------------------+
bool ObjectChartSetSymbolAndPeriod(const long chart_ID=0, // chart's ID (not Chart
const string name="Chart", // object name
const string symbol="EURUSD", // symbol
const ENUM_TIMEFRAMES period=PERIOD_H1) // time frame
{
//--- reset the error value
ResetLastError();
//--- set Chart object's symbol and time frame
if(!ObjectSetString(chart_ID,name,OBJPROP_SYMBOL,symbol))
{
Print(__FUNCTION__,
": failed to set a symbol for \"Chart\" object! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_PERIOD,period))
{
Print(__FUNCTION__,

© 2000-2025, MetaQuotes Ltd.


640 Constants, Enumerations and Structures

": failed to set a period for \"Chart\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Chart object |
//+------------------------------------------------------------------+
bool ObjectChartMove(const long chart_ID=0, // chart's ID (not Chart object's one)
const string name="Chart", // object name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of \"Chart\" object! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of \"Chart\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Chart object size |
//+------------------------------------------------------------------+
bool ObjectChartChangeSize(const long chart_ID=0, // chart's ID (not Chart object's one)
const string name="Chart", // object name
const int width=300, // width
const int height=200) // height
{
//--- reset the error value
ResetLastError();
//--- change the object size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the width of \"Chart\" object! Error code = ",GetLastError());
return(false);
}

© 2000-2025, MetaQuotes Ltd.


641 Constants, Enumerations and Structures

if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the height of \"Chart\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Return Chart object's ID |
//+------------------------------------------------------------------+
long ObjectChartGetID(const long chart_ID=0, // chart's ID (not Chart object's one)
const string name="Chart") // object name
{
//--- prepare the variable to get Chart object's ID
long id=-1;
//--- reset the error value
ResetLastError();
//--- get ID
if(!ObjectGetInteger(chart_ID,name,OBJPROP_CHART_ID,0,id))
{
Print(__FUNCTION__,
": failed to get \"Chart\" object's ID! Error code = ",GetLastError());
}
//--- return the result
return(id);
}
//+------------------------------------------------------------------+
//| Delete Chart object |
//+------------------------------------------------------------------+
bool ObjectChartDelete(const long chart_ID=0, // chart's ID (not Chart object's one)
const string name="Chart") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the button
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Chart\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


642 Constants, Enumerations and Structures

void OnStart()
{
//--- get the number of symbols in Market Watch
int symbols=SymbolsTotal(true);
//--- check if the symbol with a specified name is present in the symbol list
bool exist=false;
for(int i=0;i<symbols;i++)
if(InpSymbol==SymbolName(i,true))
{
exist=true;
break;
}
if(!exist)
{
Print("Error! ",InpSymbol," symbol is not present in \"Market Watch\"!");
return;
}
//--- check validity of input parameters
if(InpScale<0 || InpScale>5)
{
Print("Error! Incorrect values of input parameters!");
return;
}

//--- chart window size


long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- set Chart object coordinates and its size
int x=(int)x_distance/16;
int y=(int)y_distance/16;
int x_size=(int)x_distance*7/16;
int y_size=(int)y_distance*7/16;
//--- create Chart object
if(!ObjectChartCreate(0,InpName,0,InpSymbol,InpPeriod,x,y,x_size,y_size,InpCorner,InpScale,InpDa
InpPriceScale,InpColor,InpStyle,InpPointWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}

© 2000-2025, MetaQuotes Ltd.


643 Constants, Enumerations and Structures

//--- redraw the chart and wait for 1 second


ChartRedraw();
Sleep(1000);
//--- stretch Chart object
int steps=(int)MathMin(x_distance*7/16,y_distance*7/16);
for(int i=0;i<steps;i++)
{
//--- resize
x_size+=1;
y_size+=1;
if(!ObjectChartChangeSize(0,InpName,x_size,y_size))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart and wait for 0.01 seconds
ChartRedraw();
Sleep(10);
}
//--- half a second of delay
Sleep(500);
//--- change chart's time frame
if(!ObjectChartSetSymbolAndPeriod(0,InpName,InpSymbol,PERIOD_M1))
return;
ChartRedraw();
//--- three seconds of delay
Sleep(3000);
//--- delete the object
ObjectChartDelete(0,InpName);
ChartRedraw();
//--- wait for 1 second
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


644 Constants, Enumerations and Structures

OBJ_BITMAP
Bitmap object.

Note

For Bitmap object, you can select visibility scope of an image.


Example

The following script creates several bitmaps on the chart. S pecial functions have been developed to
create and change graphical object's properties. You can use these functions " as is " in your own
applications.

//--- description
#property description "Script creates a bitmap in the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpFile="\\Images\\dollar.bmp"; // Bitmap file name
input int InpWidth=24; // Visibility scope X coordinate
input int InpHeight=24; // Visibility scope Y coordinate
input int InpXOffset=4; // Visibility scope shift by X axis
input int InpYOffset=4; // Visibility scope shift by Y axis
input color InpColor=clrRed; // Border color when highlighted
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Line style when highlighted
input int InpPointWidth=1; // Point size to move
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move

© 2000-2025, MetaQuotes Ltd.


645 Constants, Enumerations and Structures

input bool InpHidden=true; // Hidden in the object list


input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create a bitmap in the chart window |
//+------------------------------------------------------------------+
bool BitmapCreate(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const string file="", // bitmap file name
const int width=10, // visibility scope X coordinate
const int height=10, // visibility scope Y coordinate
const int x_offset=0, // visibility scope shift by X axis
const int y_offset=0, // visibility scope shift by Y axis
const color clr=clrRed, // border color when highlighted
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style when highlighted
const int point_width=1, // move point size
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor point coordinates if they are not set
ChangeBitmapEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create a bitmap
if(!ObjectCreate(chart_ID,name,OBJ_BITMAP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create a bitmap in the chart window! Error code = ",GetLastError());
return(false);
}
//--- set the path to the image file
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,file))
{
Print(__FUNCTION__,
": failed to load the image! Error code = ",GetLastError());
return(false);
}
//--- set visibility scope for the image; if width or height values
//--- exceed the width and height (respectively) of a source image,
//--- it is not drawn; in the opposite case,
//--- only the part corresponding to these values is drawn
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the part of an image that is to be displayed in the visibility scope
//--- the default part is the upper left area of an image; the values allow

© 2000-2025, MetaQuotes Ltd.


646 Constants, Enumerations and Structures

//--- performing a shift from this area displaying another part of the image
ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset);
ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset);
//--- set the border color when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a size of the anchor point for moving an object
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,point_width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set a new image for the bitmap |
//+------------------------------------------------------------------+
bool BitmapSetImage(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
const string file="") // path to the file
{
//--- reset the error value
ResetLastError();
//--- set the path to the image file
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,file))
{
Print(__FUNCTION__,
": failed to load the image! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move a bitmap in the chart window |
//+------------------------------------------------------------------+
bool BitmapMove(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
datetime time=0, // anchor point time
double price=0) // anchor point price
{
//--- if point position is not set, move it to the current bar having Bid price

© 2000-2025, MetaQuotes Ltd.


647 Constants, Enumerations and Structures

if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change visibility scope (bitmap) size |
//+------------------------------------------------------------------+
bool BitmapChangeSize(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
const int width=0, // bitmap width
const int height=0) // bitmap height
{
//--- reset the error value
ResetLastError();
//--- change bitmap size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the bitmap width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the bitmap height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------+
//| Change coordinate of the upper left corner of the visibility scope |
//+--------------------------------------------------------------------+
bool BitmapMoveVisibleArea(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
const int x_offset=0, // visibility scope X coordinate
const int y_offset=0) // visibility scope Y coordinate

© 2000-2025, MetaQuotes Ltd.


648 Constants, Enumerations and Structures

{
//--- reset the error value
ResetLastError();
//--- change the bitmap's visibility scope coordinates
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset))
{
Print(__FUNCTION__,
": failed to change X coordinate of the visibility scope! Error code = ",GetLastError()
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset))
{
Print(__FUNCTION__,
": failed to change Y coordinate of the visibility scope! Error code = ",GetLastError()
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete a bitmap |
//+------------------------------------------------------------------+
bool BitmapDelete(const long chart_ID=0, // chart's ID
const string name="Bitmap") // bitmap name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a bitmap! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeBitmapEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);

© 2000-2025, MetaQuotes Ltd.


649 Constants, Enumerations and Structures

}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double close[]; // array for storing Close prices
//--- bitmap file name
string file="\\Images\\dollar.bmp";
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(close,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of Close prices
if(CopyClose(Symbol(),Period(),0,bars,close)==-1)
{
Print("Failed to copy the values of Close prices! Error code = ",GetLastError());
return;
}
//--- define how often the images should be displayed
int scale=(int)ChartGetInteger(0,CHART_SCALE);
//--- define the step
int step=1;
switch(scale)
{
case 0:
step=27;
break;
case 1:
step=14;
break;
case 2:
step=7;
break;
case 3:
step=4;
break;
case 4:
step=2;
break;

© 2000-2025, MetaQuotes Ltd.


650 Constants, Enumerations and Structures

}
//--- create bitmaps for High and Low bars' values (with gaps)
for(int i=0;i<bars;i+=step)
{
//--- create the bitmaps
if(!BitmapCreate(0,"Bitmap_"+(string)i,0,date[i],close[i],InpFile,InpWidth,InpHeight,InpXOffs
InpYOffset,InpColor,InpStyle,InpPointWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- half a second of delay
Sleep(500);
//--- delete Sell signs
for(int i=0;i<bars;i+=step)
{
if(!BitmapDelete(0,"Bitmap_"+(string)i))
return;
if(!BitmapDelete(0,"Bitmap_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//---
}

© 2000-2025, MetaQuotes Ltd.


651 Constants, Enumerations and Structures

OBJ_BITMAP_LABEL
Bitmap Label object.

Note

Anchor point position relative to the label can be selected from ENUM _ANCHOR_POINT enumeration.
Anchor point coordinates are set in pixels.
You can also select bitmap anchoring corner from ENUM _BASE_CORNER enumeration.
For bitmap label, you can select visibility scope of an image.
Example

The following script creates several bitmaps on the chart. S pecial functions have been developed to
create and change graphical object's properties. You can use these functions " as is " in your own
applications.
//--- description
#property description "Script creates \"Bitmap Label\" object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="BmpLabel"; // Label name
input string InpFileOn="\\Images\\dollar.bmp"; // File name for On mode
input string InpFileOff="\\Images\\euro.bmp"; // File name for Off mode
input bool InpState=false; // Label pressed/released
input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring
input ENUM_ANCHOR_POINT InpAnchor=ANCHOR_CENTER; // Anchor type
input color InpColor=clrRed; // Border color when highlighted

© 2000-2025, MetaQuotes Ltd.


652 Constants, Enumerations and Structures

input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Line style when highlighted


input int InpPointWidth=1; // Point size to move
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Bitmap Label object |
//+------------------------------------------------------------------+
bool BitmapLabelCreate(const long chart_ID=0, // chart's ID
const string name="BmpLabel", // label name
const int sub_window=0, // subwindow index
const int x=0, // X coordinate
const int y=0, // Y coordinate
const string file_on="", // image in On mode
const string file_off="", // image in Off mode
const int width=0, // visibility scope X coor
const int height=0, // visibility scope Y coor
const int x_offset=10, // visibility scope shift
const int y_offset=10, // visibility scope shift
const bool state=false, // pressed/released
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner for anchor
const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type
const color clr=clrRed, // border color when highl
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style when highlig
const int point_width=1, // move point size
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object li
const long z_order=0) // priority for mouse clic
{
//--- reset the error value
ResetLastError();
//--- create a bitmap label
if(!ObjectCreate(chart_ID,name,OBJ_BITMAP_LABEL,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create \"Bitmap Label\" object! Error code = ",GetLastError());
return(false);
}
//--- set the images for On and Off modes
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,0,file_on))
{
Print(__FUNCTION__,
": failed to load the image for On mode! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,1,file_off))
{

© 2000-2025, MetaQuotes Ltd.


653 Constants, Enumerations and Structures

Print(__FUNCTION__,
": failed to load the image for Off mode! Error code = ",GetLastError());
return(false);
}
//--- set label coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set visibility scope for the image; if width or height values
//--- exceed the width and height (respectively) of a source image,
//--- it is not drawn; in the opposite case,
//--- only the part corresponding to these values is drawn
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the part of an image that is to be displayed in the visibility scope
//--- the default part is the upper left area of an image; the values allow
//--- performing a shift from this area displaying another part of the image
ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset);
ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset);
//--- define the label's status (pressed or released)
ObjectSetInteger(chart_ID,name,OBJPROP_STATE,state);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set the border color when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a size of the anchor point for moving an object
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,point_width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set a new image for Bitmap label object |
//+------------------------------------------------------------------+
bool BitmapLabelSetImage(const long chart_ID=0, // chart's ID
const string name="BmpLabel", // label name
const int on_off=0, // modifier (On or Off)
const string file="") // path to the file

© 2000-2025, MetaQuotes Ltd.


654 Constants, Enumerations and Structures

{
//--- reset the error value
ResetLastError();
//--- set the path to the image file
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,on_off,file))
{
Print(__FUNCTION__,
": failed to load the image! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Bitmap Label object |
//+------------------------------------------------------------------+
bool BitmapLabelMove(const long chart_ID=0, // chart's ID
const string name="BmpLabel", // label name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the object! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change visibility scope (object) size |
//+------------------------------------------------------------------+
bool BitmapLabelChangeSize(const long chart_ID=0, // chart's ID
const string name="BmpLabel", // label name
const int width=0, // label width
const int height=0) // label height
{
//--- reset the error value
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


655 Constants, Enumerations and Structures

//--- change the object size


if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the object width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the object height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------+
//| Change coordinate of the upper left corner of the visibility scope |
//+--------------------------------------------------------------------+
bool BitmapLabelMoveVisibleArea(const long chart_ID=0, // chart's ID
const string name="BmpLabel", // label name
const int x_offset=0, // visibility scope X coordinate
const int y_offset=0) // visibility scope Y coordinate
{
//--- reset the error value
ResetLastError();
//--- change the object's visibility scope coordinates
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset))
{
Print(__FUNCTION__,
": failed to change X coordinate of the visibility scope! Error code = ",GetLastError()
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset))
{
Print(__FUNCTION__,
": failed to change Y coordinate of the visibility scope! Error code = ",GetLastError()
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete "Bitmap label" object |
//+------------------------------------------------------------------+
bool BitmapLabelDelete(const long chart_ID=0, // chart's ID
const string name="BmpLabel") // label name
{
//--- reset the error value

© 2000-2025, MetaQuotes Ltd.


656 Constants, Enumerations and Structures

ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Bitmap label\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define bitmap label coordinates
int x=(int)x_distance/2;
int y=(int)y_distance/2;
//--- set label size and visibility scope coordinates
int width=32;
int height=32;
int x_offset=0;
int y_offset=0;
//--- place bitmap label at the center of the window
if(!BitmapLabelCreate(0,InpName,0,x,y,InpFileOn,InpFileOff,width,height,x_offset,y_offset,InpSta
InpCorner,InpAnchor,InpColor,InpStyle,InpPointWidth,InpBack,InpSelection,InpHidden,InpZOrder)
{
return;
}
//--- redraw the chart and wait one second
ChartRedraw();
Sleep(1000);
//--- change label's visibility scope size in the loop
for(int i=0;i<6;i++)

© 2000-2025, MetaQuotes Ltd.


657 Constants, Enumerations and Structures

{
//--- change visibility scope size
width--;
height--;
if(!BitmapLabelChangeSize(0,InpName,width,height))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.3 seconds of delay
Sleep(300);
}
//--- 1 second of delay
Sleep(1000);
//--- change label's visibility scope coordinates in the loop
for(int i=0;i<2;i++)
{
//--- change visibility scope coordinates
x_offset++;
y_offset++;
if(!BitmapLabelMoveVisibleArea(0,InpName,x_offset,y_offset))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.3 seconds of delay
Sleep(300);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the label
BitmapLabelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


658 Constants, Enumerations and Structures

OBJ_EDIT
Edit object.

Note

Anchor point coordinates are set in pixels. You can select Edit anchoring corner from
ENUM _BASE_CORNER enumeration.

You can also select one of the text alignment types inside Edit from ENUM _ALIGN_MODE
enumeration.
Example

The following script creates and moves Edit object on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.
//--- description
#property description "Script creates \"Edit\" object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Edit"; // Object name
input string InpText="Text"; // Object text
input string InpFont="Arial"; // Font
input int InpFontSize=14; // Font size
input ENUM_ALIGN_MODE InpAlign=ALIGN_CENTER; // Text alignment type
input bool InpReadOnly=false; // Permission to edit
input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring
input color InpColor=clrBlack; // Text color

© 2000-2025, MetaQuotes Ltd.


659 Constants, Enumerations and Structures

input color InpBackColor=clrWhite; // Background color


input color InpBorderColor=clrBlack; // Border color
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Edit object |
//+------------------------------------------------------------------+
bool EditCreate(const long chart_ID=0, // chart's ID
const string name="Edit", // object name
const int sub_window=0, // subwindow index
const int x=0, // X coordinate
const int y=0, // Y coordinate
const int width=50, // width
const int height=18, // height
const string text="Text", // text
const string font="Arial", // font
const int font_size=10, // font size
const ENUM_ALIGN_MODE align=ALIGN_CENTER, // alignment type
const bool read_only=false, // ability to edit
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner for anchoring
const color clr=clrBlack, // text color
const color back_clr=clrWhite, // background color
const color border_clr=clrNONE, // border color
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- reset the error value
ResetLastError();
//--- create edit field
if(!ObjectCreate(chart_ID,name,OBJ_EDIT,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create \"Edit\" object! Error code = ",GetLastError());
return(false);
}
//--- set object coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set object size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);

© 2000-2025, MetaQuotes Ltd.


660 Constants, Enumerations and Structures

//--- set font size


ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the type of text alignment in the object
ObjectSetInteger(chart_ID,name,OBJPROP_ALIGN,align);
//--- enable (true) or cancel (false) read-only mode
ObjectSetInteger(chart_ID,name,OBJPROP_READONLY,read_only);
//--- set the chart's corner, relative to which object coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set text color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set background color
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border color
ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Edit object |
//+------------------------------------------------------------------+
bool EditMove(const long chart_ID=0, // chart's ID
const string name="Edit", // object name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the object! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the object! Error code = ",GetLastError());
return(false);
}

© 2000-2025, MetaQuotes Ltd.


661 Constants, Enumerations and Structures

//--- successful execution


return(true);
}
//+------------------------------------------------------------------+
//| Resize Edit object |
//+------------------------------------------------------------------+
bool EditChangeSize(const long chart_ID=0, // chart's ID
const string name="Edit", // object name
const int width=0, // width
const int height=0) // height
{
//--- reset the error value
ResetLastError();
//--- change the object size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the object width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the object height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Edit object's text |
//+------------------------------------------------------------------+
bool EditTextChange(const long chart_ID=0, // chart's ID
const string name="Edit", // object name
const string text="Text") // text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


662 Constants, Enumerations and Structures

//| Return Edit object text |


//+------------------------------------------------------------------+
bool EditTextGet(string &text, // text
const long chart_ID=0, // chart's ID
const string name="Edit") // object name
{
//--- reset the error value
ResetLastError();
//--- get object text
if(!ObjectGetString(chart_ID,name,OBJPROP_TEXT,0,text))
{
Print(__FUNCTION__,
": failed to get the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Edit object |
//+------------------------------------------------------------------+
bool EditDelete(const long chart_ID=0, // chart's ID
const string name="Edit") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Edit\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;

© 2000-2025, MetaQuotes Ltd.


663 Constants, Enumerations and Structures

}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define the step for changing the edit field
int x_step=(int)x_distance/64;
//--- set edit field coordinates and its size
int x=(int)x_distance/8;
int y=(int)y_distance/2;
int x_size=(int)x_distance/8;
int y_size=InpFontSize*2;
//--- store the text in the local variable
string text=InpText;
//--- create edit field
if(!EditCreate(0,InpName,0,x,y,x_size,y_size,InpText,InpFont,InpFontSize,InpAlign,InpReadOnly,
InpCorner,InpColor,InpBackColor,InpBorderColor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- stretch the edit field
while(x_size-x<x_distance*5/8)
{
//--- increase edit field's width
x_size+=x_step;
if(!EditChangeSize(0,InpName,x_size,y_size))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart and wait for 0.05 seconds
ChartRedraw();
Sleep(50);
}
//--- half a second of delay
Sleep(500);
//--- change the text
for(int i=0;i<20;i++)
{
//--- add "+" at the beginning and at the end
text="+"+text+"+";
if(!EditTextChange(0,InpName,text))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())

© 2000-2025, MetaQuotes Ltd.


664 Constants, Enumerations and Structures

return;
//--- redraw the chart and wait for 0.1 seconds
ChartRedraw();
Sleep(100);
}
//--- half a second of delay
Sleep(500);
//--- delete edit field
EditDelete(0,InpName);
ChartRedraw();
//--- wait for 1 second
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


665 Constants, Enumerations and Structures

OBJ_EVENT
Event object.

Note

W hen hovering mouse over the event, its text appears.


Example

The following script creates and moves Event object on the chart. S pecial functions have been
developed to create and change graphical object's properties. You can use these functions " as is " in
your own applications.

//--- description
#property description "Script draws \"Event\" graphical object."
#property description "Anchor point date is set in percentage of"
#property description "the chart window width in bars."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Event"; // Event name
input int InpDate=25; // Event date, %
input string InpText="Text"; // Event text
input color InpColor=clrRed; // Event color
input int InpWidth=1; // Point size when highlighted
input bool InpBack=false; // Background event
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list

© 2000-2025, MetaQuotes Ltd.


666 Constants, Enumerations and Structures

input long InpZOrder=0; // Priority for mouse click


//+------------------------------------------------------------------+
//| Create Event object on the chart |
//+------------------------------------------------------------------+
bool EventCreate(const long chart_ID=0, // chart's ID
const string name="Event", // event name
const int sub_window=0, // subwindow index
const string text="Text", // event text
datetime time=0, // time
const color clr=clrRed, // color
const int width=1, // point width when highlighted
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- if time is not set, create the object on the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- create Event object
if(!ObjectCreate(chart_ID,name,OBJ_EVENT,sub_window,time,0))
{
Print(__FUNCTION__,
": failed to create \"Event\" object! Error code = ",GetLastError());
return(false);
}
//--- set event text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set anchor point width if the object is highlighted
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving event by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Event object text |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


667 Constants, Enumerations and Structures

bool EventTextChange(const long chart_ID=0, // chart's ID


const string name="Event", // event name
const string text="Text") // text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Event object |
//+------------------------------------------------------------------+
bool EventMove(const long chart_ID=0, // chart's ID
const string name="Event", // event name
datetime time=0) // time
{
//--- if time is not set, move event to the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectMove(chart_ID,name,0,time,0))
{
Print(__FUNCTION__,
": failed to move \"Event\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Event object |
//+------------------------------------------------------------------+
bool EventDelete(const long chart_ID=0, // chart's ID
const string name="Event") // event name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{

© 2000-2025, MetaQuotes Ltd.


668 Constants, Enumerations and Structures

Print(__FUNCTION__,
": failed to delete \"Event\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- array for storing the date values to be used
//--- for setting and changing Event object anchor point's coordinates
datetime date[];
//--- memory allocation
ArrayResize(date,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- define the points to create an object
int d=InpDate*(bars-1)/100;
//--- create Event object
if(!EventCreate(0,InpName,0,InpText,date[d],InpColor,InpWidth,
InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the object
//--- loop counter
int h_steps=bars/2;
//--- move the object
for(int i=0;i<h_steps;i++)
{

© 2000-2025, MetaQuotes Ltd.


669 Constants, Enumerations and Structures

//--- use the following value


if(d<bars-1)
d+=1;
//--- move the point
if(!EventMove(0,InpName,date[d]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
EventDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


670 Constants, Enumerations and Structures

OBJ_RECTANGLE_LABEL
R ectangle Label object.

Note

Anchor point coordinates are set in pixels. You can select rectangle label's anchoring corner from
ENUM _BASE_CORNER enumeration. R ectangle label's border type can be selected from
ENUM _BORDER_T YPE enumeration.

The object is used to create and design the custom graphical interface.
Example

The following script creates and moves Rectangle Label object on the chart. S pecial functions have
been developed to create and change graphical object's properties. You can use these functions " as
is " in your own applications.

//--- description
#property description "Script creates \"Rectangle Label\" graphical object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="RectLabel"; // Label name
input color InpBackColor=clrSkyBlue; // Background color
input ENUM_BORDER_TYPE InpBorder=BORDER_FLAT; // Border type
input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring
input color InpColor=clrDarkBlue; // Flat border color (Flat)
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Flat border style (Flat)
input int InpLineWidth=3; // Flat border width (Flat)

© 2000-2025, MetaQuotes Ltd.


671 Constants, Enumerations and Structures

input bool InpBack=false; // Background object


input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create rectangle label |
//+------------------------------------------------------------------+
bool RectLabelCreate(const long chart_ID=0, // chart's ID
const string name="RectLabel", // label name
const int sub_window=0, // subwindow index
const int x=0, // X coordinate
const int y=0, // Y coordinate
const int width=50, // width
const int height=18, // height
const color back_clr=C'236,233,216', // background color
const ENUM_BORDER_TYPE border=BORDER_SUNKEN, // border type
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner for anchoring
const color clr=clrRed, // flat border color (Flat)
const ENUM_LINE_STYLE style=STYLE_SOLID, // flat border style
const int line_width=1, // flat border width
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- reset the error value
ResetLastError();
//--- create a rectangle label
if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE_LABEL,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create a rectangle label! Error code = ",GetLastError());
return(false);
}
//--- set label coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set label size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set background color
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border type
ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_TYPE,border);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set flat border color (in Flat mode)
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set flat border line style

© 2000-2025, MetaQuotes Ltd.


672 Constants, Enumerations and Structures

ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set flat border width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,line_width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move rectangle label |
//+------------------------------------------------------------------+
bool RectLabelMove(const long chart_ID=0, // chart's ID
const string name="RectLabel", // label name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the rectangle label
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the label! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the size of the rectangle label |
//+------------------------------------------------------------------+
bool RectLabelChangeSize(const long chart_ID=0, // chart's ID
const string name="RectLabel", // label name
const int width=50, // label width
const int height=18) // label height
{

© 2000-2025, MetaQuotes Ltd.


673 Constants, Enumerations and Structures

//--- reset the error value


ResetLastError();
//--- change label size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the label's width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the label's height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change rectangle label border type |
//+------------------------------------------------------------------+
bool RectLabelChangeBorderType(const long chart_ID=0, // chart's ID
const string name="RectLabel", // label name
const ENUM_BORDER_TYPE border=BORDER_SUNKEN) // border type
{
//--- reset the error value
ResetLastError();
//--- change border type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_TYPE,border))
{
Print(__FUNCTION__,
": failed to change the border type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the rectangle label |
//+------------------------------------------------------------------+
bool RectLabelDelete(const long chart_ID=0, // chart's ID
const string name="RectLabel") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,

© 2000-2025, MetaQuotes Ltd.


674 Constants, Enumerations and Structures

": failed to delete a rectangle label! Error code = ",GetLastError());


return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define rectangle label coordinates
int x=(int)x_distance/4;
int y=(int)y_distance/4;
//--- set label size
int width=(int)x_distance/4;
int height=(int)y_distance/4;
//--- create a rectangle label
if(!RectLabelCreate(0,InpName,0,x,y,width,height,InpBackColor,InpBorder,InpCorner,
InpColor,InpStyle,InpLineWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait one second
ChartRedraw();
Sleep(1000);
//--- change the size of the rectangle label
int steps=(int)MathMin(x_distance/4,y_distance/4);
for(int i=0;i<steps;i++)
{
//--- resize
width+=1;
height+=1;
if(!RectLabelChangeSize(0,InpName,width,height))
return;

© 2000-2025, MetaQuotes Ltd.


675 Constants, Enumerations and Structures

//--- check if the script's operation has been forcefully disabled


if(IsStopped())
return;
//--- redraw the chart and wait for 0.01 seconds
ChartRedraw();
Sleep(10);
}
//--- 1 second of delay
Sleep(1000);
//--- change border type
if(!RectLabelChangeBorderType(0,InpName,BORDER_RAISED))
return;
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- change border type
if(!RectLabelChangeBorderType(0,InpName,BORDER_SUNKEN))
return;
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- delete the label
RectLabelDelete(0,InpName);
ChartRedraw();
//--- wait for 1 second
Sleep(1000);
//---
}

© 2000-2025, MetaQuotes Ltd.


676 Constants, Enumerations and Structures

Object Properties
Graphical objects can have various properties depending on the object type. Values of object
properties are set up and received by corresponding functions for working with graphical objects.
All objects used in technical analysis are bound to the time and price coordinates : trendline, channels,
Fibonacci tools, etc. But there is a number of auxiliary objects intended to improve the user interface
that are bound to the always visible part of a chart (main chart windows or indicator subwindows):

Object ID X /Y Width/ Date/Pr OBJPRO OBJPRO OBJPRO


Height ice P_COR P_ANC P_ANGL
NER HOR E

Text OBJ_TEXT — — Yes — Yes Yes

Label OBJ_LABEL Yes Yes — Yes Yes Yes


(read
only)
Button OBJ_BUTTON Yes Yes — Yes — —

Bitmap OBJ_BITM AP — Yes Yes — Yes —


(read
only)
Bitmap OBJ_BITM AP_LABEL Yes Yes — Yes Yes —
Label (read
only)
Edit OBJ_EDIT Yes Yes — Yes — —

R ectan OBJ_RECTANGLE_LABEL Yes Yes — Yes — —


gle
Label

The following designations are used in the table:


· X /Y – coordinates of anchor points specified in pixels relative to a chart corner;
· Width/Height – objects have width and height. For " read only" , the width and height values are
calculated only once the object is rendered on chart;
· Date/Price – anchor point coordinates are specified using the date and price values ;
· OBJPROP_CORNER – defines the chart corner relative to which the anchor point coordinates are
specified. Can be one of the 4 values of the ENUM _BASE_CORNER enumeration;
· OBJPROP_ANCHOR – defines the anchor point in object itself and can be one of the 9 values of the
ENUM _ANCH OR_POINT enumeration. Coordinates in pixels are specified from this very point to
selected chart corner;
· OBJPROP_ANGLE – defines the object rotation angle counterclock wise.

The functions defining the properties of graphical objects, as well as ObjectCreate() and ObjectMove()
operations for creating and moving objects along the chart are actually used for sending commands to
the chart. If these functions are executed successfully, the command is included in the common queue

© 2000-2025, MetaQuotes Ltd.


677 Constants, Enumerations and Structures

of the chart events. Visual changes in the properties of graphical objects are implemented when
handling the queue of the chart events.
Thus, do not expect an immediate visual update of graphical objects after calling these functions.
Generally, the graphical objects on the chart are updated automatically by the terminal following the
change events - a new quote arrival, resizing the chart window, etc. Use ChartRedraw() function to
forcefully update the graphical objects.
For functions ObjectS etInteger() and ObjectGetInteger()
ENUM_OBJECT_PROPERTY _INTEGER

Identifier Des Property Type


crip
tion

OBJPROP_COLOR Colo color


r
OBJPROP_S TYLE S tyl ENUM _LINE_S T YL E
e
OBJPROP_W IDTH Line int
thic
k ne
ss
OBJPROP_BACK Obj bool
ect
in
the
bac
k gro
und
OBJPROP_ZORDER Prio long
rity
of a
grap
hica
l
obje
ct
for
rece
ivin
g
eve
nts
of
click
ing
on a

© 2000-2025, MetaQuotes Ltd.


678 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

char
t
(CH
AR T
EVE
NT _
CLI
CK).
The
defa
ult
zero
valu
e is
set
whe
n
crea
ting
an
obje
ct;
the
prio
rity
can
be
incr
eas
ed
if
nec
essa
ry.
W he
n
obje
cts
are
plac
ed
one
atop
anot
her,
only
one

© 2000-2025, MetaQuotes Ltd.


679 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

of
the
m
with
the
high
est
prio
rity
will
rece
ive
the
CHA
RTE
VEN
T _C
LICK
eve
nt.
OBJPROP_FILL Fill bool
an
obje
ct
with
colo
r
(for
OBJ
_RE
CTA
NGL
E,
OBJ
_T R
IAN
GL E
,
OBJ
_EL
LIPS
E,
OBJ
_CH
ANN
EL,
OBJ

© 2000-2025, MetaQuotes Ltd.


680 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

_S T
DDE
VCH
ANN
EL,
OBJ
_RE
GRE
SS I
ON)
OBJPROP_HIDDEN Proh bool
ibit
sho
win
g of
the
nam
e of
a
grap
hica
l
obje
ct in
the
list
of
obje
cts
fro
m
the
ter
min
al
men
u
" Ch
arts
" -
" Obj
ects
" -
" Lis
t of
obje
cts "

© 2000-2025, MetaQuotes Ltd.


681 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

.
The
true
valu
e
allo
ws
to
hide
an
obje
ct
fro
m
the
list.
By
defa
ult,
true
is
set
to
the
obje
cts
that
disp
lay
cale
ndar
eve
nts,
trad
ing
hist
ory
and
to
the
obje
cts
crea
ted
fro
m
MQL

© 2000-2025, MetaQuotes Ltd.


682 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

5
prog
ram
s.
To
see
such
grap
hica
l
obje
cts
and
acce
ss
thei
r
prop
erti
es,
click
on
the
"All"
butt
on
in
the
" Lis
t of
obje
cts "
win
dow
.
OBJPROP_SELECTED Obj bool
ect
is
sele
cted
OBJPROP_READONLY Abili bool
ty
to
edit
text
in

© 2000-2025, MetaQuotes Ltd.


683 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

the
Edit
obje
ct
OBJPROP_TYPE Obj ENUM _OBJECT r/o
ect
type
OBJPROP_TIM E Tim datetime modifier=number of anchor point
e
coor
dina
te
OBJPROP_SELECTABLE Obj bool
ect
avai
labil
ity
OBJPROP_CREATETIM E Tim datetime r/o
e of
obje
ct
crea
tion
OBJPROP_LEVELS Num int
ber
of
leve
ls
OBJPROP_LEVELCOLOR Colo color modifier=level number
r of
the
line-
leve
l
OBJPROP_LEVELS TYLE S tyl ENUM _LINE_S T YL E modifier=level number
e of
the
line-
leve
l
OBJPROP_LEVELW IDTH Thic int modifier=level number
k nes

© 2000-2025, MetaQuotes Ltd.


684 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

s of
the
line-
level
OBJPROP_ALIGN H ori ENUM _ALIGN_MODE
zont
al
text
alig
nme
nt
in
the
"Edi
t"
obje
ct
(OB
J_E
DIT)

OBJPROP_FONTS IZE Font int


size
OBJPROP_RAY_LEFT R ay bool
goe
s to
the
left
OBJPROP_RAY_RIGHT R ay bool
goe
s to
the
righ
t
OBJPROP_RAY A bool
vert
ical
line
goe
s
thro
ugh
all
the
win

© 2000-2025, MetaQuotes Ltd.


685 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

dow
s of
a
char
t
OBJPROP_ELLIPSE S ho bool
win
g
the
full
ellip
se
of
the
Fibo
nacc
i
Arc
obje
ct
(OB
J_FI
BOA
R C)

OBJPROP_ARROW CODE Arro uchar


w
cod
e
for
the
Arro
w
obje
ct
OBJPROP_TIM EFRAM ES Visi set of flags flags
bilit
y of
an
obje
ct
at
tim
efra
mes

© 2000-2025, MetaQuotes Ltd.


686 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

OBJPROP_ANCHOR Loc ENUM _ARROW_ANCHOR (for OBJ_ARROW ),


atio ENUM _ANCHOR_POINT (for OBJ_LABEL,
n of OBJ_BITM AP_LABEL and OBJ_TEXT)
the
anc
hor
poin
t of
a
grap
hica
l
obje
ct
OBJPROP_XDIS TANCE The int
dist
anc
e in
pixe
ls
alon
g
the
X
axis
fro
m
the
bind
ing
corn
er
(see
note
)
OBJPROP_YDIS TANCE The int
dist
anc
e in
pixe
ls
alon
g
the
Y
axis

© 2000-2025, MetaQuotes Ltd.


687 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

fro
m
the
bind
ing
corn
er
(see
note
)
OBJPROP_DIRECTION Tre ENUM _GANN_DIRECTION
nd
of
the
Gan
n
obje
ct
OBJPROP_DEGREE Lev ENUM _ELLIOT _WAVE_DEGREE
el of
the
Ellio
tt
W av
e
Mar
k ing

OBJPROP_DRAW LINES Disp bool


layi
ng
line
s
for
mar
k ing
the
Ellio
tt
W av
e
OBJPROP_S TATE Butt bool
on
stat
e
(pre

© 2000-2025, MetaQuotes Ltd.


688 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

ssed
/
depr
esse
d)
OBJPROP_CHART_ID ID long r/o
of
the
" Ch
art"
obje
ct
(OB
J_C
HAR
T).
It
allo
ws
wor
k ing
with
the
prop
erti
es
of
this
obje
ct
like
with
a
nor
mal
char
t
usin
g
the
func
tion
s
desc
ribe
d in
Cha

© 2000-2025, MetaQuotes Ltd.


689 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

rt
Ope
rati
ons,
but
ther
e
som
e
exc
epti
ons.
OBJPROP_XS IZE The int
obje
ct's
widt
h
alon
g
the
X
axis
in
pixe
ls.
S pe
cifie
d
for
OBJ
_L A
BEL
(rea
d
only
),
OBJ
_BU
TTO
N,
OBJ
_CH
AR T
,
OBJ
_BIT
M AP

© 2000-2025, MetaQuotes Ltd.


690 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

,
OBJ
_BIT
M AP
_L A
BEL,
OBJ
_EDI
T,
OBJ
_RE
CTA
NGL
E_L
ABE
L
obje
cts.
OBJPROP_YS IZE The int
obje
ct's
heig
ht
alon
g
the
Y
axis
in
pixe
ls.
S pe
cifie
d
for
OBJ
_L A
BEL
(rea
d
only
),
OBJ
_BU
TTO
N,
OBJ

© 2000-2025, MetaQuotes Ltd.


691 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

_CH
AR T
,
OBJ
_BIT
M AP
,
OBJ
_BIT
M AP
_L A
BEL,
OBJ
_EDI
T,
OBJ
_RE
CTA
NGL
E_L
ABE
L
obje
cts.
OBJPROP_XOFFSET The int
X
coor
dina
te
of
the
upp
er
left
corn
er
of
the
rect
ang
ular
visi
ble
area
in
the
grap

© 2000-2025, MetaQuotes Ltd.


692 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

hica
l
obje
cts
"Bit
map
Lab
el"
and
"Bit
map
" (O
BJ_
BIT
M AP
_L A
BEL
and
OBJ
_BIT
M AP
).
The
valu
e is
set
in
pixe
ls
rela
tive
to
the
upp
er
left
corn
er
of
the
orig
inal
ima
ge.
OBJPROP_YOFFSET The int
Y
coor

© 2000-2025, MetaQuotes Ltd.


693 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

dina
te
of
the
upp
er
left
corn
er
of
the
rect
ang
ular
visi
ble
area
in
the
grap
hica
l
obje
cts
"Bit
map
Lab
el"
and
"Bit
map
" (O
BJ_
BIT
M AP
_L A
BEL
and
OBJ
_BIT
M AP
).
The
valu
e is
set
in

© 2000-2025, MetaQuotes Ltd.


694 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

pixe
ls
rela
tive
to
the
upp
er
left
corn
er
of
the
orig
inal
ima
ge.
OBJPROP_PERIOD Tim ENUM _TIM EFRAM ES
efra
me
for
the
Cha
rt
obje
ct
OBJPROP_DATE_S CALE Disp bool
layi
ng
the
tim
e
scal
e
for
the
Cha
rt
obje
ct
OBJPROP_PRICE_S CALE Disp bool
layi
ng
the
pric

© 2000-2025, MetaQuotes Ltd.


695 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

e
scal
e
for
the
Cha
rt
obje
ct
OBJPROP_CHART_S CALE The int value in the range 0–5
scal
e
for
the
Cha
rt
obje
ct
OBJPROP_BGCOLOR The color
bac
k gro
und
colo
r for
OBJ
_EDI
T,
OBJ
_BU
TTO
N,
OBJ
_RE
CTA
NGL
E_L
ABE
L
OBJPROP_CORNER The ENUM _BASE_CORNER
corn
er
of
the
char
t to

© 2000-2025, MetaQuotes Ltd.


696 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

link
a
grap
hica
l
obje
ct
OBJPROP_BORDER_TYPE Bord ENUM _BORDER_T YPE
er
type
for
the
"R ec
tang
le
labe
l"
obje
ct
OBJPROP_BORDER_COLOR Bord color
er
colo
r for
the
OBJ
_EDI
T
and
OBJ
_BU
TTO
N
obje
cts
W hen using chart operations for the " Chart" object (OBJ_CHART), the following limitations are
imposed:
· It cannot be closed using ChartClose();
· S ymbol/period cannot be changed using the ChartS etS ymbolPeriod() function;
· The following properties are ineffective CHART_S CALE, CHART_BRING_TO_TOP,
CHART_SHOW_DATE_S CALE and CHART_SHOW_PRICE_S CALE (ENUM _CHART_PROPERTY_INTEGER).

© 2000-2025, MetaQuotes Ltd.


697 Constants, Enumerations and Structures

You can set a special mode of image display for OBJ_BITM AP_LABEL and OBJ_BITM AP objects. In this
mode, only part of an original image (at which a rectangular visible area is applied) is displayed, while
the rest of the image becomes invisible. The size of this area should be set using the properties
OBJPROP_XS IZE and OBJPROP_YS IZE. The visible area can be " moved" only within the original image
using the properties OBJPROP_XOFFSET and OBJPROP_YOFFSET.

For the fixed-sized objects : OBJ_BUTTON, OBJ_RECTANGLE_LABEL, OBJ_EDIT and OBJ_CHART,


properties OBJPROP_XDIS TANCE and OBJPROP_YDIS TANCE set the position of the top left point of the
object relative to the chart corner (OBJPROP_CORNER), from which the X and Y coordinates will be
counted in pixels.

For functions ObjectS etDouble() and ObjectGetDouble()


ENUM_OBJECT_PROPERTY _DOUBLE

Identifier Des Property Type


crip
tion

OBJPROP_PRICE Pric double modifier=number of anchor point


e
coor
dina
te
OBJPROP_LEVELVALUE Lev double modifier=level number
el
valu
e
OBJPROP_S CALE S cal double
e
(pro
pert
ies
of
Gan
n
obje
cts
and
Fibo
nacc
i
Arcs
)
OBJPROP_ANGLE Angl double
e.

© 2000-2025, MetaQuotes Ltd.


698 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

For
the
obje
cts
with
no
angl
e
spec
ifie
d,
crea
ted
fro
m a
prog
ram
,
the
valu
e is
equ
al to
EMP
TY_
VAL
UE

OBJPROP_DEVIATION Devi double


atio
n
for
the
S tan
dard
Devi
atio
n
Cha
nnel

For functions ObjectS etS tring() and ObjectGetS tring()


ENUM_OBJECT_PROPERTY _STRING

© 2000-2025, MetaQuotes Ltd.


699 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

OBJPROP_NAM E Obj string


ect
nam
e
OBJPROP_TEXT Des string
crip
tion
of
the
obje
ct
(the
text
cont
aine
d in
the
obje
ct)
OBJPROP_TOOLTIP The string
text
of a
tool
tip.
If
the
prop
erty
is
not
set,
then
the
tool
tip
gen
erat
ed
auto
mat
icall
y by
the
ter
min
al is

© 2000-2025, MetaQuotes Ltd.


700 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

sho
wn.
A
tool
tip
can
be
disa
bled
by
sett
ing
the
"\n"
(line
feed
)
valu
e to
it
OBJPROP_LEVELTEXT Lev string modifier=level number
el
desc
ripti
on
OBJPROP_FONT Font string
OBJPROP_BMPFILE The string modifier: 0-state ON, 1-state OFF
nam
e of
BMP
-file
for
Bit
map
Lab
el.
S ee
also
R es
ourc
es
OBJPROP_SYM BOL S ym string
bol
for
the

© 2000-2025, MetaQuotes Ltd.


701 Constants, Enumerations and Structures

Identifier Des Property Type


crip
tion

Cha
rt
obje
ct

For the OBJ_RECTANGLE_LABEL object ("Rectangle label" ) one of the three design modes can be set,
to which the following values of ENUM _BORDER_TYPE correspond.
ENUM_BORDER_TY PE

Identifier Description

BORDER_FL AT Flat form

BORDER_RAISED Prominent form


BORDER_SUNKEN Concave form

For the OBJ_EDIT object ("Edit" ) and for the ChartS creenS hot() function, you can specify the horizontal
alignment type using the values of the ENUM _ALIGN_MODE enumeration.
ENUM_ALIGN_MODE

Identifier Description

ALIGN_L EFT Left alignment


ALIGN_CENT ER Centered (only for the Edit object)
ALIGN_R IGH T R ight alignment

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 Label object
ObjectCreate(0,label_name,OBJ_LABEL,0,0,0);

© 2000-2025, MetaQuotes Ltd.


702 Constants, Enumerations and Structures

//--- set X coordinate


ObjectSetInteger(0,label_name,OBJPROP_XDISTANCE,200);
//--- set Y coordinate
ObjectSetInteger(0,label_name,OBJPROP_YDISTANCE,300);
//--- define text color
ObjectSetInteger(0,label_name,OBJPROP_COLOR,clrWhite);
//--- define text for object Label
ObjectSetString(0,label_name,OBJPROP_TEXT,UP);
//--- define font
ObjectSetString(0,label_name,OBJPROP_FONT,"Wingdings");
//--- define font size
ObjectSetInteger(0,label_name,OBJPROP_FONTSIZE,10);
//--- 45 degrees rotation clockwise
ObjectSetDouble(0,label_name,OBJPROP_ANGLE,-45);
//--- disable for mouse selecting
ObjectSetInteger(0,label_name,OBJPROP_SELECTABLE,false);
//--- draw it on the chart
ChartRedraw(0);
}
}

© 2000-2025, MetaQuotes Ltd.


703 Constants, Enumerations and Structures

Methods of Object Binding


Graphical objects Text, Label, Bitmap and Bitmap Label (OBJ_TEXT, OBJ_LABEL, OBJ_BITM AP and
OBJ_BITM AP_LABEL) can have one of the 9 different ways of coordinate binding defined by the
OBJPROP_ANCHOR property.

Object ID X /Y Width/He Date/Pric OBJPROP OBJPROP OBJPROP


ight e _CORNER _ANCHOR _ANGLE

Text OBJ_TEX — — Yes — Y es Yes


T
Label OBJ_LAB Yes Yes (read — Yes Y es Yes
EL only)
Button OBJ_BUT Yes Yes — Yes — —
TON
Bitmap OBJ_BIT — Yes (read Yes — Y es —
M AP only)
Bitmap OBJ_BIT Yes Yes (read — Yes Y es —
Label M AP_LAB only)
EL

Edit OBJ_EDIT Yes Yes — Yes — —

R ectangle OBJ_REC Yes Yes — Yes — —


Label TANGLE_
LABEL

The following designations are used in the table:


· X /Y – coordinates of anchor points specified in pixels relative to a chart corner;
· Width/Height – objects have width and height. For " read only" , the width and height values are
calculated only once the object is rendered on chart;
· Date/Price – anchor point coordinates are specified using the date and price values ;
· OBJPROP_CORNER – defines the chart corner relative to which the anchor point coordinates are
specified. Can be one of the 4 values of the ENUM _BASE_CORNER enumeration;
· OBJPROP_ANCHOR – defines the anchor point in object itself and can be one of the 9 values of the
ENUM _ANCH OR_POINT enumeration. Coordinates in pixels are specified from this very point to
selected chart corner;
· OBJPROP_ANGLE – defines the object rotation angle counterclock wise.

The necessary variant can be specified using the function ObjectS etInteger(chart_handle,
object_name, OBJPROP_ANCHOR, anchor_point_mode), where anchor_point_mode is one of the
values of ENUM _ANCHOR_POINT.
ENUM_ANCHOR_POINT

ID Description

ANCH OR_L EFT _UPPER Anchor point at the upper left corner

© 2000-2025, MetaQuotes Ltd.


704 Constants, Enumerations and Structures

ID Description

ANCH OR_L EFT Anchor point to the left in the center


ANCH OR_L EFT _LOWER Anchor point at the lower left corner
ANCH OR_LOWER Anchor point below in the center
ANCH OR_R IGH T _LOWER Anchor point at the lower right corner
ANCH OR_R IGH T Anchor point to the right in the center
ANCH OR_R IGH T _UPPER Anchor point at the upper right corner
ANCH OR_UPPER Anchor point above in the center
ANCH OR_CENT ER Anchor point strictly in the center of the object
The OBJ_BUTTON, OBJ_RECTANGLE_LABEL, OBJ_EDIT and OBJ_CHART objects have a fixed anchor
point in the upper left corner (ANCHOR_LEFT_UPPER).
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 object Label
ObjectCreate(0,text_name,OBJ_TEXT,0,TimeCurrent(),chart_max_price);
//--- Set color of the text
ObjectSetInteger(0,text_name,OBJPROP_COLOR,clrWhite);
//--- Set background color
ObjectSetInteger(0,text_name,OBJPROP_BGCOLOR,clrGreen);
//--- Set text for the Label object
ObjectSetString(0,text_name,OBJPROP_TEXT,TimeToString(TimeCurrent()));
//--- Set text font
ObjectSetString(0,text_name,OBJPROP_FONT,"Trebuchet MS");
//--- Set 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);
}

Graphical objects Arrow (OBJ_ARR OW ) have only 2 ways of linking their coordinates. Identifiers are
listed in ENUM _ARROW_ANCHOR.

© 2000-2025, MetaQuotes Ltd.


705 Constants, Enumerations and Structures

ENUM_ARROW_ANCHOR

ID Description

ANCH OR_TOP Anchor on the top side


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

© 2000-2025, MetaQuotes Ltd.


706 Constants, Enumerations and Structures

int upcounter=0,downcounter=0; // count there the number of arrows


bool created;// 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 "Up" arrows
{
//--- Try to create an "Up" object
created=ObjectCreate(0,string(Time[i]),OBJ_ARROW_THUMB_UP,0,Time[i],Ups[i]);
if(created)// If set up - let's make tuning for it
{
//--- Point anchor is below in order not to cover bar
ObjectSetInteger(0,string(Time[i]),OBJPROP_ANCHOR,ANCHOR_BOTTOM);
//--- Final touch - painted
ObjectSetInteger(0,string(Time[i]),OBJPROP_COLOR,clrBlue);
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 - let's make tuning for it
{
//--- Point anchor is above in order not to cover bar
ObjectSetInteger(0,string(Time[i]),OBJPROP_ANCHOR,ANCHOR_TOP);
//--- Final touch - painted
ObjectSetInteger(0,string(Time[i]),OBJPROP_COLOR,clrRed);
downcounter++;
}
}
}
}
}

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

© 2000-2025, MetaQuotes Ltd.


707 Constants, Enumerations and Structures

© 2000-2025, MetaQuotes Ltd.


708 Constants, Enumerations and Structures

The Chart Corner to Which an Object Is Attached


There is a number of graphical objects for which you can set a chart corner, relative to which the
coordinates are specified in pixels. These are the following types of objects (in brackets object type
identifiers are specified):
· Label (OBJ_LABEL);
· Button (OBJ_BUTTON);
· Bitmap Label (OBJ_BITM AP_L ABEL);
· Edit (OBJ_EDIT).
· R ectangle Label (OBJ_RECT ANGL E_L ABEL);

Object ID X /Y Width/He Date/Pric OBJPROP OBJPROP OBJPROP


ight e _CORNER _ANCHOR _ANGLE

Text OBJ_TEX — — Yes — Yes Yes


T
Label OBJ_LAB Yes Yes (read — Y es Yes Yes
EL only)
Button OBJ_BUT Yes Yes — Y es — —
TON
Bitmap OBJ_BIT — Yes (read Yes — Yes —
M AP only)
Bitmap OBJ_BIT Yes Yes (read — Y es Yes —
Label M AP_LAB only)
EL

Edit OBJ_EDIT Yes Yes — Y es — —

Rectangl OBJ_REC Yes Yes — Y es — —


e Label TANGLE_
LABEL

The following designations are used in the table:


· X /Y – coordinates of anchor points specified in pixels relative to a chart corner;
· Width/Height – objects have width and height. For " read only" , the width and height values are
calculated only once the object is rendered on chart;
· Date/Price – anchor point coordinates are specified using the date and price values ;
· OBJPROP_CORNER – defines the chart corner relative to which the anchor point coordinates are
specified. Can be one of the 4 values of the ENUM _BASE_CORNER enumeration;
· OBJPROP_ANCHOR – defines the anchor point in object itself and can be one of the 9 values of the
ENUM _ANCH OR_POINT enumeration. Coordinates in pixels are specified from this very point to
selected chart corner;
· OBJPROP_ANGLE – defines the object rotation angle counterclock wise.

In order to specify the chart corner, from which X and Y coordinates will be measured in pixels, use
ObjectS etInteger(chartID, name, OBJPROP_CORNER, chart_corner), where:

© 2000-2025, MetaQuotes Ltd.


709 Constants, Enumerations and Structures

· chartID - chart identifier;


· name – name of a graphical object;
· OBJPROP_CORNER – property ID to specify the corner for binding;
· chart_corner – the desired chart corner, can be one of the values of the ENUM _BASE_CORNER
enumeration.
ENUM_BASE_CORNER

ID Description

CORNER_LEFT_UPPER Center of coordinates is in the upper left corner


of the chart
CORNER_LEFT_LOWER Center of coordinates is in the lower left corner
of the chart
CORNER_RIGHT_LOWER Center of coordinates is in the lower right corner
of the chart
CORNER_RIGHT_UPPER Center of coordinates is in the upper right
corner of the chart
Example:

void CreateLabel(long chart_id,


string name,
int chart_corner,
int anchor_point,
string text_label,
int x_ord,
int y_ord)
{
//---
if(ObjectCreate(chart_id,name,OBJ_LABEL,0,0,0))
{
ObjectSetInteger(chart_id,name,OBJPROP_CORNER,chart_corner);
ObjectSetInteger(chart_id,name,OBJPROP_ANCHOR,anchor_point);
ObjectSetInteger(chart_id,name,OBJPROP_XDISTANCE,x_ord);
ObjectSetInteger(chart_id,name,OBJPROP_YDISTANCE,y_ord);
ObjectSetString(chart_id,name,OBJPROP_TEXT,text_label);
}
else
Print("Failed to create the object OBJ_LABEL ",name,", Error code = ", GetLastError());
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int height=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);

© 2000-2025, MetaQuotes Ltd.


710 Constants, Enumerations and Structures

int width=(int)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,ANCHOR_LEFT_UPPER,arrows[0],50,50);
CreateLabel(0,arrows[1],CORNER_RIGHT_UPPER,ANCHOR_RIGHT_UPPER,arrows[1],50,50);
CreateLabel(0,arrows[2],CORNER_RIGHT_LOWER,ANCHOR_RIGHT_LOWER,arrows[2],50,50);
CreateLabel(0,arrows[3],CORNER_LEFT_LOWER,ANCHOR_LEFT_LOWER,arrows[3],50,50);
}

© 2000-2025, MetaQuotes Ltd.


711 Constants, Enumerations and Structures

Visibility of Objects
The combination of object visibility flags determines chart timeframes, where the object is visible. To
set/get the value of the OBJPROP_TIM EFRAM ES property, you can use functions
ObjectS etInteger()/ObjectGetInteger().
ID Value Description

OBJ_NO_PERIODS 0 The object is not drawn in all


timeframes
OBJ_PERIOD_M 1 0x 00000001 The object is drawn in 1-
minute chart
OBJ_PERIOD_M 2 0x 00000002 The object is drawn in 2-
minute chart
OBJ_PERIOD_M 3 0x 00000004 The object is drawn in 3-
minute chart
OBJ_PERIOD_M 4 0x 00000008 The object is drawn in 4-
minute chart
OBJ_PERIOD_M5 0x 00000010 The object is drawn in 5-
minute chart
OBJ_PERIOD_M 6 0x 00000020 The object is drawn in 6-
minute chart
OBJ_PERIOD_M 10 0x 00000040 The object is drawn in 10-
minute chart
OBJ_PERIOD_M 12 0x 00000080 The object is drawn in 12-
minute chart
OBJ_PERIOD_M 15 0x 00000100 The object is drawn in 15-
minute chart
OBJ_PERIOD_M 20 0x 00000200 The object is drawn in 20-
minute chart
OBJ_PERIOD_M 30 0x 00000400 The object is drawn in 30-
minute chart
OBJ_PERIOD_H1 0x 00000800 The object is drawn in 1-hour
chart
OBJ_PERIOD_H2 0x 00001000 The object is drawn in 2-hour
chart
OBJ_PERIOD_H3 0x 00002000 The object is drawn in 3-hour
chart
OBJ_PERIOD_H4 0x 00004000 The object is drawn in 4-hour
chart

© 2000-2025, MetaQuotes Ltd.


712 Constants, Enumerations and Structures

ID Value Description

OBJ_PERIOD_H6 0x 00008000 The object is drawn in 6-hour


chart
OBJ_PERIOD_H8 0x 00010000 The object is drawn in 8-hour
chart
OBJ_PERIOD_H12 0x 00020000 The object is drawn in 12-hour
chart
OBJ_PERIOD_D1 0x 00040000 The object is drawn in day
charts
OBJ_PERIOD_W1 0x 00080000 The object is drawn in week
charts
OBJ_PERIOD_M N1 0x 00100000 The object is drawn in month
charts
OBJ_ALL_PERIODS 0x 001fffff The object is drawn in all
timeframes
Visibility flags can be combined using the symbol "|" , for example, the combination of flags
OBJ_PERIOD_M 10|OBJ_PERIOD_H4 means that the object will be visible on the 10-minute and 4-hour
timeframes.
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 the Horizontal Line object
}
//--- Set value for the price level for the line highlevel
ObjectSetDouble(0,highlevel,OBJPROP_PRICE,0,prevHigh);

© 2000-2025, MetaQuotes Ltd.


713 Constants, Enumerations and Structures

//--- 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 the Horizontal Line object
}
//--- 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); // redraw the chart forcibly


}

See also

PeriodS econds, Period, Chart timeframes, Date and Time

© 2000-2025, MetaQuotes Ltd.


714 Constants, Enumerations and Structures

Levels of Elliott Wave


Elliott W aves are represented by two graphical objects of types OBJ_ELLIOTWAVE5 and
OBJ_ELLIOTWAVE3. To set the wave size (method of wave labeling), the OBJPROP_DEGREE property is
used, to which one of values of the ENUM _ELLIOT_WAVE_DEGREE enumeration can be assigned.
ENUM_ELLIOT_WAVE_DEGREE

ID Description

ELLIOTT _GRAND_SUPER CYCL E Grand S upercycle

ELLIOTT _SUPER CYCL E S upercycle

ELLIOTT _CYCL E Cycle


ELLIOTT _PR IM ARY Primary
ELLIOTT _INT ER M EDIAT E Intermediate
ELLIOTT _MINOR Minor
ELLIOTT _MINUT E Minute
ELLIOTT _MINUETT E Minuette
ELLIOTT _SUBMINUETT E S ubminuette

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)))
{
//--- set the marking level in INTERMEDIATE
ObjectSetInteger(0,currobj,OBJPROP_DEGREE,ELLIOTT_INTERMEDIATE);
//--- show lines between tops of waves
ObjectSetInteger(0,currobj,OBJPROP_DRAWLINES,true);
//--- set line color
ObjectSetInteger(0,currobj,OBJPROP_COLOR,clrBlue);
//--- set line width
ObjectSetInteger(0,currobj,OBJPROP_WIDTH,5);
//--- set description
ObjectSetString(0,currobj,OBJPROP_TEXT,"test script");
}
}

© 2000-2025, MetaQuotes Ltd.


715 Constants, Enumerations and Structures

Gann Objects
For Gann Fan (OBJ_GANNFAN) and Gann Grid (OBJ_GANNGR ID) objects you can specify two values of
the ENUM _GANN_DIRECTION enumeration that sets the trend direction.
ENUM_GANN_DIRECTION

ID Description

GANN_UP_T REND Line corresponding to the uptrend line


GANN_DOWN_T REND Line corresponding to the downward trend
To set the scale of the main line as 1x1, use function ObjectS etDouble(chart_handle,
gann_object_name, OBJPROP_S CALE, scale), where:
· chart_handle – chart window where the object is located;
· gann_object_name – object name;
· OBJPROP_S CALE – identifier of the "S cale" property;
· scale – required scale in units of Pips /Bar.

Example of creating Gann Fan:

void OnStart()
{
//---
string my_gann="OBJ_GANNFAN object";
if(ObjectFind(0,my_gann)<0)// Object not found
{
//--- Inform about the failure
Print("Object ",my_gann," not found. Error code = ",GetLastError());
//--- Get the maximal price of the chart
double chart_max_price=ChartGetDouble(0,CHART_PRICE_MAX,0);
//--- Get the minimal price of the chart
double chart_min_price=ChartGetDouble(0,CHART_PRICE_MIN,0);
//--- How many bars are shown in the chart?

© 2000-2025, MetaQuotes Ltd.


716 Constants, Enumerations and Structures

int bars_on_chart=ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- Create an array, to write the opening time of each bar to
datetime Time[];
//--- Arrange access to the array as that of timeseries
ArraySetAsSeries(Time,true);
//--- Now copy data of bars visible in the chart into this array
int times=CopyTime(NULL,0,0,bars_on_chart,Time);
if(times<=0)
{
Print("Could not copy the array with the open time!");
return;
}
//--- Preliminary preparations completed

//--- Index of the central bar in 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 to 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[c
//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,clrYellowGreen);
//--- 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);
}
}

© 2000-2025, MetaQuotes Ltd.


717 Constants, Enumerations and Structures

Web Colors
The following color constants are defined for the color type:

clrBlac k clrDarkGre clrDarkSlat clrOlive clrGreen clrTeal clrNavy clrPurple


en eGray
clrMaroon clrIndigo clrMidnigh clrDarkBlu clrDarkOliv clrSaddleB clrForestG clrOliveDra
tBlue e eGreen rown reen b
clrSeaGre clrDarkGol clrDarkSlat clrSienna clrMedium clrBrown clrDarkTur clrDimGray
en denrod eBlue Blue quoise

clrLightSe clrDarkViol clrFireBric clrMedium clrMedium clrChocola clrCrimson clrSteelBlu


aGreen et k VioletRed SeaGreen te e
clrGoldenr clrMedium clrLawnGr clrCadetBl clrDarkOrc clrYellowG clrLimeGre clrOrange
od SpringGre een ue hid reen en Red
en
clrDarkOra clrOrange clrGold clrYellow clrChartre clrLime clrSpringG clrAqua
nge use reen
clrDeepSk clrBlue clrMagent clrRed clrGray clrSlateGra clrPeru clrBlueViol
yBlue a y et
clrLightSla clrDeepPin clrMedium clrDodgerB clrTurquoi clrRoyalBlu clrSlateBlu clrDarkKha
teGray k Turquoise lue se e e ki

clrIndianR clrMedium clrGreenY clrMedium clrDarkSea clrTomato clrRosyBro clrOrchid


ed Orchid ellow Aquamarin Green wn
e
clrMedium clrPaleViol clrCoral clrCornflo clrDarkGra clrSandyBr clrMedium clrTan
Purple etRed werBlue y own Slate Blue

clrDarkSal clrBurlyWo clrHotPink clrSalmon clrViolet clrLightCor clrSkyBlue clrLightSal


mon od al mon
clrPlum clrKhaki clrLightGr clrAquama clrSilver clrLightSky clrLightSte clrLightBlu
een rine Blue elBlue e
clrPaleGre clrThistle clrPowder clrPaleGol clrPaleTur clrLightGra clrWheat clrNavajo W
en Blue denrod quoise y hite
clrMoccasi clrLightPin clrGainsbo clrPeachP clrPink clrBisque clrLightGol clrBlanche
n k ro uff denrod dAlmond
clrLemonC clrBeige clrAntique clrPapaya clrCornsilk clrLightYel clrLightCya clrLinen
hiffon White Whip low n
clrLavende clrMistyRo clrOldLace clrWhiteS clrSeashell clrIvory clrHoneyd clrAliceBlu
r se mo ke ew e
clrLavend clrMintCre clrSnow clrWhite
erBlush am

Color can be set to an object using the ObjectS etInteger() function. For setting color to custom
indicators the PlotIndexS etInteger() function is used. For getting color values there are similar
functions ObjectGetInteger() and PlotIndexGetInteger().

© 2000-2025, MetaQuotes Ltd.


718 Constants, Enumerations and Structures

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 clrBlue
#property indicator_color2 clrRed
#property indicator_color3 clrLime

© 2000-2025, MetaQuotes Ltd.


719 Constants, Enumerations and Structures

Wingdings
Characters of W ingdings used with the OBJ_ARROW object:

A necessary character can be set using the ObjectS etInteger() function.


Example:

void OnStart()
{
//---
string up_arrow="up_arrow";
datetime time=TimeCurrent();
double lastClose[1];
int close=CopyClose(Symbol(),Period(),0,1,lastClose); // Get the Close price
//--- If the price was obtained
if(close>0)
{
ObjectCreate(0,up_arrow,OBJ_ARROW,0,0,0,0,0); // Create an 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 Close price!");
}

© 2000-2025, MetaQuotes Ltd.


720 Constants, Enumerations and Structures

Indicators Constants
There are 37 predefined technical indicators, which can be used in programs written in the MQL5
language. In addition, there is an opportunity to create custom indicators using the iCustom()
function. All constants required for that are divided into 5 groups :
· Price constants – for selecting the type of price or volume, on which an indicator is calculated;
· S moothing methods – built-in smoothing methods used in indicators ;
· Indicator lines – identifiers of indicator buffers when accessing indicator values using CopyBuffer();
· Drawing styles – for indicating one of 18 types of drawing and setting the line drawing style;
· Custom indicators properties are used in functions for working with custom indicators ;
· Types of indicators are used for specifying the type of technical indicator when creating a handle
using IndicatorCreate();
· Identifiers of data types are used for specifying the type of data passed in an array of the M qlParam
type into the IndicatorCreate() function.

© 2000-2025, MetaQuotes Ltd.


721 Constants, Enumerations and Structures

Price Constants
Calculations of technical indicators require price values and/or values of volumes, on which
calculations will be performed. There are 7 predefined identifiers from the ENUM _APPLIED_PRICE
enumeration, used to specify the desired price base for calculations.
ENUM_APPLIED_PRICE

ID Description

PRICE_CLOSE Close price


PRICE_OPEN Open price
PRICE_HIGH The maximum price for the period
PRICE_LOW The minimum price for the period
PRICE_M EDIAN Median price, (high + low)/2
PRICE_TYPICAL Typical price, (high + low + close)/3
PRICE_WEIGHTED Average price, (high + low + close + close)/4
If the volume is used in calculations, it's necessary to specify one of the two values from the
ENUM _APPLIED_VOL UM E enumeration.

ENUM_APPLIED_VOLUME

ID Description

VOL UM E_TICK Tick volume


VOL UM E_REAL Trade volume
The iS tochastic() technical Indicator can be calculated in two ways using:
· either only Close prices ;
· or H igh and Low prices.

To select a necessary variant for calculation, specify one of the values of the ENUM _S TO_PR ICE
enumeration.
ENUM_STO_PRICE

ID Description

S TO_LOWH IGH Calculation is based on Low/High prices


S TO_CLOSECLOSE Calculation is based on Close/Close prices
If a technical indicator uses for calculations price data, type of which is set by ENUM _APPLIED_PRICE,
then handle of any indicator (built in the terminal or written by a user) can be used as the input price
series. In this case, values of the zero buffer of the indicator will be used for calculations. This makes
it easy to build values of one indicator using values of another indicator. The handle of a custom
indicator is created by calling the iCustom() function.

© 2000-2025, MetaQuotes Ltd.


722 Constants, Enumerations and Structures

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 clrRed
#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 clrNavy
#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[]
)

© 2000-2025, MetaQuotes Ltd.


723 Constants, Enumerations and Structures

//--- Reset the 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 using values of RSI
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);
}

© 2000-2025, MetaQuotes Ltd.


724 Constants, Enumerations and Structures

Smoothing Methods
Many technical indicators are based on various methods of the price series smoothing. S ome standard
technical indicators require specification of the smoothing type as an input parameter. For specifying
the desired type of smoothing, identifiers listed in the ENUM _M A_M ETHOD enumeration are used.
ENUM_MA_METHOD

ID Description

MODE_S M A S imple averaging

MODE_EM A Exponential averaging

MODE_S MM A S moothed averaging

MODE_LW M A 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);

© 2000-2025, MetaQuotes Ltd.


725 Constants, Enumerations and Structures

Indicators Lines
S ome technical indicators have several buffers drawn in the chart. Numbering of indicator buffers
starts with 0. W hen copying indicator values using the CopyBuffer() function into an array of the
double type, for some indicators one may indicate the identifier of a copied buffer instead of its
number.

Identifiers of indicator lines permissible when copying values of iM ACD(), iRVI() and iS tochastic().
Constant Value Description

M AIN_LINE 0 Main line


S IGNAL _LINE 1 S ignal line

Identifiers of indicator lines permissible when copying values of ADX() and ADXW ().
Constant Value Description

M AIN_LINE 0 Main line


PLUSDI_LINE 1 Line +DI
MINUSDI_LINE 2 Line –DI
Identifiers of indicator lines permissible when copying values of iBands().
Constant Value Description

BASE_LINE 0 Main line


UPPER_BAND 1 Upper limit
LOWER_BAND 2 Lower limit
Identifiers of indicator lines permissible when copying values of iEnvelopes() and iFractals().
Constant Value Description

UPPER_LINE 0 Upper line


LOWER_LINE 1 Bottom line
Identifiers of indicator lines permissible when copying values of iGator()
Constant Value Description

UPPER_H IS TOGRAM 0 Upper histogram


LOWER_HIS TOGRAM 2 Bottom histogram
Identifiers of indicator lines permissible when copying values of iAlligator().

© 2000-2025, MetaQuotes Ltd.


726 Constants, Enumerations and Structures

Constant Value Description

GATORJAW_LINE 0 Jaw line

GATOR T EET H_LINE 1 Teeth line


GATOR LIPS_LINE 2 Lips line
Identifiers of indicator lines permissible when copying values of iIchimoku().
Constant Value Description

TENKANSEN_LINE 0 Tenkan-sen line


KIJUNSEN_LINE 1 Kijun-sen line

SENKOUS PANA_LINE 2 S enk ou S pan A line


SENKOUS PANB_LINE 3 S enk ou S pan B line

CHIKOUS PAN_LINE 4 Chikou S pan line

© 2000-2025, MetaQuotes Ltd.


727 Constants, Enumerations and Structures

Drawing Styles
W hen creating a custom indicator, you can specify one of 18 types of graphical plotting (as displayed
in the main chart window or a chart subwindow), whose values are specified in the ENUM _DRAW_TYPE
enumeration.
In one custom indicator, it is permissible to use any indicator building/drawing types. Each
construction type requires specification of one to five global arrays for storing data necessary for
drawing. These data arrays must be bound with indicator buffers using the S etIndexBuffer() function.
The type of data from ENUM _INDEXBUFFER_TYPE should be specified for each buffer.
Depending on the drawing style, you may need one to four value buffers (mark ed as
INDICATOR_DATA). If a style admits dynamic alternation of colors (all styles contain COLOR in their
names), then you'll need one more buffer of color (indicated type INDICATOR_COLOR_INDEX). The
color buffers are always bound after value buffers corresponding to the style.
ENUM_DRAW_TY PE

ID Descripti Data buffers Color buffers


on

DRAW_NONE Not
1 0
drawn
DRAW_LINE Line 1 0

DRAW_SECTION S ection 1 0

DRAW_H IS TOGRAM H istogra


m from
1 0
the zero
line
DRAW_H IS TOGRAM 2 H istogra
m of the
two 2 0
indicator
buffers
DRAW_ARR OW Drawing
1 0
arrows
DRAW_ZIGZAG S tyle
Zig zag
allows
vertical 2 0
section
on the
bar
DRAW_FILLING Color fill
between
2 0
the two
levels

© 2000-2025, MetaQuotes Ltd.


728 Constants, Enumerations and Structures

ID Descripti Data buffers Color buffers


on

DRAW_BARS Display
as a
4 0
sequence
of bars
DRAW_CANDL ES Display
as a
sequence
4 0
of
candlesti
cks
DRAW_COLOR_LINE Multicolo
1 1
red line
DRAW_COLOR_SECTION Multicolo
red 1 1
section
DRAW_COLOR_H IS TOGRAM Multicolo
red
histogra
1 1
m from
the zero
line
DRAW_COLOR_H IS TOGRAM 2 Multicolo
red
histogra
m of the 2 1
two
indicator
buffers
DRAW_COLOR_ARR OW Drawing
multicolo
1 1
red
arrows
DRAW_COLOR_ZIGZAG Multicolo
red 2 1
Zig Zag

DRAW_COLOR_BARS Multicolo
4 1
red bars
DRAW_COLOR_CANDL ES Multicolo
red
4 1
candlesti
cks

© 2000-2025, MetaQuotes Ltd.


729 Constants, Enumerations and Structures

To refine the display of the selected drawing type identifiers listed in ENUM _PLOT _PR OPER T Y are
used.
For functions PlotIndexS etInteger() and PlotIndexGetInteger()
ENUM_PLOT_PROPERTY _INTEGER

ID Description Property type

PLOT_ARROW Arrow code for uchar


style
DRAW_ARR OW

PLOT_ARROW_SHIFT Verticalshift of int


arrows for style
DRAW_ARR OW

PLOT_DRAW_BEGIN Number of initial int


bars without
drawing and
values in the
DataW indow

PLOT_DRAW_TYPE Type of graphical ENUM _DRAW_T YPE


construction
PLOT_SHOW_DATA S ignof display of bool
construction
values in the
DataW indow

PLOT_SHIFT S hift of indicator int


plotting along the
time axis in bars
PLOT_LINE_S TYLE Drawing line ENUM _LINE_S T YL E
style
PLOT_LINE_W IDTH The thickness of int
the drawing line
PLOT_COLOR_INDEXES The number of int
colors
PLOT_LINE_COLOR The index of a color modifier = index number of colors
buffer containing
the drawing color
For the function PlotIndexS etDouble()
ENUM_PLOT_PROPERTY _DOUBLE

ID Description Property type

PLOT_EMPTY_VALUE An empty value double


for plotting, for

© 2000-2025, MetaQuotes Ltd.


730 Constants, Enumerations and Structures

ID Description Property type

which there is no
drawing
For the function PlotIndexS etS tring()
ENUM_PLOT_PROPERTY _STRING

ID Description Property type

PLOT_LABEL The name of the string


indicator
graphical series
to display in the
DataW indow.
W hen working
with complex
graphical styles
requiring several
indicator buffers
for display, the
names for each
buffer can be
specified using
";" as a
separator.
S ample code is
shown in
DRAW_CANDL ES

5 styles can be used for drawing lines in custom indicators. They are valid only for the line thickness 0
or 1.
ENUM_LINE_STY LE

ID Description

S T YL E_S OLID S olid line

S T YL E_DASH Brok en line

S T YL E_DOT Dotted line

S T YL E_DASHDOT Dash-dot line

S T YL E_DASHDOT DOT Dash - two points

To set the line drawing style and the type of drawing, the PlotIndexS etInteger() function is used. For
the Fibonacci extensions the thickness and drawing style of levels can be indicated using the
ObjectS etInteger() function.
Example:

© 2000-2025, MetaQuotes Ltd.


731 Constants, Enumerations and Structures

#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,clrRed);
//--- Set line thickness
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,1);
//--- Set labels for the line
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);
}

© 2000-2025, MetaQuotes Ltd.


732 Constants, Enumerations and Structures

Custom Indicators Properties


The number of indicator buffers that can be used in a custom indicator is unlimited. But for each
array, which is designated as the indicator buffer using the S etIndexBuffer() function, it's necessary to
specify the data type that it will store. This may be one of the values of the ENUM _INDEXBUFFER_TYPE
enumeration.
ENUM_INDEX BUFFER_TY PE

ID Description

INDICATOR_DATA Data to draw


INDICATOR_COLOR_INDEX Color
INDICATOR_CALCULATIONS Auxiliary buffers for intermediate calculations
A custom indicator has a lot of settings to provide convenient displaying. These settings are made
through the assignment of corresponding indicator properties using functions IndicatorS etDouble(),
IndicatorS etInteger() and IndicatorS etS tring(). Identifiers of indicator properties are listed in the
ENUM _CUS TOMIND_PR OPER T Y enumeration.

ENUM_CUSTOMIND_PROPERTY _INTEGER

ID Des Property type


crip
tion

INDICATOR_DIGITS Acc int


urac
y of
dra
win
g of
indi
cato
r
valu
es
INDICATOR_HEIGHT Fixe int
d
heig
ht
of
the
indi
cato
r's
win
dow
(the
prep

© 2000-2025, MetaQuotes Ltd.


733 Constants, Enumerations and Structures

ID Des Property type


crip
tion

roce
ssor
com
man
d
#pro
pert
y
indi
cato
r_he
ight
)
INDICATOR_LEVELS Num int
ber
of
leve
ls in
the
indi
cato
r
win
dow
INDICATOR_LEVELCOLOR Colo color modifier = level number
r of
the
leve
l
line
INDICATOR_LEVELS TYLE S tyl ENUM _LINE_S T YL E modifier = level number
e of
the
leve
l
line
INDICATOR_LEVELW IDTH Thic int modifier = level number
k ne
ss
of
the
leve
l
line

© 2000-2025, MetaQuotes Ltd.


734 Constants, Enumerations and Structures

ID Des Property type


crip
tion

INDICATOR_FIXED_MINIM UM Fixe bool


d
mini
mu
m
for
the
indi
cato
r
win
dow
.
The
prop
erty
can
only
be
writ
ten
by
the
Indi
cato
rS et
Inte
ger(
)
func
tion
INDICATOR_FIXED_M AXIM UM Fixe bool
d
max
imu
m
for
the
indi
cato
r
win
dow
.
The
prop
erty

© 2000-2025, MetaQuotes Ltd.


735 Constants, Enumerations and Structures

ID Des Property type


crip
tion

can
only
be
writ
ten
by
the
Indi
cato
rS et
Inte
ger(
)
func
tion
ENUM_CUSTOMIND_PROPERTY _DOUBLE

ID Des Property type


crip
tion

INDICATOR_MINIM UM Mini double


mu
m
of
the
indi
cato
r
win
dow
INDICATOR_M AXIM UM Max double
imu
m
of
the
indi
cato
r
win
dow
INDICATOR_LEVELVALUE Lev double modifier = level number
el
valu
e

© 2000-2025, MetaQuotes Ltd.


736 Constants, Enumerations and Structures

ENUM_CUSTOMIND_PROPERTY _STRING

ID Des Property type


crip
tion

INDICATOR_SHORTNAM E S hor string


t
indi
cato
r
nam
e
INDICATOR_LEVELTEXT Lev string modifier = level number
el
desc
ripti
on
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 clrLightSeaGreen
#property indicator_color2 clrRed
//--- 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);

© 2000-2025, MetaQuotes Ltd.


737 Constants, Enumerations and Structures

//--- 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 which 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 to empty value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0.0);
//--- initialization done
}

© 2000-2025, MetaQuotes Ltd.


738 Constants, Enumerations and Structures

Types of Technical Indicators


There are two ways to create an indicator handle for further accessing to its values. The first way is to
directly specify a function name from the list of technical indicators. The second method using the
IndicatorCreate() is to uniformly create a handle of any indicator by assigning an identifier from the
ENUM _INDICATOR enumeration. Both ways of handle creation are equal, you can use the one that is
most convenient in a particular case when writing a program in MQL5.
W hen creating an indicator of type IND_CUS TOM, the type field of the first element of an array of
input parameters M qlParam must have the TYPE_S TRING value of the enumeration ENUM _DATATYPE,
while the field string_value of the first element must contain the name of the custom indicator.
ENUM_INDICATOR

Identifier Indicator

IND_AC Accelerator Oscillator


IND_AD Accumulation/Distribution

IND_ADX Average Directional Index

IND_ADXW ADX by W elles W ilder

IND_ALLIGATOR Alligator

IND_AM A Adaptive Moving Average

IND_AO Awesome Oscillator

IND_ATR Average True R ange

IND_BANDS Bollinger Bands ®

IND_BEARS Bears Power


IND_BULLS Bulls Power
IND_BW M FI Market Facilitation Index
IND_CCI Commodity Channel Index
IND_CHAIKIN Chaikin Oscillator
IND_CUS TOM Custom indicator
IND_DEM A Double Exponential Moving Average

IND_DEM ARKER DeMark er

IND_ENVELOPES Envelopes

IND_FORCE Force Index

IND_FRACTALS Fractals

IND_FRAM A Fractal Adaptive Moving Average

IND_GATOR Gator Oscillator

© 2000-2025, MetaQuotes Ltd.


739 Constants, Enumerations and Structures

Identifier Indicator

IND_ICHIMOKU Ichimoku Kinko Hyo


IND_M A Moving Average
IND_M ACD M A CD
IND_M FI Money Flow Index
IND_MOM ENTUM Momentum
IND_OBV On Balance Volume
IND_OS M A OsM A
IND_RS I R elative S trength Index

IND_RVI R elative Vigor Index


IND_SAR Parabolic SAR
IND_S TDDEV S tandard Deviation

IND_S TOCHAS TIC S tochastic Oscillator

IND_TEM A Triple Exponential Moving Average


IND_TRIX Triple Exponential Moving Averages Oscillator
IND_VIDYA Variable Index Dynamic Average

IND_VOLUM ES Volumes

IND_W PR W illiams ' Percent R ange

© 2000-2025, MetaQuotes Ltd.


740 Constants, Enumerations and Structures

Data Type Identifiers


W hen creating an indicator handle using the IndicatorCreate() function, an array of M qlParam type
must be specified as the last parameter. Accordingly, the M qlParam structure, describing indicator,
contains a special field type. This field contains information about the data type (real, integer or
string type) that are passed by a particular element of the array. The value of this field of the
M qlParam structure may be one of ENUM _DATATYPE values.
ENUM_DATATY PE

Identifier Data type

TYPE_BOOL bool
TYPE_CHAR char
TYPE_UCHAR uchar
TYPE_SHORT short
TYPE_USHORT ushort
TYPE_COLOR color
TYPE_INT int
TYPE_UINT uint
TYPE_DATETIM E datetime
TYPE_LONG long
TYPE_ULONG ulong
TYPE_FLOAT float
TYPE_DOUBLE double
TYPE_S TRING string
Each element of the array describes the corresponding input parameter of a created technical
indicator, so the type and order of elements in the array must be strictly maintained in accordance
with the description.

© 2000-2025, MetaQuotes Ltd.


741 Constants, Enumerations and Structures

Environment State
Constants describing the current runtime environment of an mql5-program are divided into groups :
· Client terminal properties – information about the client terminal;
· Executed MQL5-program properties – mql5 program properties, which help to control its execution;
· S ymbol properties – obtaining information about a symbol;
· Account properties – information about the current account;
· Testing S tatistics – results of Expert Advisor testing.

© 2000-2025, MetaQuotes Ltd.


742 Constants, Enumerations and Structures

Client Terminal Properties


Information about the client terminal can be obtained by two functions : TerminalInfoInteger() and
TerminalInfoS tring(). For parameters, these functions accept values from
ENUM _T ER MINAL _INFO_INT EGER and ENUM _T ER MINAL _INFO_S T R ING respectively.

ENUM_TERMINAL_INFO_INTEGER

Identifier Description Type

TERMINAL_BUILD The client terminal build number int


TERMINAL_COMM UNITY_ACCOUNT The flag indicates the presence of bool
MQL5.community authorization
data in the terminal
TERMINAL_COMM UNITY_CONNECTION Connection to MQL5.community bool
TERMINAL_CONNECTED Connection to a trade server bool
TERMINAL_DLLS_ALLOWED Permission to use DLL bool
TERMINAL_TRADE_ALLOWED Permission to trade bool
TERMINAL_EM AIL_ENABLED Permission to send e-mails using bool
S MTP-server and login, specified
in the terminal settings
TERMINAL_FTP_ENABLED Permission to send reports using bool
FTP-server and login, specified in
the terminal settings
TERMINAL_NOTIFICATIONS_ENABLED Permission to send notifications to bool
smartphone
TERMINAL_M AXBARS The maximal bars count on the int
chart
TERMINAL_MQID The flag indicates the presence of bool
MetaQuotes ID data for Push
notifications
TERMINAL_CODEPAGE Number of the code page of the int
language installed in the client
terminal
TERMINAL_CPU_CORES The number of CPU cores in the int
system
TERMINAL_DISK_S PACE Free dis k space for the MQL5\Files int
folder of the terminal (agent), M B
TERMINAL_M EMORY_PHYS ICAL Physical memory in the system, M B int
TERMINAL_M EMORY_TOTAL Memory available to the process of int
the terminal (agent), M B

© 2000-2025, MetaQuotes Ltd.


743 Constants, Enumerations and Structures

Identifier Description Type

TERMINAL_M EMORY_AVAILABLE Free memory of the terminal int


(agent) process, M B
TERMINAL_M EMORY_USED Memory used by the terminal int
(agent), M B
TERMINAL_X64 Indication of the "64-bit terminal" bool
TERMINAL_OPENCL_SUPPORT The version of the supported int
OpenCL in the format of
0x 00010002 = 1.2. "0" means that
OpenCL is not supported
TERMINAL_S CREEN_DPI The resolution of information int
display on the screen is measured
as number of Dots in a line per
Inch (DPI).
Knowing the parameter value, you
can set the size of graphical
objects so that they look the same
on monitors with different
resolution characteristics.
TERMINAL_S CREEN_LEFT The left coordinate of the virtual int
screen. A virtual screen is a
rectangle that covers all monitors.
If the system has two monitors
ordered from right to left, then
the left coordinate of the virtual
screen can be on the border of two
monitors.
TERMINAL_S CREEN_TOP The top coordinate of the virtual int
screen
TERMINAL_S CREEN_W IDTH Terminal width int
TERMINAL_S CREEN_HEIGHT Terminal height int
TERMINAL_LEFT The left coordinate of the terminal int
relative to the virtual screen
TERMINAL_TOP The top coordinate of the terminal int
relative to the virtual screen
TERMINAL_RIGHT The right coordinate of the int
terminal relative to the virtual
screen
TERMINAL_BOTTOM The bottom coordinate of the int
terminal relative to the virtual
screen

© 2000-2025, MetaQuotes Ltd.


744 Constants, Enumerations and Structures

Identifier Description Type

TERMINAL_PING_LAS T The last known value of a ping to a int


trade server in microseconds. One
second comprises of one million
microseconds
TERMINAL_VPS Indication that the terminal is bool
launched on the MetaTrader Virtual
H osting server (MetaTrader VPS )

Key identifier Description

TERMINAL_KEYS TATE_LEFT S tate of the " Left arrow" key int


TERMINAL_KEYS TATE_UP S tate of the "Up arrow" key int
TERMINAL_KEYS TATE_RIGHT S tate of the "Right arrow" key int
TERMINAL_KEYS TATE_DOWN S tate of the "Down arrow" key int
TERMINAL_KEYS TATE_SHIFT S tate of the "S hift" key int
TERMINAL_KEYS TATE_CONTROL S tate of the " Ctrl" key int
TERMINAL_KEYS TATE_M ENU S tate of the "W indows " key int
TERMINAL_KEYS TATE_CAPS LOCK S tate of the " CapsLock" key int
TERMINAL_KEYS TATE_NUMLOCK S tate of the "NumLock" key int
TERMINAL_KEYS TATE_S CRLOCK S tate of the "S crollLock" key int
TERMINAL_KEYS TATE_ENTER S tate of the "Enter" key int
TERMINAL_KEYS TATE_INSERT S tate of the " Insert" key int
TERMINAL_KEYS TATE_DELETE S tate of the "Delete" key int
TERMINAL_KEYS TATE_HOM E S tate of the "Home" key int
TERMINAL_KEYS TATE_END S tate of the "End" key int
TERMINAL_KEYS TATE_TAB S tate of the " Tab" key int
TERMINAL_KEYS TATE_PAGEUP S tate of the " PageUp" key int
TERMINAL_KEYS TATE_PAGEDOWN S tate of the " PageDown" key int
TERMINAL_KEYS TATE_ES CAPE S tate of the "Escape" key int

Call to TerminalInfoInteger(TERMINAL_KEYS TATE_XXX) returns the same state code of a key as the
GetKeyS tate() function in M SDN.

Example of scaling factor calculation:


//--- Creating a 1.5 inch wide button on a screen
int screen_dpi = TerminalInfoInteger(TERMINAL_SCREEN_DPI); // Find DPI of the user monitor

© 2000-2025, MetaQuotes Ltd.


745 Constants, Enumerations and Structures

int base_width = 144; // The basic width in the screen points


int width = (button_width * screen_dpi) / 96; // Calculate the button width for the us
...

//--- Calculating the scaling factor as a percentage


int scale_factor=(TerminalInfoInteger(TERMINAL_SCREEN_DPI) * 100) / 96;
//--- Use of the scaling factor
width=(base_width * scale_factor) / 100;

In the above example, the graphical resource looks the same on monitors with different resolution
characteristics. The size of control elements (buttons, dialog windows, etc.) corresponds to
personalization settings.

ENUM_TERMINAL_INFO_DOUBLE

Identifier Description Type

TERMINAL_COMM UNITY_BALANCE Balance in MQL5.community double


TERMINAL_RETRANS MISS ION Percentage of resent network double
packets in the TCP/IP protocol for
all running applications and
services on the given computer.
Packet loss occurs even in the
fastest and correctly configured
networks. In this case, there is no
confirmation of packet delivery
between the recipient and the
sender, therefore lost packets are
resent.

It is not an indication of the


connection quality between a
particular terminal and a trade
server, since the percentage is
calculated for the entire network
activity, including system and
background activity.

The TERMINAL_RETRANS MISS ION


value is requested from the
operating system once per minute.
The terminal itself does not
calculate this value.

File operations can be performed only in two directories ; corresponding paths can be obtained using
the request for TERMINAL_DATA_PATH and TERMINAL_COMMONDATA_PATH properties.
ENUM_TERMINAL_INFO_STRING

© 2000-2025, MetaQuotes Ltd.


746 Constants, Enumerations and Structures

Identifier Description Type

TERMINAL_LANGUAGE Language of the terminal string


TERMINAL_COMPANY Company name string
TERMINAL_NAM E Terminal name string
TERMINAL_PATH Folder from which the terminal is string
started
TERMINAL_DATA_PATH Folder in which terminal data are string
stored
TERMINAL_COMMONDATA_PATH Common path for all of the string
terminals installed on a computer
TERMINAL_CPU_NAM E CPU name string
TERMINAL_CPU_ARCHITECTURE CPU architecture string
TERMINAL_OS_VERS ION User's OS name string
For a better understanding of paths, stored in properties of TERMINAL_PATH, TERMINAL_DATA_PATH
and TERMINAL_COMMONDATA_PATH parameters, it is recommended to execute the script, which will
return these values for the current copy of the client terminal, installed on your computer
Example: Script returns information about the client terminal paths

//+------------------------------------------------------------------+
//| Check_TerminalPaths.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://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:

© 2000-2025, MetaQuotes Ltd.


747 Constants, Enumerations and Structures

© 2000-2025, MetaQuotes Ltd.


748 Constants, Enumerations and Structures

Running MQL5 Program Properties


To obtain information about the currently running mql5 program, constants from
ENUM _MQL _INFO_INT EGER and ENUM _MQL _INFO_S T R ING are used.

For function MQLInfoInteger


ENUM_MQL_INFO_INTEGER

Identifier Description Type

MQL_HANDLES_USED The current int


number of active
object handles.
These include
both dynamic
(created via new)
and non-dynamic
objects,
global/local
variables or class
members. The
more handles a
program uses,
the more
resources it
consumes.
MQL_M EMORY_LIMIT Maximum int
possible amount
of dynamic
memory for MQL5
program in M B
MQL_M EMORY_USED Memory used by int
MQL5 program in
MB
MQL_PROGRAM _TYPE Type of the MQL5 ENUM _PR OGRAM _T YPE
program
MQL_DLLS_ALLOWED The permission to bool
use DLL for the
given running
program

MQL_TRADE_ALLOWED The permission to bool


trade for the
given running
program

MQL_S IGNALS_ALLOWED The permission to bool


modify the
S ignals for the

© 2000-2025, MetaQuotes Ltd.


749 Constants, Enumerations and Structures

Identifier Description Type

given running
program

MQL_DEBUG Indication that bool


the program is
running in the
debugging mode
MQL_PROFILER Indication that bool
the program is
running in the
code profiling
mode
MQL_TES TER Indication that bool
the program is
running in the
tester
MQL_FORWARD Indication that bool
the program is
running in the
forward testing
process
MQL_OPTIMIZATION Indication that bool
the program is
running in the
optimization
mode
MQL_VISUAL_MODE Indication that bool
the program is
running in the
visual testing
mode
MQL_FRAM E_MODE Indication that bool
the Expert
Advisor is running
in gathering
optimization
result frames
mode
MQL_LICENSE_TYPE Type of license of ENUM _LICENSE_T YPE
the EX5 module.
The license refers
to the EX5
module, from
which a request is
made using

© 2000-2025, MetaQuotes Ltd.


750 Constants, Enumerations and Structures

Identifier Description Type

MQLInfoInteger(M
QL_LICENSE_TYP
E).

MQL_S TARTED_FROM _CONFIG R eturns true if a bool


script/EA is
launched from the
S tartUp section of
the configuration
file. This means
that the script/EA
had been
specified in the
configuration file
the terminal was
launched with.
For function MQLInfoS tring
ENUM_MQL_INFO_STRING

Identifier Description Type

MQL_PROGRAM _NAM E Name of the string


running mql5-
program
MQL5_PROGRAM _PATH Path for the string
given running
program

For information about the type of the running program, values of ENUM _PROGRAM _TYPE are used.
ENUM_PROGRAM_TY PE

Identifier Description

PROGRAM _S CRIPT S cript

PROGRAM _EXPERT Expert

PROGRAM _INDICATOR Indicator


PROGRAM _SERVICE S ervice

ENUM_LICENSE_TY PE

Identifier Description

LICENSE_FREE A free unlimited version

© 2000-2025, MetaQuotes Ltd.


751 Constants, Enumerations and Structures

Identifier Description

LICENSE_DEMO A trial version of a paid product from the Market. It


works only in the strategy tester
LICENSE_FULL A purchased licensed version allows at least 5
activations. The number of activations is specified by
seller. S eller may increase the allowed number of
activations
LICENSE_TIM E A version with a limited term license
Example:

ENUM_PROGRAM_TYPE mql_program=(ENUM_PROGRAM_TYPE)MQLInfoInteger(MQL_PROGRAM_TYPE);
switch(mql_program)
{
case PROGRAM_SCRIPT:
{
Print(__FILE__+" is script");
break;
}
case PROGRAM_EXPERT:
{
Print(__FILE__+" is Expert Advisor");
break;
}
case PROGRAM_INDICATOR:
{
Print(__FILE__+" is custom indicator");
break;
}
default:Print("MQL5 type value is ",mql_program);
//---
Print("MQLInfoInteger(MQL_MEMORY_LIMIT)=", MQLInfoInteger(MQL_MEMORY_LIMIT), " MB");
Print("MQLInfoInteger(MQL_MEMORY_USED)=", MQLInfoInteger(MQL_MEMORY_USED), " MB");
Print("MQLInfoInteger(MQL_HANDLES_USED)=", MQLInfoInteger(MQL_HANDLES_USED), " handles");

© 2000-2025, MetaQuotes Ltd.


752 Constants, Enumerations and Structures

Symbol Properties
To obtain the current market information there are several functions : S ymbolInfoInteger(),
S ymbolInfoDouble() and S ymbolInfoS tring(). The first parameter is the symbol name, the values of the
second function parameter can be one of the identifiers of ENUM _SYM BOL_INFO_INTEGER,
ENUM _SYM BOL _INFO_DOUBL E and ENUM _SYM BOL _INFO_S T R ING.

For function S ymbolInfoInteger()


ENUM_SY MBOL_INFO_INTEGER

Identifier Des Type


crip
tion

SYM BOL _SUBS CR IPTION_DEL AY S ym bool


bol
data
arri
ves
with
a
dela
y.
The
prop
erty
can
be
requ
este
d
only
for
sym
bols
sele
cted
in
Mar
k et
W at
ch
(SY
M BO
L_S
EL E
CT
=
true
).

© 2000-2025, MetaQuotes Ltd.


753 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

The
ERR
_M A
RKE
T_N
OT_
SEL
ECT
ED
(430
2)
erro
r is
gen
erat
ed
for
othe
r
sym
bols
SYM BOL _SECTOR The ENUM _SYM BOL _SECTOR
sect
or
of
the
eco
nom
y to
whic
h
the
asse
t
belo
ngs
SYM BOL _INDUS T RY The ENUM _SYM BOL _INDUS T RY
indu
stry
or
the
eco
nom
y
bran

© 2000-2025, MetaQuotes Ltd.


754 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

ch
to
whic
h
the
sym
bol
belo
ngs
SYM BOL _CUS TOM It is bool
a
cust
om
sym
bol –
the
sym
bol
has
bee
n
crea
ted
synt
heti
cally
bas
ed
on
othe
r
sym
bols
fro
m
the
Mar
k et
W at
ch
and
/or
exte
rnal
data

© 2000-2025, MetaQuotes Ltd.


755 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

sour
ces
SYM BOL _BACKGR OUND_COLOR The color
colo
r of
the
bac
k gro
und
use
d
for
the
sym
bol
in
Mar
k et
W at
ch
SYM BOL _CHAR T _MODE The ENUM _SYM BOL _CHAR T _MODE
pric
e
type
use
d
for
gen
erat
ing
sym
bols
bars
,
i.e.
Bid
or
Last
SYM BOL _EXIS T S ym bool
bol
with
this
nam
e

© 2000-2025, MetaQuotes Ltd.


756 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

exis
ts
SYM BOL _SEL ECT S ym bool
bol
is
sele
cted
in
Mar
k et
W at
ch
SYM BOL _VIS IBL E S ym bool
bol
is
visi
ble
in
Mar
k et
W at
ch.

S om
e
sym
bols
(mo
stly,
thes
e
are
cros
s
rate
s
requ
ired
for
calc
ulati
on
of
mar
gin

© 2000-2025, MetaQuotes Ltd.


757 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

requ
ire
men
ts
or
prof
its
in
dep
osit
curr
ency
)
are
sele
cted
auto
mat
icall
y,
but
may
not
be
visi
ble
in
Mar
k et
W at
ch.
To
be
disp
laye
d
such
sym
bols
hav
e to
be
expl
icitl
y
sele

© 2000-2025, MetaQuotes Ltd.


758 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

cted
.
SYM BOL _SESS ION_DEAL S Num long
ber
of
deal
s in
the
curr
ent
sess
ion
SYM BOL _SESS ION_BUY_ORDERS Num long
ber
of
Buy
orde
rs
at
the
mo
men
t
SYM BOL _SESS ION_SELL _ORDERS Num long
ber
of
S ell
orde
rs
at
the
mo
men
t
SYM BOL _VOL UM E Volu long
me
of
the
last
deal
SYM BOL _VOL UM EH IGH Max long
imal
day

© 2000-2025, MetaQuotes Ltd.


759 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

volu
me
SYM BOL _VOL UM ELOW Mini long
mal
day
volu
me
SYM BOL _TIM E Tim datetime
e of
the
last
quot
e
SYM BOL _TIM E_M S C Tim long
e of
the
last
quot
e in
milli
seco
nds
sinc
e
197
0.01
.01
SYM BOL _DIGIT S Digi int
ts
afte
r a
deci
mal
poin
t
SYM BOL _S PREAD_FLOAT Indi bool
cati
on
of a
floa
ting
spre
ad

© 2000-2025, MetaQuotes Ltd.


760 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

SYM BOL _S PREAD S pre int


ad
valu
e in
poin
ts
SYM BOL _TICKS_BOOKDEPT H Max int
imal
num
ber
of
requ
ests
sho
wn
in
Dep
th
of
Mar
k et.
For
sym
bols
that
hav
e no
que
ue
of
requ
ests
,
the
valu
e is
equ
al to
zero
.
SYM BOL _T RADE_CALC_MODE Con ENUM _SYM BOL _CALC_MODE
trac
t
pric
e

© 2000-2025, MetaQuotes Ltd.


761 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

calc
ulati
on
mod
e
SYM BOL _T RADE_MODE Ord ENUM _SYM BOL _T RADE_MODE
er
exe
cuti
on
type
SYM BOL _S T AR T _TIM E Dat datetime
e of
the
sym
bol
trad
e
begi
nnin
g
(usu
ally
use
d
for
futu
res)
SYM BOL _EXPIRATION_TIM E Dat datetime
e of
the
sym
bol
trad
e
end
(usu
ally
use
d
for
futu
res)

© 2000-2025, MetaQuotes Ltd.


762 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

SYM BOL _T RADE_S TOPS_L EVEL Mini int


mal
inde
ntio
n in
poin
ts
fro
m
the
curr
ent
clos
e
pric
e to
plac
e
S top
orde
rs
SYM BOL _T RADE_FREEZE_L EVEL Dist int
anc
e to
free
ze
trad
e
oper
atio
ns
in
poin
ts
SYM BOL _T RADE_EXEMODE Deal ENUM _SYM BOL _T RADE_EXECUTION
exe
cuti
on
mod
e
SYM BOL _SWAP_MODE S wa ENUM _SYM BOL _SWAP_MODE
p
calc
ulati

© 2000-2025, MetaQuotes Ltd.


763 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

on
mod
el
SYM BOL _SWAP_R OLLOVER3DAYS The ENUM _DAY_OF_WEEK
day
of
wee
k to
char
ge
3-
day
swa
p
rollo
ver
SYM BOL _M ARGIN_HEDGED_USE_L EG Calc bool
ulati
ng
hed
ging
mar
gin
usin
g
the
larg
er
leg
(Buy
or
S ell)

SYM BOL _EXPIRATION_MODE Flag int


s of
allo
wed
orde
r
expi
rati
on
mod
es

© 2000-2025, MetaQuotes Ltd.


764 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

SYM BOL _FILLING_MODE Flag int


s of
allo
wed
orde
r
fillin
g
mod
es
SYM BOL _ORDER_MODE Flag int
s of
allo
wed
orde
r
type
s
SYM BOL _ORDER_GTC_MODE Expi ENUM _SYM BOL _ORDER_GTC_MODE
rati
on
of
S top
Loss
and
Tak
e
Prof
it
orde
rs,
if
SYM
BOL
_EX
PIR
ATI
ON_
MO
DE=
SYM
BOL
_EX
PIR
ATI

© 2000-2025, MetaQuotes Ltd.


765 Constants, Enumerations and Structures

Identifier Des Type


crip
tion

ON_
GTC
(Go
od
till
canc
eled
)
SYM BOL _OPTION_MODE Opti ENUM _SYM BOL _OPTION_MODE
on
type
SYM BOL _OPTION_R IGH T Opti ENUM _SYM BOL _OPTION_R IGH T
on
righ
t
(Call
/Put
)
For function S ymbolInfoDouble()
ENUM_SY MBOL_INFO_DOUBLE

Identifier Descrip Type


tion

SYM BOL _BID Bid - double


best sell
offer
SYM BOL _BIDH IGH Maxima double
l Bid of
the day
SYM BOL _BIDLOW Minimal double
Bid of
the day
SYM BOL _ASK As k - double
best
buy
offer
SYM BOL _ASKH IGH Maxima double
l As k of
the day

© 2000-2025, MetaQuotes Ltd.


766 Constants, Enumerations and Structures

Identifier Descrip Type


tion

SYM BOL _ASKLOW Minimal double


As k of
the day
SYM BOL _L AS T Price of double
the last
deal
SYM BOL _L AS T H IGH Maxima double
l Last of
the day
SYM BOL _L AS TLOW Minimal double
Last of
the day
SYM BOL _VOL UM E_REAL Volume double
of the
last
deal
SYM BOL _VOL UM EH IGH_REAL Maximu double
m
Volume
of the
day
SYM BOL _VOL UM ELOW_REAL Minimu double
m
Volume
of the
day
SYM BOL _OPTION_S T R IKE The double
strike
price of
an
option.
The
price at
which
an
option
buyer
can buy
(in a
Call
option)
or sell
(in a
Put

© 2000-2025, MetaQuotes Ltd.


767 Constants, Enumerations and Structures

Identifier Descrip Type


tion

option)
the
underlyi
ng
asset,
and the
option
seller is
obliged
to sell
or buy
the
appropr
iate
amount
of the
underlyi
ng
asset.
SYM BOL _POINT S ymbol double
point
value
SYM BOL _T RADE_TICK_VAL UE Value of double
SYM BOL
_T RADE
_TICK_V
AL UE_P
R OFIT

SYM BOL _T RADE_TICK_VAL UE_PR OFIT Calculat double


ed tick
price
for a
profitab
le
position
SYM BOL _T RADE_TICK_VAL UE_LOSS Calculat double
ed tick
price
for a
losing
position
SYM BOL _T RADE_TICK_S IZE Minimal double
price
change

© 2000-2025, MetaQuotes Ltd.


768 Constants, Enumerations and Structures

Identifier Descrip Type


tion

SYM BOL _T RADE_CONT RACT _S IZE Trade double


contract
size
SYM BOL _T RADE_ACCRUED_INT ERES T Accrued double
interest

accumul
ated
coupon
interest
, i.e.
part of
the
coupon
interest
calculat
ed in
proporti
on to
the
number
of days
since
the
coupon
bond
issuanc
e or the
last
coupon
interest
paymen
t
SYM BOL _T RADE_FACE_VAL UE Face double
value –
initial
bond
value
set by
the
issuer
SYM BOL _T RADE_LIQUIDIT Y_RAT E Liquidit double
y Rate
is the
share of
the

© 2000-2025, MetaQuotes Ltd.


769 Constants, Enumerations and Structures

Identifier Descrip Type


tion

asset
that can
be used
for the
margin.
SYM BOL _VOL UM E_MIN Minimal double
volume
for a
deal
SYM BOL _VOL UM E_M AX Maxima double
l
volume
for a
deal
SYM BOL _VOL UM E_S T EP Minimal double
volume
change
step for
deal
executi
on
SYM BOL _VOL UM E_LIMIT Maximu double
m
allowed
aggrega
te
volume
of an
open
position
and
pending
orders
in one
directio
n (buy
or sell)
for the
symbol.
For
exampl
e, with
the
limitati
on of 5
lots,

© 2000-2025, MetaQuotes Ltd.


770 Constants, Enumerations and Structures

Identifier Descrip Type


tion

you can
have an
open
buy
position
with the
volume
of 5 lots
and
place a
pending
order
S ell
Limit
with the
volume
of 5
lots.
But in
this
case
you
cannot
place a
Buy
Limit
pending
order
(since
the
total
volume
in one
directio
n will
exceed
the
limitati
on) or
place
S ell
Limit
with the
volume
more
than 5
lots.

© 2000-2025, MetaQuotes Ltd.


771 Constants, Enumerations and Structures

Identifier Descrip Type


tion

SYM BOL _SWAP_LONG Long double


swap
value
SYM BOL _SWAP_SH OR T S hort double
swap
value
SYM BOL _SWAP_SUNDAY S wap double
calculati
on ratio
(SYM BO
L_SWAP
_LONG
or
SYM BOL
_SWAP_
SH OR T)
for
overnig
ht
position
s rolled
over
from
SUNDAY
to the
next
day.
There
followin
g values
are
support
ed:
· 0

n
o
s
w
a
p
i
s
c
h
a
r

© 2000-2025, MetaQuotes Ltd.


772 Constants, Enumerations and Structures

Identifier Descrip Type


tion

g
e
d
· 1

s
i
n
g
l
e
s
w
a
p
· 3

t
r
i
p
l
e
s
w
a
p
SYM BOL _SWAP_MONDAY S wap double
calculati
on ratio
(SYM BO
L_SWAP
_LONG
or
SYM BOL
_SWAP_
SH OR T)
for
overnig
ht
position
s rolled
over
from
Monday
to
Tuesday

© 2000-2025, MetaQuotes Ltd.


773 Constants, Enumerations and Structures

Identifier Descrip Type


tion

SYM BOL _SWAP_T UESDAY S wap double


calculati
on ratio
(SYM BO
L_SWAP
_LONG
or
SYM BOL
_SWAP_
SH OR T)
for
overnig
ht
position
s rolled
over
from
Tuesday
to
W ednes
day
SYM BOL _SWAP_WEDNESDAY S wap double
calculati
on ratio
(SYM BO
L_SWAP
_LONG
or
SYM BOL
_SWAP_
SH OR T)
for
overnig
ht
position
s rolled
over
from
W ednes
day to
Thursda
y
SYM BOL _SWAP_T HURSDAY S wap double
calculati
on ratio
(SYM BO
L_SWAP

© 2000-2025, MetaQuotes Ltd.


774 Constants, Enumerations and Structures

Identifier Descrip Type


tion

_LONG
or
SYM BOL
_SWAP_
SH OR T)
for
overnig
ht
position
s rolled
over
from
Thursda
y to
Friday

SYM BOL _SWAP_FR IDAY S wap double


calculati
on ratio
(SYM BO
L_SWAP
_LONG
or
SYM BOL
_SWAP_
SH OR T)
for
overnig
ht
position
s rolled
over
from
Friday
to
S aturda
y
SYM BOL _SWAP_SAT URDAY S wap double
calculati
on ratio
(SYM BO
L_SWAP
_LONG
or
SYM BOL
_SWAP_
SH OR T)
for

© 2000-2025, MetaQuotes Ltd.


775 Constants, Enumerations and Structures

Identifier Descrip Type


tion

overnig
ht
position
s rolled
over
from
S aturda
y to
S unday

SYM BOL _M ARGIN_INITIAL Initial double


margin
means
the
amount
in the
margin
currenc
y
require
d for
opening
a
position
with the
volume
of one
lot. It is
used for
checkin
g a
client's
assets
when he
or she
enters
the
market.

The
S ymbolI
nfoMarg
inRate()
function
provide
s data
on the
amount
of

© 2000-2025, MetaQuotes Ltd.


776 Constants, Enumerations and Structures

Identifier Descrip Type


tion

charged
margin
dependi
ng on
the
order
type
and
directio
n.
SYM BOL _M ARGIN_M AINT ENANCE The double
mainten
ance
margin.
If it is
set, it
sets the
margin
amount
in the
margin
currenc
y of the
symbol,
charged
from
one lot.
It is
used for
checkin
g a
client's
assets
when
his /her
account
state
changes
. If the
mainten
ance
margin
is equal
to 0,
the
initial
margin
is used.

© 2000-2025, MetaQuotes Ltd.


777 Constants, Enumerations and Structures

Identifier Descrip Type


tion

The
S ymbolI
nfoMarg
inRate()
function
provide
s data
on the
amount
of
charged
margin
dependi
ng on
the
order
type
and
directio
n.
SYM BOL _SESS ION_VOL UM E S ummar double
y
volume
of
current
session
deals
SYM BOL _SESS ION_T URNOVER S ummar double
y
turnove
r of the
current
session
SYM BOL _SESS ION_INT ERES T S ummar double
y open
interest
SYM BOL _SESS ION_BUY_ORDERS_VOL UM E Current double
volume
of Buy
orders
SYM BOL _SESS ION_SELL _ORDERS_VOL UM E Current double
volume
of S ell
orders

© 2000-2025, MetaQuotes Ltd.


778 Constants, Enumerations and Structures

Identifier Descrip Type


tion

SYM BOL _SESS ION_OPEN Open double


price of
the
current
session
SYM BOL _SESS ION_CLOSE Close double
price of
the
current
session
SYM BOL _SESS ION_AW Average double
weighte
d price
of the
current
session
SYM BOL _SESS ION_PR ICE_SETTL EM ENT S ettlem double
ent
price of
the
current
session
SYM BOL _SESS ION_PR ICE_LIMIT _MIN Minimal double
price of
the
current
session
SYM BOL _SESS ION_PR ICE_LIMIT _M AX Maxima double
l price
of the
current
session
SYM BOL _M ARGIN_HEDGED Contrac double
t size or
margin
value
per one
lot of
hedged
position
s
(opposit
ely
directed
position

© 2000-2025, MetaQuotes Ltd.


779 Constants, Enumerations and Structures

Identifier Descrip Type


tion

s of one
symbol)
. Two
margin
calculati
on
method
s are
possible
for
hedged
position
s. The
calculati
on
method
is
defined
by the
broker.

Basic
calculati
on:
· If the
initial
margi
n
(SYM
BOL _
M ARG
IN_INI
TIAL)
is
specif
ied
for a
symb
ol,
the
hedge
d
margi
n is
specif
ied as
an
absol

© 2000-2025, MetaQuotes Ltd.


780 Constants, Enumerations and Structures

Identifier Descrip Type


tion

ute
value
(in
mone
tary
terms
).
· If the
initial
margi
n is
not
specif
ied
(equa
l to
0),
SYM B
OL_M
ARGI
N_HE
DGED
is
equal
to the
size
of the
contr
act,
that
will
be
used
to
calcul
ate
the
margi
n by
the
appro
priate
formu
la in
accor
dance
with
the

© 2000-2025, MetaQuotes Ltd.


781 Constants, Enumerations and Structures

Identifier Descrip Type


tion

type
of the
finan
cial
instru
ment
(SYM
BOL _
TRAD
E_CA
LC_M
ODE).

Calculat
ion for
the
largest
position
:
· The
SYM B
OL_M
ARGI
N_HE
DGED
value
is not
taken
into
accou
nt.
· The
volum
e of
all
short
and
all
long
positi
ons
of a
symb
ol is
calcul
ated.
· For
each

© 2000-2025, MetaQuotes Ltd.


782 Constants, Enumerations and Structures

Identifier Descrip Type


tion

direct
ion, a
weigh
ted
avera
ge
open
price
and a
weigh
ted
avera
ge
rate
of
conve
rsion
to the
depos
it
curre
ncy is
calcul
ated.
· Next,
using
the
appro
priate
formu
la
chose
n in
accor
dance
with
the
symb
ol
type
(SYM
BOL _
TRAD
E_CA
LC_M
ODE)
the
margi

© 2000-2025, MetaQuotes Ltd.


783 Constants, Enumerations and Structures

Identifier Descrip Type


tion

n is
calcul
ated
for
the
short
and
the
long
part.
· The
larges
t one
of the
value
s is
used
as
the
margi
n.
SYM BOL _PR ICE_CHANGE Change double
of the
current
price
relative
to the
end of
the
previou
s
trading
day in %
SYM BOL _PR ICE_VOL ATILIT Y Price double
volatilit
y in %
SYM BOL _PR ICE_T HEORETICAL Theoret double
ical
option
price
SYM BOL _PR ICE_DELT A Option/ double
warrant
delta
shows
the
value

© 2000-2025, MetaQuotes Ltd.


784 Constants, Enumerations and Structures

Identifier Descrip Type


tion

the
option
price
changes
by,
when
the
underlyi
ng
asset
price
changes
by 1
SYM BOL _PR ICE_T HET A Option/ double
warrant
theta
shows
the
number
of
points
the
option
price is
to lose
every
day due
to a
tempor
ary
breakup
, i.e.
when
the
expirati
on date
approac
hes
SYM BOL _PR ICE_GAMM A Option/ double
warrant
gamma
shows
the
change
rate of
delta –
how

© 2000-2025, MetaQuotes Ltd.


785 Constants, Enumerations and Structures

Identifier Descrip Type


tion

quick ly
or
slowly
the
option
premiu
m
changes
SYM BOL _PR ICE_VEGA Option/ double
warrant
vega
shows
the
number
of
points
the
option
price
changes
by when
the
volatilit
y
changes
by 1%
SYM BOL _PR ICE_RH O Option/ double
warrant
rho
reflects
the
sensitiv
ity of
the
theoreti
cal
option
price to
the
interest
rate
changin
g by 1%
SYM BOL _PR ICE_OM EGA Option/ double
warrant
omega.

© 2000-2025, MetaQuotes Ltd.


786 Constants, Enumerations and Structures

Identifier Descrip Type


tion

Option
elasticit
y shows
a
relative
percent
age
change
of the
option
price by
the
percent
age
change
of the
underlyi
ng
asset
price
SYM BOL _PR ICE_SENS ITIVIT Y Option/ double
warrant
sensitiv
ity
shows
by how
many
points
the
price of
the
option's
underlyi
ng
asset
should
change
so that
the
price of
the
option
changes
by one
point
For function S ymbolInfoS tring()

© 2000-2025, MetaQuotes Ltd.


787 Constants, Enumerations and Structures

ENUM_SY MBOL_INFO_STRING

Identifier Descripti Type


on

SYM BOL _BAS IS The string


underlying
asset of a
derivative
SYM BOL _CAT EGORY The name string
of the
sector or
category
to which
the
financial
symbol
belongs
SYM BOL _COUNT RY The string
country to
which the
financial
symbol
belongs
SYM BOL _SECTOR_NAM E The string
sector of
the
economy
to which
the
financial
symbol
belongs
SYM BOL _INDUS T RY_NAM E The string
industry
branch or
the
industry
to which
the
financial
symbol
belongs
SYM BOL _CURRENCY_BASE Basic string
currency
of a
symbol

© 2000-2025, MetaQuotes Ltd.


788 Constants, Enumerations and Structures

Identifier Descripti Type


on

SYM BOL _CURRENCY_PR OFIT Profit string


currency
SYM BOL _CURRENCY_M ARGIN Margin string
currency
SYM BOL _BANK Feeder of string
the
current
quote

SYM BOL _DES CR IPTION S ymbol string


descriptio
n
SYM BOL _EXCHANGE The name string
of the
exchange
in which
the
financial
symbol is
traded
SYM BOL _FOR M UL A The string
formula
used for
the
custom
symbol
pricing. If
the name
of a
financial
symbol
used in
the
formula
starts
with a
digit or
contains a
special
character
(">" " , " ." ,
" -" , "&" ,
"#" and so
on)
quotation
marks

© 2000-2025, MetaQuotes Ltd.


789 Constants, Enumerations and Structures

Identifier Descripti Type


on

should be
used
around
this
symbol
name.
· S
y
n
t
h
e
t
i
c
s
y
m
b
o
l
:
"
@
E
S
U
1
9
"
/
E
U
R
C
A
D
· C
a
l
e
n
d
a
r
s
p
r

© 2000-2025, MetaQuotes Ltd.


790 Constants, Enumerations and Structures

Identifier Descripti Type


on

e
a
d
:
"
S
i
-
9
.
1
3
"
-
"
S
i
-
6
.
1
3
"
· E
u
r
o
i
n
d
e
x
:
3
4
.
3
8
8
0
5
7
2
6
*
p
o
w

© 2000-2025, MetaQuotes Ltd.


791 Constants, Enumerations and Structures

Identifier Descripti Type


on

(
E
U
R
U
S
D
,
0
.
3
1
5
5
)
*
p
o
w
(
E
U
R
G
B
P
,
0
.
3
0
5
6
)
*
p
o
w
(
E
U
R
J
P
Y
,
0
.

© 2000-2025, MetaQuotes Ltd.


792 Constants, Enumerations and Structures

Identifier Descripti Type


on

1
8
9
1
)
*
p
o
w
(
E
U
R
C
H
F
,
0
.
1
1
1
3
)
*
p
o
w
(
E
U
R
S
E
K
,
0
.
0
7
8
5
)
SYM BOL _IS IN The name string
of a
symbol in
the IS IN

© 2000-2025, MetaQuotes Ltd.


793 Constants, Enumerations and Structures

Identifier Descripti Type


on

system
(Internati
onal
S ecurities
Identificat
ion
Number).
The
Internatio
nal
S ecurities
Identificat
ion
Number is
a 12-digit
alphanum
eric code
that
uniquely
identifies
a
security.
The
presence
of this
symbol
property
is
determine
d on the
side of a
trade
server.
SYM BOL _PAGE The string
address of
the web
page
containing
symbol
informati
on. This
address
will be
displayed
as a link
when
viewing
symbol

© 2000-2025, MetaQuotes Ltd.


794 Constants, Enumerations and Structures

Identifier Descripti Type


on

properties
in the
terminal
SYM BOL _PAT H Path in string
the
symbol
tree

A symbol price chart can be based on Bid or Last prices. The price selected for symbol charts also
affects the generation and display of bars in the terminal. Possible values of the
SYM BOL _CHAR T _MODE property are described in ENUM _SYM BOL _CHAR T _MODE

ENUM_SY MBOL_CHART_MODE

Identifier Description

SYM BOL _CHAR T _MODE_BID Bars are based on Bid prices


SYM BOL _CHAR T _MODE_L AS T Bars are based on Last prices

For each symbol several expiration modes of pending orders can be specified. A flag is matched to
each mode. Flags can be combined using the operation of logical OR (|), for example,
SYM BOL _EXPIRATION_GTC|SYM BOL _EXPIRATION_S PECIFIED. In order to check whether a certain mode
is allowed for the symbol, the result of the logical AND (&) should be compared to the mode flag.
If flag SYM BOL_EXPIRATION_S PECIFIED is specified for a symbol, then while sending a pending order,
you may specify the moment this pending order is valid till.
Identifier Value Description

SYM BOL _EXPIRATION_GTC 1 The order is valid during the


unlimited time period, until it is
explicitly canceled
SYM BOL _EXPIRATION_DAY 2 The order is valid till the end of
the day
SYM BOL _EXPIRATION_S PECIFIED 4 The expiration time is specified in
the order
SYM BOL _EXPIRATION_S PECIFIED_DAY 8 The expiration date is specified in
the order
Example:

//+------------------------------------------------------------------+
//| Checks if the specified expiration mode is allowed |

© 2000-2025, MetaQuotes Ltd.


795 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
bool IsExpirationTypeAllowed(string symbol,int exp_type)
{
//--- Obtain the value of the property that describes allowed expiration modes
int expiration=(int)SymbolInfoInteger(symbol,SYMBOL_EXPIRATION_MODE);
//--- Return true, if mode exp_type is allowed
return((expiration&exp_type)==exp_type);
}

If the SYM BOL_EXPIRATION_MODE property is set to SYM BOL_EXPIRATION_GTC (good till canceled),
the expiration of pending orders, as well as of S top Loss /Take Profit orders should be additionally set
using the ENUM _SYM BOL_ORDER_GTC_MODE enumeration.
ENUM_SY MBOL_ORDER_GTC_MODE

Identifier Description

SYM BOL _ORDERS_GTC Pending orders and S top Loss /Take Profit levels
are valid for an unlimited period until their
explicit cancellation
SYM BOL _ORDERS_DAIL Y Orders are valid during one trading day. At the
end of the day, all S top Loss and Take Profit
levels, as well as pending orders are deleted.
SYM BOL _ORDERS_DAIL Y_EXCL UDING_S TOPS W hen a trade day changes, only pending orders
are deleted, while S top Loss and Take Profit levels
are preserved.

W hen sending an order, we can specify the filling policy of a volume set in the order. The possible
volume-based order execution options for each symbol are specified in the table. It is possible to set
several modes for each instrument via a combination of flags. The combination of flags is expressed
by the logical OR (|) operation, for example SYM BOL_FILLING_FOK|SYM BOL_FILLING_IOC. To check if
a specific mode is allowed for an instrument, compare the logical AND (&) result with the mode flag -
example.
Fill policy ID Value D
e
s
c
r
i
p
ti
o
n

Fill or Kill SYM BOL _FILLING_FOK 1 A


n

© 2000-2025, MetaQuotes Ltd.


796 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

o
r
d
e
r
c
a
n
b
e
e
x
e
c
u
t
e
d
i
n
t
h
e
s
p
e
c
if
i
e
d
v
o
l
u
m
e
o
n

© 2000-2025, MetaQuotes Ltd.


797 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

ly
.

If
t
h
e
n
e
c
e
s
s
a
r
y
a
m
o
u
n
t
o
f
a
fi
n
a
n
c
i
a
l
i
n
s
t
r
u
m

© 2000-2025, MetaQuotes Ltd.


798 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

e
n
t
i
s
c
u
r
r
e
n
tl
y
u
n
a
v
a
il
a
b
l
e
i
n
t
h
e
m
a
r
k
e
t
,
t
h
e
o
r

© 2000-2025, MetaQuotes Ltd.


799 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

d
e
r
w
il
l
n
o
t
b
e
e
x
e
c
u
t
e
d
.
T
h
e
d
e
s
ir
e
d
v
o
l
u
m
e
c
a
n
b
e

© 2000-2025, MetaQuotes Ltd.


800 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

m
a
d
e
u
p
o
f
s
e
v
e
r
a
l
a
v
a
il
a
b
l
e
o
f
f
e
r
s
.

W
h
e
n
s
e
n
d
i

© 2000-2025, MetaQuotes Ltd.


801 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

n
g
a
n
o
r
d
e
r
,
t
h
e
O
R
D
E
R
_
F
I
L
L
I
N
G
_
F
O
K
fi
ll
i
n
g
t
y
p
e
s

© 2000-2025, MetaQuotes Ltd.


802 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

h
o
u
l
d
b
e
s
p
e
c
if
i
e
d
f
o
r
t
h
i
s
p
o
li
c
y
.

T
h
e
p
o
s
s
i
b
i
l

© 2000-2025, MetaQuotes Ltd.


803 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

i
t
y
o
f
u
s
i
n
g
F
O
K
o
r
d
e
r
s
i
s
d
e
t
e
r
m
i
n
e
d
a
t
t
h
e
t
r
a
d

© 2000-2025, MetaQuotes Ltd.


804 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

e
s
e
r
v
e
r
.
Immediate or Cancel SYM BOL _FILLING_IOC 2 A
t
r
a
d
e
r
a
g
r
e
e
s
t
o
e
x
e
c
u
t
e
a
d
e
a
l
w
it
h
t
h

© 2000-2025, MetaQuotes Ltd.


805 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

e
v
o
l
u
m
e
m
a
x
i
m
a
ll
y
a
v
a
il
a
b
l
e
i
n
t
h
e
m
a
r
k
e
t
w
it
h
i
n
t

© 2000-2025, MetaQuotes Ltd.


806 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

h
a
t
i
n
d
i
c
a
t
e
d
i
n
t
h
e
o
r
d
e
r
.
If
t
h
e
r
e
q
u
e
s
t
c
a
n
n
o
t

© 2000-2025, MetaQuotes Ltd.


807 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

b
e
fi
ll
e
d
c
o
m
p
l
e
t
e
ly
,
a
n
o
r
d
e
r
w
it
h
t
h
e
a
v
a
il
a
b
l
e
v
o
l

© 2000-2025, MetaQuotes Ltd.


808 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

u
m
e
w
il
l
b
e
e
x
e
c
u
t
e
d
,
a
n
d
t
h
e
r
e
m
a
i
n
i
n
g
v
o
l
u
m
e
w
il

© 2000-2025, MetaQuotes Ltd.


809 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

l
b
e
c
a
n
c
e
l
e
d
.

W
h
e
n
s
e
n
d
i
n
g
a
n
o
r
d
e
r
,
t
h
e
O
R
D
E
R

© 2000-2025, MetaQuotes Ltd.


810 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

_
F
I
L
L
I
N
G
_
I
O
C
fi
ll
i
n
g
t
y
p
e
s
h
o
u
l
d
b
e
s
p
e
c
if
i
e
d
f
o
r

© 2000-2025, MetaQuotes Ltd.


811 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

t
h
i
s
p
o
li
c
y
.

T
h
e
p
o
s
s
i
b
il
it
y
o
f
u
s
i
n
g
I
O
C
o
r
d
e
r
s
i

© 2000-2025, MetaQuotes Ltd.


812 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

s
d
e
t
e
r
m
i
n
e
d
a
t
t
h
e
t
r
a
d
e
s
e
r
v
e
r
.
Passive SYM BOL _FILLING_BOC 4 T
h
e
B
O
C
(
B
o
o
k
-

© 2000-2025, MetaQuotes Ltd.


813 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

o
r
-
C
a
n
c
e
l
)
p
o
l
i
c
y
a
s
s
u
m
e
s
t
h
a
t
a
n
o
r
d
e
r
c
a
n
o
n
l

© 2000-2025, MetaQuotes Ltd.


814 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

y
b
e
p
l
a
c
e
d
i
n
t
h
e
D
e
p
t
h
o
f
M
a
r
k
e
t
a
n
d
c
a
n
n
o
t
b
e
i
m

© 2000-2025, MetaQuotes Ltd.


815 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

m
e
d
i
a
t
e
l
y
e
x
e
c
u
t
e
d
.
I
f
t
h
e
o
r
d
e
r
c
a
n
b
e
e
x
e
c
u
t
e

© 2000-2025, MetaQuotes Ltd.


816 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

d
i
m
m
e
d
i
a
t
e
l
y
w
h
e
n
p
l
a
c
e
d
,
t
h
e
n
i
t
i
s
c
a
n
c
e
l
e
d
.

© 2000-2025, MetaQuotes Ltd.


817 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

I
n
f
a
c
t
,
t
h
i
s
e
x
e
c
u
t
i
o
n
p
o
l
i
c
y
c
a
n
o
n
l
y
b
e
s
p
e
c

© 2000-2025, MetaQuotes Ltd.


818 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

i
f
i
e
d
w
h
e
n
t
h
e
p
r
i
c
e
o
f
t
h
e
p
l
a
c
e
d
o
r
d
e
r
i
s
t
o
b
e
w

© 2000-2025, MetaQuotes Ltd.


819 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

o
r
s
e
t
h
a
n
t
h
e
c
u
r
r
e
n
t
m
a
r
k
e
t
.
B
o
C
o
r
d
e
r
s
a
r
e
u
s
e

© 2000-2025, MetaQuotes Ltd.


820 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

d
t
o
i
m
p
l
e
m
e
n
t
p
a
s
s
i
v
e
t
r
a
d
i
n
g
,
s
o
t
h
a
t
t
h
e
o
r
d
e

© 2000-2025, MetaQuotes Ltd.


821 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

r
i
s
n
o
t
e
x
e
c
u
t
e
d
i
m
m
e
d
i
a
t
e
l
y
w
h
e
n
p
l
a
c
e
d
a
n
d
d
o

© 2000-2025, MetaQuotes Ltd.


822 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

e
s
n
o
t
a
f
f
e
c
t
c
u
r
r
e
n
t
l
i
q
u
i
d
i
t
y
.

O
n
l
y
l
i
m
i
t
a
n

© 2000-2025, MetaQuotes Ltd.


823 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

d
s
t
o
p
l
i
m
i
t
o
r
d
e
r
s
a
r
e
s
u
p
p
o
r
t
e
d
,
i
.
e
.
t
h
e
S
Y
M
B

© 2000-2025, MetaQuotes Ltd.


824 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

O
L
_
O
R
D
E
R
_
M
O
D
E
f
l
a
g
s
h
o
u
l
d
c
o
n
t
a
i
n
t
h
e
S
Y
M
B
O
L
_

© 2000-2025, MetaQuotes Ltd.


825 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

O
R
D
E
R
_
L
I
M
I
T
a
n
d
/
o
r
S
Y
M
B
O
L
_
O
R
D
E
R
_
S
T
O
P
_
L
I
M
I
T

© 2000-2025, MetaQuotes Ltd.


826 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

v
a
l
u
e
s
.
R eturn No identifier I
n
c
a
s
e
o
f
p
a
r
ti
a
l
fi
ll
i
n
g
,
a
m
a
r
k
e
t
o
r
li
m
it
o

© 2000-2025, MetaQuotes Ltd.


827 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

r
d
e
r
w
it
h
r
e
m
a
i
n
i
n
g
v
o
l
u
m
e
i
s
n
o
t
c
a
n
c
e
l
e
d
b
u
t
p
r

© 2000-2025, MetaQuotes Ltd.


828 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

o
c
e
s
s
e
d
f
u
r
t
h
e
r
.

W
h
e
n
s
e
n
d
i
n
g
a
n
o
r
d
e
r
,
t
h
e
O
R

© 2000-2025, MetaQuotes Ltd.


829 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

D
E
R
_
F
I
L
L
I
N
G
_
R
E
T
U
R
N
fi
ll
i
n
g
t
y
p
e
s
h
o
u
l
d
b
e
s
p
e
c
if

© 2000-2025, MetaQuotes Ltd.


830 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

i
e
d
f
o
r
t
h
i
s
p
o
li
c
y
.

R
e
t
u
r
n
o
r
d
e
r
s
a
r
e
n
o
t
a
l
l
o
w

© 2000-2025, MetaQuotes Ltd.


831 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

e
d
i
n
t
h
e
M
a
r
k
e
t
E
x
e
c
u
t
i
o
n
m
o
d
e
(
m
a
r
k
e
t
e
x
e
c
u
t
i

© 2000-2025, MetaQuotes Ltd.


832 Constants, Enumerations and Structures

Fill policy ID Value D


e
s
c
r
i
p
ti
o
n

o
n

S
Y
M
B
O
L
_
T
R
A
D
E
_
E
X
E
C
U
T
I
O
N
_
M
A
R
K
E
T
)
.
W hen sending a trade request using the OrderS end() function, the necessary volume execution policy
can be set in the type_filling field, namely in the special M qlTradeRequest structure. The values from
the ENUM _ORDER_TYPE_FILLING enumeration are available. If no filling type is specified,
ORDER_FILLING_RETURN is automatically set in the trade request. The ORDER_FILLING_RETURN filling

© 2000-2025, MetaQuotes Ltd.


833 Constants, Enumerations and Structures

type is enabled in any execution mode except for " Mark et


execution" (SYM BOL_TRADE_EXECUTION_M ARKET).
W hile sending a trade request for execution at the current time (time in force), we should keep in
mind that financial markets provide no guarantee that the entire requested volume is available for a
certain financial instrument at the desired price. Therefore, trading operations in real time are
regulated using the price and volume execution modes. The modes, or execution policies, define the
rules for cases when the price has changed or the requested volume cannot be completely fulfilled at
the moment.

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

Execution mode Executi SYM BOL _T RADE_EXECUTION_REQUES T


ng a
(Request Execution) market
order
at the
price
previou
sly
receive
d from
the
broker.

Prices
for a
certain
market
order
are
request
ed
from
the
broker
before
the
order
is sent.
Upon
receivi
ng the
prices,
order
executi
on at
the
given
price
can be

© 2000-2025, MetaQuotes Ltd.


834 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

either
confir
med or
rejecte
d.
Instant Execution Executi SYM BOL _T RADE_EXECUTION_INS T ANT
ng a
market
order
at the
specifi
ed
price
immedi
ately.

W hen
sendin
g a
trade
request
to be
execut
ed, the
platfor
m
automa
tically
adds
the
current
prices
to the
order.
· I
f
t
h
e
b
r
o
k
e
r
a
c

© 2000-2025, MetaQuotes Ltd.


835 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

c
e
p
t
s
t
h
e
p
r
i
c
e
,
t
h
e
o
r
d
e
r
i
s
e
x
e
c
u
t
e
d
.
· I
f
t
h
e
b
r
o
k
e
r
d
o
e
s

© 2000-2025, MetaQuotes Ltd.


836 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

n
o
t
a
c
c
e
p
t
t
h
e
r
e
q
u
e
s
t
e
d
p
r
i
c
e
,
a
"
R
e
q
u
o
t
e
"
i
s
s
e
n
t

t
h
e
b

© 2000-2025, MetaQuotes Ltd.


837 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

r
o
k
e
r
r
e
t
u
r
n
s
p
r
i
c
e
s
,
a
t
w
h
i
c
h
t
h
i
s
o
r
d
e
r
c
a
n
b
e
e
x
e
c
u
t
e

© 2000-2025, MetaQuotes Ltd.


838 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

d
.
Market Execution A SYM BOL _T RADE_EXECUTION_M ARKET
broker
makes
a
decisio
n about
the
order
executi
on
price
without
any
additio
nal
discuss
ion
with
the
trader.

S endin
g the
order
in such
a mode
means
advanc
e
consen
t to its
executi
on at
this
price.
Exchange Execution Trade SYM BOL _T RADE_EXECUTION_EXCHANGE
operati
ons are
execut
ed at
the
prices
of the
current

© 2000-2025, MetaQuotes Ltd.


839 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

market
offers.
Before sending an order with the current execution time, for the correct setting of the
ORDER_TYPE_FILLING value (volume execution type), you can use the S ymbolInfoInteger() function
with each financial instrument to get the SYM BOL_FILLING_MODE property value, which shows volume
execution types allowed for the symbol as a combination of flags. The ORDER_FILLING_RETURN filling
type is enabled at all times except for the " Market execution" mode
(SYM BOL_TRADE_EXECUTION_M ARKET).
The use of filling types depending on the execution mode can be shown as the following table:
Type of Execution\Fill Policy Fill or Kill (FOK Immediate or Return (Return
ORDER_FILLIN Cancel (IOC ORDER_FILLING
G_FOK) ORDER_FILLING _RETURN)
_IOC)

Instant Execution + (regardless + (regardless of + (always)


of a symbol a symbol
(SYM BOL_TRADE_EXECUTION_INS TANT) setting) setting)
R equest Execution + (regardless + (regardless of + (always)
of a symbol a symbol
SYM BOL _T RADE_EXECUTION_REQUES T setting) setting)

Market Execution + (set in the + (set in the - (disabled


symbol symbol regardless of
SYM BOL _T RADE_EXECUTION_M ARKET settings) settings) the symbol
settings)
Exchange Execution + (set in the + (set in the + (always)
symbol symbol
SYM BOL _T RADE_EXECUTION_EXCHANGE settings) settings)
In case of pending orders, the ORDER_FILLING_RETURN filling type should be used regardless of an
execution type (SYM BOL_TRADE_EXEMODE), since such orders are not meant for execution at the time
of sending. W hen using pending orders, a trader agrees in advance that, when conditions for a deal on
this order are met, the broker will use the filling type supported by the exchange.
Example:

//+------------------------------------------------------------------+
//| check if a given filling mode is allowed |
//+------------------------------------------------------------------+
bool IsFillingTypeAllowed(string symbol,int fill_type)
{
//--- get the value of the property describing the filling mode
int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);
//--- return 'true' if the fill_type mode is allowed

© 2000-2025, MetaQuotes Ltd.


840 Constants, Enumerations and Structures

return((filling&fill_type)==fill_type);
}

W hen sending a trade request using OrderS end() function, an order type from ENUM _ORDER_TYPE
enumeration should be specified for some operations. Not all types of orders may be allowed for a
specific symbol. SYM BOL_ORDER_MODE property describes the flags of the allowed order types.
Identifier Value Description

SYM BOL _ORDER_M ARKET 1 Market orders are allowed (Buy and
S ell)

SYM BOL _ORDER_LIMIT 2 Limit orders are allowed (Buy Limit


and S ell Limit)
SYM BOL _ORDER_S TOP 4 S top orders are allowed (Buy S top
and S ell S top)
SYM BOL _ORDER_S TOP_LIMIT 8 S top-limit orders are allowed (Buy
S top Limit and S ell S top Limit)

SYM BOL _ORDER_S L 16 S top Loss is allowed


SYM BOL _ORDER_TP 32 Take Profit is allowed
SYM BOL _ORDER_CLOSEBY 64 Close By operation is allowed, i.e.
closing a position by another open
position on the same instruments
but in the opposite direction. The
property is set for accounts with
the hedging accounting system
(ACCOUNT_M ARGIN_MODE_RETAIL
_HEDGING)

Example:

//+------------------------------------------------------------------+
//| The function prints out order types allowed for a symbol |
//+------------------------------------------------------------------+
void Check_SYMBOL_ORDER_MODE(string symbol)
{
//--- receive the value of the property describing allowed order types
int symbol_order_mode=(int)SymbolInfoInteger(symbol,SYMBOL_ORDER_MODE);
//--- check for market orders (Market Execution)
if((SYMBOL_ORDER_MARKET&symbol_order_mode)==SYMBOL_ORDER_MARKET)
Print(symbol+": Market orders are allowed (Buy and Sell)");
//--- check for Limit orders
if((SYMBOL_ORDER_LIMIT&symbol_order_mode)==SYMBOL_ORDER_LIMIT)
Print(symbol+": Buy Limit and Sell Limit orders are allowed");
//--- check for Stop orders
if((SYMBOL_ORDER_STOP&symbol_order_mode)==SYMBOL_ORDER_STOP)
Print(symbol+": Buy Stop and Sell Stop orders are allowed");

© 2000-2025, MetaQuotes Ltd.


841 Constants, Enumerations and Structures

//--- check for Stop Limit orders


if((SYMBOL_ORDER_STOP_LIMIT&symbol_order_mode)==SYMBOL_ORDER_STOP_LIMIT)
Print(symbol+": Buy Stop Limit and Sell Stop Limit orders are allowed");
//--- check if placing a Stop Loss orders is allowed
if((SYMBOL_ORDER_SL&symbol_order_mode)==SYMBOL_ORDER_SL)
Print(symbol+": Stop Loss orders are allowed");
//--- check if placing a Take Profit orders is allowed
if((SYMBOL_ORDER_TP&symbol_order_mode)==SYMBOL_ORDER_TP)
Print(symbol+": Take Profit orders are allowed");
//--- check if closing a position by an opposite one is allowed
if((SYMBOL_ORDER_TP&symbol_order_mode)==SYMBOL_ORDER_CLOSEBY)
Print(symbol+": Close by allowed");
//---
}

The ENUM _SYM BOL_CALC_MODE enumeration is used for obtaining information about how the margin
requirements for a symbol are calculated.
ENUM_SY MBOL_CALC_MODE

Identifier Desc Formula


ripti
on

SYM BOL _CALC_MODE_FOREX Fore Margin: Lots * Contract_S ize / Leverage *


x Margin_Rate
mod
e - Profit: (close_price - open_price) *
calcu Contract_S ize*Lots
latio
n of
profi
t and
marg
in
for
Fore
x
SYM BOL _CALC_MODE_FOREX_NO_L EV Fore Margin: Lots * Contract_S ize * Margin_Rate
ERAGE x No
Leve Profit: (close_price - open_price) * Contract_S ize
rage * Lots
mod
e –
calcu
latio
n of
profi
t and

© 2000-2025, MetaQuotes Ltd.


842 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

marg
in
for
Fore
x
symb
ols
with
out
takin
g
into
acco
unt
the
lever
age
SYM BOL _CALC_MODE_FUT URES Futur Margin: Lots * InitialMargin * Margin_Rate
es
mod Profit: (close_price - open_price) * TickPrice /
e - TickS ize*Lots
calcu
latio
n of
marg
in
and
profi
t for
futur
es
SYM BOL _CALC_MODE_CFD CFD Margin: Lots * ContractS ize * MarketPrice *
mod Margin_Rate
e -
calcu Profit: (close_price - open_price) * Contract_S ize *
latio Lots
n of
marg
in
and
profi
t for
CFD
SYM BOL _CALC_MODE_CFDINDEX CFD Margin: (Lots * ContractS ize * MarketPrice) *
inde TickPrice / TickS ize * Margin_Rate

© 2000-2025, MetaQuotes Ltd.


843 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

x
mod Profit: (close_price - open_price) * Contract_S ize *
e - Lots
calcu
latio
n of
marg
in
and
profi
t for
CFD
by
inde
xes
SYM BOL _CALC_MODE_CFDL EVERAGE CFD Margin: (Lots * ContractS ize * MarketPrice) /
Leve Leverage * Margin_Rate
rage
mod Profit: (close_price-open_price) * Contract_S ize *
e - Lots
calcu
latio
n of
marg
in
and
profi
t for
CFD
at
lever
age
tradi
ng
SYM BOL _CALC_MODE_EXCH_S TOCKS Exch Margin: Lots * ContractS ize * LastPrice *
ange Margin_Rate
mod
e – Profit: (close_price - open_price) * Contract_S ize *
calcu Lots
latio
n of
marg
in
and
profi
t for

© 2000-2025, MetaQuotes Ltd.


844 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

tradi
ng
secur
ities
on a
stock
exch
ange
SYM BOL _CALC_MODE_EXCH_FUT URE Futur Margin: Lots * InitialMargin * Margin_Rate or Lots *
S es MaintenanceMargin * Margin_Rate
mod
e – Profit: (close_price - open_price) * Lots * TickPrice
calcu / TickS ize
latio
n of
marg
in
and
profi
t for
tradi
ng
futur
es
contr
acts
on a
stock
exch
ange
SYM BOL _CALC_MODE_EXCH_FUT URE FO R Margin: Lots * InitialMargin * Margin_Rate or Lots *
S_FOR T S TS MaintenanceMargin * Margin_Rate
Futur
es Profit: (close_price - open_price) * Lots * TickPrice
mod / TickS ize
e –
calcu
latio
n of
marg
in
and
profi
t for
tradi
ng

© 2000-2025, MetaQuotes Ltd.


845 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

futur
es
contr
acts
on
FO R
TS .
The
marg
in
may
be
redu
ced
by
the
amo
unt
of
Marg
inDis
coun
t
devi
ation
accor
ding
to
the
follo
wing
rules
:
1. If
the
price
of a
long
posit
ion
(buy
order
) is
less
than
the
esti

© 2000-2025, MetaQuotes Ltd.


846 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

mate
d
price
,
Marg
inDis
coun
t =
Lots *
((Pri
ceS e
ttle-
Price
Orde
r)
*Tick
Price
/Tic
kS ize
)
2. If
the
price
of a
short
posit
ion
(sell
order
)
exce
eds
the
esti
mate
d
price
,
Marg
inDis
coun
t =
Lots *
((Pri
ceOr
der-
Price

© 2000-2025, MetaQuotes Ltd.


847 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

S ettl
e)
*Tick
Price
/Tic
kS ize
)
wher
e:
oP
r
i
c
e
S
e
t
t
l
e

e
s
t
i
m
a
t
e
d
(
c
l
e
a
r
i
n
g
)
p
r
i
c
e
o
f

© 2000-2025, MetaQuotes Ltd.


848 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

t
h
e
p
r
e
v
i
o
u
s
s
e
s
s
i
o
n
;
oP
r
i
c
e
O
r
d
e
r

a
v
e
r
a
g
e
w
e
i
g
h
t
e
d
p
o

© 2000-2025, MetaQuotes Ltd.


849 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

s
i
t
i
o
n
p
r
i
c
e
o
r
o
p
e
n
p
r
i
c
e
s
e
t
i
n
t
h
e
o
r
d
e
r
(
r
e
q
u
e
s
t
)
;
oT
i

© 2000-2025, MetaQuotes Ltd.


850 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

c
k
P
r
i
c
e

t
i
c
k
p
r
i
c
e
(
c
o
s
t
o
f
t
h
e
p
r
i
c
e
c
h
a
n
g
e
b
y
o
n
e
p
o
i
n

© 2000-2025, MetaQuotes Ltd.


851 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

t
)
oT
i
c
k
S
i
z
e

t
i
c
k
s
i
z
e
(
m
i
n
i
m
u
m
p
r
i
c
e
c
h
a
n
g
e
s
t
e
p
)
SYM BOL _CALC_MODE_EXCH_BONDS Exch Margin: Lots * ContractS ize * FaceValue *
ange open_price * /100
Bond
s

© 2000-2025, MetaQuotes Ltd.


852 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

mod Profit: Lots * close_price * FaceValue *


e – Contract_S ize + AccruedInterest * Lots *
calcu ContractS ize
latio
n of
marg
in
and
profi
t for
tradi
ng
bond
s on
a
stock
exch
ange
SYM BOL _CALC_MODE_EXCH_S TOCKS Exch Margin: Lots * ContractS ize * LastPrice *
_MOEX ange Margin_Rate
MOE
X Profit: (close_price - open_price) * Contract_S ize *
S toc Lots
ks
mod
e –
calcu
latio
n of
marg
in
and
profi
t for
tradi
ng
secur
ities
on
MOE
X

SYM BOL _CALC_MODE_EXCH_BONDS_ Exch Margin: Lots * ContractS ize * FaceValue *


MOEX ange open_price * /100
MOE
X
Bond

© 2000-2025, MetaQuotes Ltd.


853 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

s Profit: Lots * close_price * FaceValue *


mod Contract_S ize + AccruedInterest * Lots *
e – ContractS ize
calcu
latio
n of
marg
in
and
profi
t for
tradi
ng
bond
s on
MOE
X

SYM BOL _CALC_MODE_SERV_COLL AT E Colla Margin: no


RAL teral Profit: no
mod
e-a Market Value:
symb Lots *ContractS ize*MarketPrice*LiqudityRate
ol is
used
as a
non-
trada
ble
asset
on a
tradi
ng
acco
unt.
The
mark
et
value
of an
open
posit
ion
is
calcu
lated
base
d on

© 2000-2025, MetaQuotes Ltd.


854 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

the
volu
me,
curre
nt
mark
et
price
,
contr
act
size
and
liqui
dity
ratio
. The
value
is
inclu
ded
into
Asse
ts,
whic
h are
adde
d to
Equit
y.
Open
posit
ions
of
such
symb
ols
incre
ase
the
Free
Marg
in
amo
unt
and
are

© 2000-2025, MetaQuotes Ltd.


855 Constants, Enumerations and Structures

Identifier Desc Formula


ripti
on

used
as
addit
ional
marg
in
(colla
teral
) for
open
posit
ions
of
trada
ble
instr
ume
nts.

There are several symbol trading modes. Information about trading modes of a certain symbol is
reflected in the values of enumeration ENUM _SYM BOL_TRADE_MODE.
ENUM_SY MBOL_TRADE_MODE

Identifier Description

SYM BOL _T RADE_MODE_DISABL ED Trade is disabled for the symbol


SYM BOL _T RADE_MODE_LONGONL Y Allowed only long positions
SYM BOL _T RADE_MODE_SH OR TONL Y Allowed only short positions

SYM BOL _T RADE_MODE_CLOSEONL Y Allowed only position close operations

SYM BOL _T RADE_MODE_FULL No trade restrictions

Possible deal execution modes for a certain symbol are defined in enumeration
ENUM _SYM BOL _T RADE_EXECUTION.

ENUM_SY MBOL_TRADE_EX ECUTION

Identifier Description

SYM BOL _T RADE_EXECUTION_REQUES T Execution by request

SYM BOL _T RADE_EXECUTION_INS T ANT Instant execution

© 2000-2025, MetaQuotes Ltd.


856 Constants, Enumerations and Structures

Identifier Description

SYM BOL _T RADE_EXECUTION_M ARKET Market execution


SYM BOL _T RADE_EXECUTION_EXCHANGE Exchange execution

Methods of swap calculation at position transfer are specified in enumeration


ENUM _SYM BOL _SWAP_MODE. The method of swap calculation determines the units of measure of the
SYM BOL _SWAP_LONG and SYM BOL _SWAP_SH OR T parameters. For example, if swaps are charged in
the client deposit currency, then the values of those parameters are specified as an amount of money
in the client deposit currency.
ENUM_SY MBOL_SWAP_MODE

Identifier Description

SYM BOL _SWAP_MODE_DISABL ED S waps disabled (no swaps)


SYM BOL _SWAP_MODE_POINT S S waps are charged in points
SYM BOL _SWAP_MODE_CURRENCY_SYM BOL S waps are charged in money in base currency of
the symbol
SYM BOL _SWAP_MODE_CURRENCY_M ARGIN S wapsare charged in money in margin currency of
the symbol
SYM BOL _SWAP_MODE_CURRENCY_DEPOS IT S waps are charged in money, in client deposit
currency
SYM BOL _SWAP_MODE_CURRENCY_PR OFIT S waps are charged in money in profit calculation
currency
SYM BOL _SWAP_MODE_INT ERES T _CURRENT S waps are charged as the specified annual
interest from the instrument price at calculation
of swap (standard bank year is 360 days)
SYM BOL _SWAP_MODE_INT ERES T _OPEN S waps are charged as the specified annual
interest from the open price of position (standard
bank year is 360 days)
SYM BOL _SWAP_MODE_REOPEN_CURRENT S waps are charged by reopening positions. At the
end of a trading day the position is closed. Next
day it is reopened by the close price +/- specified
number of points (parameters
SYM BOL _SWAP_LONG and
SYM BOL _SWAP_SH OR T)

SYM BOL _SWAP_MODE_REOPEN_BID S waps are charged by reopening positions. At the


end of a trading day the position is closed. Next
day it is reopened by the current Bid price +/-
specified number of points (parameters
SYM BOL _SWAP_LONG and
SYM BOL _SWAP_SH OR T)

© 2000-2025, MetaQuotes Ltd.


857 Constants, Enumerations and Structures

Values of the ENUM _DAY_OF_WEEK enumeration are used for specifying days of week.
ENUM_DAY _OF_WEEK

Identifier Description

SUNDAY S unday

MONDAY Monday
TUESDAY Tuesday
WEDNESDAY W ednesday

THURSDAY Thursday
FR IDAY Friday

SAT URDAY S aturday

An option isa contract, which gives the right, but not the obligation, to buy or sell an underlying asset
(goods, stocks, futures, etc.) at a specified price on or before a specific date. The following
enumerations describe option properties, including the option type and the right arising from it.
ENUM_SY MBOL_OPTION_RIGHT

Identifier Description

SYM BOL _OPTION_R IGH T _CALL A call option gives you the right to buy an asset at
a specified price
SYM BOL _OPTION_R IGH T _PUT A put option gives you the right to sell an asset at
a specified price

ENUM_SY MBOL_OPTION_MODE

Identifier Description

SYM BOL _OPTION_MODE_EUR OPEAN European option may only be exercised on a


specified date (expiration, execution date,
delivery date)
SYM BOL _OPTION_MODE_AM ER ICAN American option may be exercised on any trading
day or before expiry. The period within which a
buyer can exercise the option is specified for it

Financialinstruments are categorized by sectors of the economy. An economic sector is a part of


economic activity which has specific characteristics, economic goals, functions and behavior, which
allow separating this sector from other parts of the economy. ENUM _SYM BOL_SECTOR lists the
economic sectors which a trading instruments can belong to.

© 2000-2025, MetaQuotes Ltd.


858 Constants, Enumerations and Structures

ENUM _SYM BOL _SECTOR

ID Description

SECTOR_UNDEFINED Undefined

SECTOR_BAS IC_M AT ER IAL S Basic materials

SECTOR_COMM UNICATION_SERVICES Communication services


SECTOR_CONSUM ER_CYCLICAL Consumer cyclical
SECTOR_CONSUM ER_DEFENS IVE Consumer defensive
SECTOR_CURRENCY Currencies
SECTOR_CURRENCY_CRYPTO Cryptocurrencies
SECTOR_ENERGY Energy

SECTOR_FINANCIAL Finance

SECTOR_HEALT H CARE H ealthcare

SECTOR_INDUS T R IAL S Industrials


SECTOR_REAL _ES T AT E R eal estate

SECTOR_T ECHNOLOGY Technology


SECTOR_UTILITIES Utilities

Each financial instrument can be assigned to a specific type of industry or economy branch. An
industry is a branch of an economy that produces a closely related set of raw materials, goods, or
services. ENUM _SYM BOL_INDUS TRY lists industries which a trading instrument can belong to.

ENUM _SYM BOL _INDUS T RY

ID Description

INDUS TRY_UNDEFINED Undefined

Basic materials

INDUS TRY_AGRICULTURAL_INPUTS Agricultural inputs

INDUS TRY_ALUMINIUM Aluminium

INDUS TRY_BUILDING_M ATERIALS Building materials


INDUS TRY_CHEMICALS Chemicals
INDUS TRY_COKING_COAL Coking coal
INDUS TRY_COPPER Copper
INDUS TRY_GOLD Gold

© 2000-2025, MetaQuotes Ltd.


859 Constants, Enumerations and Structures

ID Description

INDUS TRY_LUM BER_W OOD Lumber and wood production


INDUS TRY_INDUS TRIAL_M ETALS Other industrial metals and mining
INDUS TRY_PRECIOUS_M ETALS Other precious metals and mining
INDUS TRY_PAPER Paper and paper products
INDUS TRY_S ILVER S ilver

INDUS TRY_S PECIALTY_CHEMICALS S pecialty chemicals

INDUS TRY_S TEEL S teel

Communication services
INDUS TRY_ADVERTIS ING Advertising agencies
INDUS TRY_BROADCAS TING Broadcasting

INDUS TRY_GAMING_M ULTIM EDIA Electronic gaming and multimedia


INDUS TRY_ENTERTAINM ENT Entertainment

INDUS TRY_INTERNET_CONTENT Internet content and information


INDUS TRY_PUBLISHING Publishing
INDUS TRY_TELECOM Telecom services
Consumer cyclical
INDUS TRY_APPAREL_M ANUFACTURING Apparel manufacturing

INDUS TRY_APPAREL_RETAIL Apparel retail

INDUS TRY_AUTO_M ANUFACTURERS Auto manufacturers


INDUS TRY_AUTO_PARTS Auto parts
INDUS TRY_AUTO_DEALERSHIP Auto and truck dealerships
INDUS TRY_DEPARTM ENT_S TORES Department stores

INDUS TRY_FOOTWEAR_ACCESS ORIES Footwear and accessories


INDUS TRY_FURNISHINGS Furnishing, fixtures and appliances
INDUS TRY_GAM BLING Gambling

INDUS TRY_HOM E_IMPROV_RETAIL H ome improvement retail

INDUS TRY_INTERNET_RETAIL Internet retail


INDUS TRY_LEISURE Leisure
INDUS TRY_LODGING Lodging
INDUS TRY_LUXURY_GOODS Luxury goods

© 2000-2025, MetaQuotes Ltd.


860 Constants, Enumerations and Structures

ID Description

INDUS TRY_PACKAGING_CONTAINERS Packaging and containers


INDUS TRY_PERS ONAL_SERVICES Personal services
INDUS TRY_RECREATIONAL_VEHICLES R ecreational vehicles

INDUS TRY_RES IDENT_CONS TRUCTION R esidential construction

INDUS TRY_RES ORTS_CAS INOS R esorts and casinos


INDUS TRY_RES TAURANTS R estaurants

INDUS TRY_S PECIALTY_RETAIL S pecialty retail

INDUS TRY_TEXTILE_M ANUFACTURING Textile manufacturing


INDUS TRY_TRAVEL_SERVICES Travel services
Consumer defensive
INDUS TRY_BEVERAGES_BREWERS Beverages - Brewers
INDUS TRY_BEVERAGES_NON_ALCO Beverages - Non-alcoholic
INDUS TRY_BEVERAGES_W INERIES Beverages - W ineries and distilleries
INDUS TRY_CONFECTIONERS Confectioners
INDUS TRY_DIS COUNT_S TORES Discount stores

INDUS TRY_EDUCATION_TRAINIG Education and training services


INDUS TRY_FARM _PRODUCTS Farm products
INDUS TRY_FOOD_DIS TRIBUTION Food distribution

INDUS TRY_GROCERY_S TORES Grocery stores

INDUS TRY_HOUSEHOLD_PRODUCTS H ousehold and personal products

INDUS TRY_PACKAGED_FOODS Packaged foods


INDUS TRY_TOBACCO Tobacco
Energy

INDUS TRY_OIL_GAS_DRILLING Oil and gas drilling


INDUS TRY_OIL_GAS_EP Oil and gas extraction and processing
INDUS TRY_OIL_GAS_EQUIPM ENT Oil and gas equipment and services
INDUS TRY_OIL_GAS_INTEGRATED Oil and gas integrated
INDUS TRY_OIL_GAS_MIDS TREAM Oil and gas midstream
INDUS TRY_OIL_GAS_REFINING Oil and gas refining and marketing
INDUS TRY_THERM AL_COAL Thermal coal

© 2000-2025, MetaQuotes Ltd.


861 Constants, Enumerations and Structures

ID Description

INDUS TRY_URANIUM Uranium

Finance

INDUS TRY_EXCHANGE_TRADED_FUND Exchange traded fund

INDUS TRY_ASSETS_M ANAGEM ENT Assets management


INDUS TRY_BANKS_DIVERS IFIED Bank s - Diversified
INDUS TRY_BANKS_REGIONAL Bank s - Regional
INDUS TRY_CAPITAL_M ARKETS Capital markets
INDUS TRY_CLOSE_END_FUND_DEBT Closed-End fund - Debt
INDUS TRY_CLOSE_END_FUND_EQUITY Closed-end fund - Equity
INDUS TRY_CLOSE_END_FUND_FOREIGN Closed-end fund - Foreign
INDUS TRY_CREDIT_SERVICES Credit services
INDUS TRY_FINANCIAL_CONGLOM ERATE Financial conglomerates

INDUS TRY_FINANCIAL_DATA_EXCHANGE Financial data and stock exchange


INDUS TRY_INSURANCE_BROKERS Insurance brokers
INDUS TRY_INSURANCE_DIVERS IFIED Insurance - Diversified
INDUS TRY_INSURANCE_LIFE Insurance - Life
INDUS TRY_INSURANCE_PROPERTY Insurance - Property and casualty
INDUS TRY_INSURANCE_REINSURANCE Insurance - Reinsurance
INDUS TRY_INSURANCE_S PECIALTY Insurance - S pecialty
INDUS TRY_MORTGAGE_FINANCE Mortgage finance
INDUS TRY_SHELL_COMPANIES S hell companies

H ealthcare

INDUS TRY_BIOTECHNOLOGY Biotechnology

INDUS TRY_DIAGNOS TICS_RESEARCH Diagnostics and research


INDUS TRY_DRUGS_M ANUFACTURERS Drugs manufacturers - general
INDUS TRY_DRUGS_M ANUFACTURERS_S PEC Drugs manufacturers - S pecialty and generic
INDUS TRY_HEALTHCARE_PLANS H ealthcare plans

INDUS TRY_HEALTH_INFORM ATION H ealth information services

INDUS TRY_M EDICAL_FACILITIES Medical care facilities


INDUS TRY_M EDICAL_DEVICES Medical devices

© 2000-2025, MetaQuotes Ltd.


862 Constants, Enumerations and Structures

ID Description

INDUS TRY_M EDICAL_DIS TRIBUTION Medical distribution


INDUS TRY_M EDICAL_INS TRUM ENTS Medical instruments and supplies
INDUS TRY_PHARM _RETAILERS Pharmaceutical retailers
Industrials
INDUS TRY_AEROS PACE_DEFENSE Aerospace and defense

INDUS TRY_AIRLINES Airlines

INDUS TRY_AIRPORTS_SERVICES Airports and air services


INDUS TRY_BUILDING_PRODUCTS Building products and equipment
INDUS TRY_BUS INESS_EQUIPM ENT Business equipment and supplies

INDUS TRY_CONGLOM ERATES Conglomerates


INDUS TRY_CONSULTING_SERVICES Consulting services
INDUS TRY_ELECTRICAL_EQUIPM ENT Electrical equipment and parts

INDUS TRY_ENGINEERING_CONS TRUCTION Engineering and construction


INDUS TRY_FARM _HEAVY_M ACHINERY Farm and heavy construction machinery
INDUS TRY_INDUS TRIAL_DIS TRIBUTION Industrial distribution
INDUS TRY_INFRAS TRUCTURE_OPERATIONS Infrastructure operations
INDUS TRY_FREIGHT_LOGIS TICS Integrated freight and logistics
INDUS TRY_M ARINE_SHIPPING Marine shipping
INDUS TRY_M ETAL_FABRICATION Metal fabrication
INDUS TRY_POLLUTION_CONTROL Pollution and treatment controls
INDUS TRY_RAILROADS R ailroads

INDUS TRY_RENTAL_LEAS ING R ental and leasing services


INDUS TRY_SECURITY_PROTECTION S ecurity and protection services

INDUS TRY_S PEALITY_BUS INESS_SERVICES S pecialty business services


INDUS TRY_S PEALITY_M ACHINERY S pecialty industrial machinery

INDUS TRY_S TUFFING_EMPLOYM ENT S tuffing and employment services


INDUS TRY_TOOLS_ACCESS ORIES Tools and accessories
INDUS TRY_TRUCKING Trucking
INDUS TRY_WAS TE_M ANAGEM ENT W aste management

R eal estate

© 2000-2025, MetaQuotes Ltd.


863 Constants, Enumerations and Structures

ID Description

INDUS TRY_REAL_ES TATE_DEVELOPM ENT R eal estate - Development

INDUS TRY_REAL_ES TATE_DIVERS IFIED R eal estate - Diversified

INDUS TRY_REAL_ES TATE_SERVICES R eal estate services

INDUS TRY_REIT_DIVERS IFIED REIT - Diversified


INDUS TRY_REIT_HEALTCARE REIT - Healthcase facilities
INDUS TRY_REIT_HOTEL_MOTEL REIT - Hotel and motel
INDUS TRY_REIT_INDUS TRIAL REIT - Industrial
INDUS TRY_REIT_MORTAGE REIT - Mortgage
INDUS TRY_REIT_OFFICE REIT - Office
INDUS TRY_REIT_RES IDENTAL REIT - Residential
INDUS TRY_REIT_RETAIL REIT - Retail
INDUS TRY_REIT_S PECIALITY REIT - S pecialty
Technology
INDUS TRY_COMM UNICATION_EQUIPM ENT Communication equipment
INDUS TRY_COMPUTER_HARDWARE Computer hardware
INDUS TRY_CONSUM ER_ELECTRONICS Consumer electronics
INDUS TRY_ELECTRONIC_COMPONENTS Electronic components

INDUS TRY_ELECTRONIC_DIS TRIBUTION Electronics and computer distribution


INDUS TRY_IT_SERVICES Information technology services
INDUS TRY_S CIENTIFIC_INS TRUM ENTS S cientific and technical instruments

INDUS TRY_SEMICONDUCTOR_EQUIPM ENT S emiconductor equipment and materials

INDUS TRY_SEMICONDUCTORS S emiconductors

INDUS TRY_S OFTWARE_APPLICATION S oftware - Application

INDUS TRY_S OFTWARE_INFRAS TRUCTURE S oftware - Infrastructure


INDUS TRY_S OLAR S olar

Utilities

INDUS TRY_UTILITIES_DIVERS IFIED Utilities - Diversified


INDUS TRY_UTILITIES_POWERPRODUCERS Utilities - Independent power producers
INDUS TRY_UTILITIES_RENEWABLE Utilities - Renewable
INDUS TRY_UTILITIES_REGULATED_ELECTRIC Utilities - Regulated electric

© 2000-2025, MetaQuotes Ltd.


864 Constants, Enumerations and Structures

ID Description

INDUS TRY_UTILITIES_REGULATED_GAS Utilities - Regulated gas


INDUS TRY_UTILITIES_REGULATED_WATER Utilities - Regulated water
INDUS TRY_UTILITIES_FIRS T S tart
of the utilities services types enumeration.
Corresponds to
INDUS TRY_UTILITIES_DIVERS IFIED.
INDUS TRY_UTILITIES_LAS T End of the utilities services types enumeration.
Corresponds to
INDUS TRY_UTILITIES_REGULATED_WATER.

© 2000-2025, MetaQuotes Ltd.


865 Constants, Enumerations and Structures

Account Properties
To obtain information about the current account there are several functions : AccountInfoInteger(),
AccountInfoDouble() and AccountInfoS tring(). The function parameter values can accept values from
the corresponding ENUM _ACCOUNT_INFO enumerations.
For the function AccountInfoInteger()
ENUM_ACCOUNT_INFO_INTEGER

Identifier Descrip Type


tion

ACCOUNT _LOGIN Account long


number
ACCOUNT _T RADE_MODE Account ENUM _ACCOUNT _T RADE_MODE
trade
mode
ACCOUNT _L EVERAGE Account long
leverag
e
ACCOUNT _LIMIT _ORDERS Maximu int
m
allowed
number
of
active
pending
orders
ACCOUNT _M ARGIN_S O_MODE Mode ENUM _ACCOUNT _S TOPOUT _MODE
for
setting
the
minima
l
allowed
margin
ACCOUNT _T RADE_ALLOWED Allowed bool
trade
for the
current
account
ACCOUNT _T RADE_EXPER T Allowed bool
trade
for an
Expert
Advisor

© 2000-2025, MetaQuotes Ltd.


866 Constants, Enumerations and Structures

Identifier Descrip Type


tion

ACCOUNT _M ARGIN_MODE Margin ENUM _ACCOUNT _M ARGIN_MODE


calculat
ion
mode
ACCOUNT _CURRENCY_DIGIT S The int
number
of
decimal
places
in the
account
currenc
y,
which
are
require
d for an
accurat
e
display
of
trading
results
ACCOUNT _FIFO_CLOSE An bool
indicati
on
showin
g that
positio
ns can
only be
closed
by FIFO
rule. If
the
propert
y value
is set
to true,
then
each
symbol
positio
ns will
be
closed
in the

© 2000-2025, MetaQuotes Ltd.


867 Constants, Enumerations and Structures

Identifier Descrip Type


tion

same
order,
in
which
they
are
opened
,
starting
with
the
oldest
one. In
case of
an
attemp
t to
close
positio
ns in a
differe
nt
order,
the
trader
will
receive
an
appropr
iate
error.

For
account
s with
the
non-
hedging
positio
n
account
ing
mode
(ACCOU
NT _M A
RGIN_M
ODE!=A
CCOUN

© 2000-2025, MetaQuotes Ltd.


868 Constants, Enumerations and Structures

Identifier Descrip Type


tion

T_M AR
GIN_M
ODE_RE
TAIL_H
EDGING
), the
propert
y value
is
always
false.
ACCOUNT _HEDGE_ALLOWED Allowed bool
opposit
e
positio
ns on a
single
symbol
For the function AccountInfoDouble()
ENUM_ACCOUNT_INFO_DOUBLE

Identifier Descrip Type


tion

ACCOUNT _BAL ANCE Account double


balance
in the
deposit
currenc
y
ACCOUNT _CREDIT Account double
credit
in the
deposit
currenc
y
ACCOUNT _PR OFIT Current double
profit
of an
account
in the
deposit
currenc
y

© 2000-2025, MetaQuotes Ltd.


869 Constants, Enumerations and Structures

Identifier Descrip Type


tion

ACCOUNT _EQUIT Y Account double


equity
in the
deposit
currenc
y
ACCOUNT _M ARGIN Account double
margin
used in
the
deposit
currenc
y
ACCOUNT _M ARGIN_FREE Free double
margin
of an
account
in the
deposit
currenc
y
ACCOUNT _M ARGIN_L EVEL Account double
margin
level in
percent
s
ACCOUNT _M ARGIN_S O_CALL Margin double
call
level.
Depend
ing on
the set
ACCOU
NT _M A
RGIN_S
O_MOD
E is
express
ed in
percent
s or in
the
deposit
currenc
y

© 2000-2025, MetaQuotes Ltd.


870 Constants, Enumerations and Structures

Identifier Descrip Type


tion

ACCOUNT _M ARGIN_S O_S O Margin double


stop
out
level.
Depend
ing on
the set
ACCOU
NT _M A
RGIN_S
O_MOD
E is
express
ed in
percent
s or in
the
deposit
currenc
y
ACCOUNT _M ARGIN_INITIAL Initial double
margin.
The
amount
reserve
d on an
account
to
cover
the
margin
of all
pending
orders
ACCOUNT _M ARGIN_M AINT ENANCE Mainte double
nance
margin.
The
minimu
m
equity
reserve
d on an
account
to
cover
the

© 2000-2025, MetaQuotes Ltd.


871 Constants, Enumerations and Structures

Identifier Descrip Type


tion

minimu
m
amount
of all
open
positio
ns
ACCOUNT _ASSET S The double
current
assets
of an
account
ACCOUNT _LIABILITIES The double
current
liabiliti
es on
an
account
ACCOUNT _COMMISS ION_BLOCKED The double
current
blocked
commis
sion
amount
on an
account
For function AccountInfoS tring()
ENUM_ACCOUNT_INFO_STRING

Identifier Descrip Type


tion

ACCOUNT _NAM E Client string


name
ACCOUNT _SERVER Trade string
server
name
ACCOUNT _CURRENCY Account string
currenc
y
ACCOUNT _COMPANY Name string
of a
compan

© 2000-2025, MetaQuotes Ltd.


872 Constants, Enumerations and Structures

Identifier Descrip Type


tion

y that
serves
the
account
There are several types of accounts that can be opened on a trade server. The type of account on
which an MQL5 program is running can be found out using the ENUM _ACCOUNT_TRADE_MODE
enumeration.
ENUM_ACCOUNT_TRADE_MODE

Identifier Description

ACCOUNT _T RADE_MODE_DEMO Demo account


ACCOUNT _T RADE_MODE_CONT ES T Contest account
ACCOUNT _T RADE_MODE_REAL R eal account

In case equity is not enough for maintaining open positions, the S top Out situation, i.e. forced closing
occurs. The minimum margin level at which S top Out occurs can be set in percentage or in monetary
terms. To find out the mode set for the account use the ENUM _ACCOUNT_S TOPOUT_MODE
enumeration.
ENUM_ACCOUNT_STOPOUT_MODE

Identifier Description

ACCOUNT _S TOPOUT _MODE_PER CENT Account stop out mode in percents

ACCOUNT _S TOPOUT _MODE_MONEY Account stop out mode in money

ENUM_ACCOUNT_MARGIN_MODE

Identifier Description

ACCOUNT _M ARGIN_MODE_RET AIL _NETTING Used for the OTC markets to interpret
positions in the " netting" mode (only one
position can exist for one symbol). The margin
is calculated based on the symbol type
(SYM BOL_TRADE_CALC_MODE).
ACCOUNT _M ARGIN_MODE_EXCHANGE Used for the exchange markets. Margin is
calculated based on the discounts specified in
symbol settings. Discounts are set by the
broker, but not less than the values set by the
exchange.
ACCOUNT _M ARGIN_MODE_RET AIL _HEDGING Used for the exchange markets where
individual positions are possible (hedging,
multiple positions can exist for one symbol).
The margin is calculated based on the symbol

© 2000-2025, MetaQuotes Ltd.


873 Constants, Enumerations and Structures

Identifier Description

type (SYM BOL_TRADE_CALC_MODE) taking


into account the hedged margin
(SYM BOL_M ARGIN_HEDGED).
An example of the script that outputs a brief account information.
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Name of the company
string company=AccountInfoString(ACCOUNT_COMPANY);
//--- Name of the client
string name=AccountInfoString(ACCOUNT_NAME);
//--- Account number
long login=AccountInfoInteger(ACCOUNT_LOGIN);
//--- Name of the server
string server=AccountInfoString(ACCOUNT_SERVER);
//--- Account currency
string currency=AccountInfoString(ACCOUNT_CURRENCY);
//--- Demo, contest or real account
ENUM_ACCOUNT_TRADE_MODE account_type=(ENUM_ACCOUNT_TRADE_MODE)AccountInfoInteger(ACCOUNT_TRADE_M
//--- Now transform the value of the enumeration into an understandable form
string trade_mode;
switch(account_type)
{
case ACCOUNT_TRADE_MODE_DEMO:
trade_mode="demo";
break;
case ACCOUNT_TRADE_MODE_CONTEST:
trade_mode="contest";
break;
default:
trade_mode="real";
break;
}
//--- Stop Out is set in percentage or money
ENUM_ACCOUNT_STOPOUT_MODE stop_out_mode=(ENUM_ACCOUNT_STOPOUT_MODE)AccountInfoInteger(ACCOUNT_MA
//--- Get the value of the levels when Margin Call and Stop Out occur
double margin_call=AccountInfoDouble(ACCOUNT_MARGIN_SO_CALL);
double stop_out=AccountInfoDouble(ACCOUNT_MARGIN_SO_SO);
//--- Show brief account information
PrintFormat("The account of the client '%s' #%d %s opened in '%s' on the server '%s'",
name,login,trade_mode,company,server);
PrintFormat("Account currency - %s, MarginCall and StopOut levels are set in %s",
currency,(stop_out_mode==ACCOUNT_STOPOUT_MODE_PERCENT)?"percentage":" money");

© 2000-2025, MetaQuotes Ltd.


874 Constants, Enumerations and Structures

PrintFormat("MarginCall=%G, StopOut=%G",margin_call,stop_out);
}

© 2000-2025, MetaQuotes Ltd.


875 Constants, Enumerations and Structures

Testing Statistics
After the testing is over, different parameters of the trading results statistics are calculated. The
values of the parameters can be obtained using the TesterS tatistics() function, by specifying the
parameter ID from the ENUM _S TATIS TICS enumeration.
Although two types of parameters (int and double) are used for calculating statistics, the function
returns all values in the double form. All the statistic values of the double type are expressed in the
deposit currency by default, unless otherwise specified.
ENUM_STATISTICS

ID Description of a Type
statistic parameter

S T AT _INITIAL _DEPOS IT The value of the initial double


deposit
S T AT _W IT HDRAWAL Money withdrawn from double
an account
S T AT _PR OFIT Net profit after double
testing, the sum of
S T AT _GR OSS_PR OFIT
and
S T AT _GR OSS_LOSS
(S TAT_GROSS_LOSS is
always less than or
equal to zero)
S T AT _GR OSS_PR OFIT Total profit, the sum double
of all profitable
(positive) trades. The
value is greater than
or equal to zero
S T AT _GR OSS_LOSS Total loss, the sum of double
all negative trades.
The value is less than
or equal to zero
S T AT _M AX_PR OFITT RADE Maximum profit – the double
largest value of all
profitable trades. The
value is greater than
or equal to zero
S T AT _M AX_LOSS T RADE Maximum loss – the double
lowest value of all
losing trades. The
value is less than or
equal to zero

© 2000-2025, MetaQuotes Ltd.


876 Constants, Enumerations and Structures

ID Description of a Type
statistic parameter

S T AT _CONPR OFITM AX Maximum profit in a double


series of profitable
trades. The value is
greater than or equal
to zero
S T AT _CONPR OFITM AX_T RADES The number of trades int
that have formed
S T AT _CONPR OFITM AX
(maximum profit in a
series of profitable
trades)
S T AT _M AX_CONW INS The total profit of the double
longest series of
profitable trades
S T AT _M AX_CONPR OFIT _T RADES The number of trades int
in the longest series of
profitable trades
S T AT _M AX_CONW INS

S T AT _CONLOSS M AX Maximum loss in a double


series of losing trades.
The value is less than
or equal to zero
S T AT _CONLOSS M AX_T RADES The number of trades int
that have formed
S T AT _CONLOSS M AX
(maximum loss in a
series of losing trades)
S T AT _M AX_CONLOSSES The total loss of the double
longest series of losing
trades
S T AT _M AX_CONLOSS_T RADES The number of trades int
in the longest series of
losing trades
S T AT _M AX_CONLOSSE
S

S T AT _BAL ANCEMIN Minimum balance double


value
S T AT _BAL ANCE_DD Maximum balance double
drawdown in monetary
terms. In the process
of trading, a balance
may have numerous

© 2000-2025, MetaQuotes Ltd.


877 Constants, Enumerations and Structures

ID Description of a Type
statistic parameter

drawdowns ; here the


largest value is taken
S T AT _BAL ANCEDD_PER CENT Balance drawdown as a double
percentage that was
recorded at the
moment of the
maximum balance
drawdown in monetary
terms
(S TAT_BALANCE_DD).
S T AT _BAL ANCE_DDREL _PER CENT Maximum balance double
drawdown as a
percentage. In the
process of trading, a
balance may have
numerous drawdowns,
for each of which the
relative drawdown
value in percents is
calculated. The
greatest value is
returned
S T AT _BAL ANCE_DD_REL ATIVE Balance drawdown in double
monetary terms that
was recorded at the
moment of the
maximum balance
drawdown as a
percentage
(S TAT_BALANCE_DDRE
L_PERCENT).
S T AT _EQUIT YMIN Minimum equity value double
S T AT _EQUIT Y_DD Maximum equity double
drawdown in monetary
terms. In the process
of trading, numerous
drawdowns may appear
on the equity; here the
largest value is taken
S T AT _EQUIT YDD_PER CENT Drawdown in percent double
that was recorded at
the moment of the
maximum equity
drawdown in monetary

© 2000-2025, MetaQuotes Ltd.


878 Constants, Enumerations and Structures

ID Description of a Type
statistic parameter

terms
(S TAT_EQUITY_DD).
S T AT _EQUIT Y_DDREL _PER CENT Maximum equity double
drawdown as a
percentage. In the
process of trading, an
equity may have
numerous drawdowns,
for each of which the
relative drawdown
value in percents is
calculated. The
greatest value is
returned
S T AT _EQUIT Y_DD_REL ATIVE Equity drawdown in double
monetary terms that
was recorded at the
moment of the
maximum equity
drawdown in percent
(S TAT_EQUITY_DDREL
_PER CENT).

S T AT _EXPECT ED_PAYOFF Expected payoff double


S T AT _PR OFIT _FACTOR Profit factor, equal to double
the ratio of
S T AT _GR OSS_PR OFIT /
S T AT _GR OSS_LOSS . If
S T AT _GR OSS_LOSS=0,
the profit factor is
equal to DBL_M AX
S T AT _RECOVERY_FACTOR R ecovery factor, equal double
to the ratio of
S T AT _PR OFIT /S T AT _B
AL ANCE_DD

S T AT _SHAR PE_RATIO S harpe ratio double


S T AT _MIN_M ARGINL EVEL Minimum value of the double
margin level
S T AT _CUS TOM _ONT ES T ER The value of the double
calculated custom
optimization criterion
returned by the
OnTester() function
S T AT _DEAL S The number of deals int

© 2000-2025, MetaQuotes Ltd.


879 Constants, Enumerations and Structures

ID Description of a Type
statistic parameter

S T AT _T RADES The number of trades int


S T AT _PR OFIT _T RADES Profitable trades int
S T AT _LOSS_T RADES Losing trades int
S T AT _SH OR T _T RADES S hort trades int
S T AT _LONG_T RADES Long trades int
S T AT _PR OFIT _SH OR TT RADES Profitable short trades int
S T AT _PR OFIT _LONGT RADES Profitable long trades int
S T AT _PR OFITT RADES_AVGCON Average length of a int
profitable series of
trades
S T AT _LOSS T RADES_AVGCON Average length of a int
losing series of trades
S T AT _COMPL EX_CR IT ER ION Complex optimization
criterion

© 2000-2025, MetaQuotes Ltd.


880 Constants, Enumerations and Structures

Trade Constants
Various constants used for programming trading strategies are divided into the following groups :
· H istory Database Properties – receiving general information on a symbol;
· Order properties – obtaining information about trade orders ;
· Position properties – obtaining information about current positions ;
· Deal properties – obtaining information about deals ;
· Trade operation types – description of trade operations available;
· Trade transaction types - description of possible trade transactions types ;
· Trade orders in DOM – separation of orders according to the direction of a requested operation.

© 2000-2025, MetaQuotes Ltd.


881 Constants, Enumerations and Structures

History Database Properties


W hen accessing timeseries the S eriesInfoInteger() function is used for obtaining additional symbol
information. Identifier of a required property is passed as the function parameter. The identifier can
be one of values of ENUM _SERIES_INFO_INTEGER.
ENUM_SERIES_INFO_INTEGER

Identifier Description Type

SER IES_BARS_COUNT Bars count for the symbol- long


period for the current
moment
SER IES_FIRS T DAT E The very first date for the datetime
symbol-period for the
current moment
SER IES_L AS T BAR_DAT E Open time of the last bar of datetime
the symbol-period
SER IES_SERVER_FIRS T DAT E The very first date in the datetime
history of the symbol on the
server regardless of the
timeframe
SER IES_T ER MINAL _FIRS T DAT E The very first date in the datetime
history of the symbol in the
client terminal, regardless
of the timeframe
SER IES_SYNCHR ONIZED S ymbol/period data bool
synchronization flag for the
current moment

© 2000-2025, MetaQuotes Ltd.


882 Constants, Enumerations and Structures

Order Properties
R equests to execute trade operations are formalized as orders. Each order has a variety of properties
for reading. Information on them can be obtained using functions OrderGet...() and
H istoryOrderGet...().

For functions OrderGetInteger() and HistoryOrderGetInteger()


ENUM_ORDER_PROPERTY _INTEGER

Identifier Description Type

ORDER_TICKET Order ticket. long


Unique
number
assigned to
each order
ORDER_TIM E_SETUP Order setup datetime
time
ORDER_TYPE Order type ENUM _ORDER_T YPE

ORDER_S TATE Order state ENUM _ORDER_S T AT E

ORDER_TIM E_EXPIRATION Order datetime


expiration
time
ORDER_TIM E_DONE Order datetime
execution or
cancellation
time
ORDER_TIM E_SETUP_M S C The time of long
placing an
order for
execution in
milliseconds
since
01.01.1970

ORDER_TIM E_DONE_M S C Order long


execution/can
cellation time
in milliseconds
since
01.01.1970

ORDER_TYPE_FILLING Order filling ENUM _ORDER_T YPE_FILLING


type
ORDER_TYPE_TIM E Order lifetime ENUM _ORDER_T YPE_TIM E

© 2000-2025, MetaQuotes Ltd.


883 Constants, Enumerations and Structures

Identifier Description Type

ORDER_M AGIC ID of an long


Expert Advisor
that has
placed the
order
(designed to
ensure that
each Expert
Advisor places
its own unique
number)
ORDER_REAS ON The reason or ENUM _ORDER_REAS ON
source for
placing an
order
ORDER_POS ITION_ID Position long
identifier that
is set to an
order as soon
as it is
executed.
Each executed
order results
in a deal that
opens or
modifies an
already
existing
position. The
identifier of
exactly this
position is set
to the
executed
order at this
moment.
ORDER_POS ITION_BY_ID Identifier of long
an opposite
position used
for closing by
order
ORDER_TYPE_
CLOSE_BY
For functions OrderGetDouble() and HistoryOrderGetDouble()
ENUM_ORDER_PROPERTY _DOUBLE

© 2000-2025, MetaQuotes Ltd.


884 Constants, Enumerations and Structures

Identifier Description Type

ORDER_VOLUM E_INITIAL Order initial double


volume
ORDER_VOLUM E_CURRENT Order current double
volume
ORDER_PRICE_OPEN Price specified double
in the order
ORDER_S L S top Loss double
value
ORDER_TP Take Profit double
value
ORDER_PRICE_CURRENT The current double
price of the
order symbol
ORDER_PRICE_S TOPLIMIT The Limit double
order price for
the S topLimit
order
For functions OrderGetS tring() and HistoryOrderGetS tring()
ENUM_ORDER_PROPERTY _STRING

Identifier Description Type

ORDER_SYM BOL S ymbol of the string


order
ORDER_COMM ENT Order string
comment
ORDER_EXTERNAL_ID Order string
identifier in
an external
trading
system (on
the Exchange)

W hen sendinga trade request using the OrderS end() function, some operations require the indication
of the order type. The order type is specified in the type field of the special structure
M qlTradeRequest, and can accept values of the ENUM _ORDER_TYPE enumeration.
ENUM_ORDER_TY PE

Identifier Description

ORDER_TYPE_BUY Market Buy order

© 2000-2025, MetaQuotes Ltd.


885 Constants, Enumerations and Structures

Identifier Description

ORDER_TYPE_SELL Market S ell order


ORDER_TYPE_BUY_LIMIT Buy Limit pending order
ORDER_TYPE_SELL_LIMIT S ell Limit pending order
ORDER_TYPE_BUY_S TOP Buy S top pending order
ORDER_TYPE_SELL_S TOP S ell S top pending order
ORDER_TYPE_BUY_S TOP_LIMIT Upon reaching the order price, a pending Buy Limit order is
placed at the S topLimit price
ORDER_TYPE_SELL_S TOP_LIMIT Upon reaching the order price, a pending S ell Limit order is
placed at the S topLimit price
ORDER_TYPE_CLOSE_BY Order to close a position by an opposite one

Each order has a status that describes its state. To obtain information, use OrderGetInteger() or
H istoryOrderGetInteger() with the ORDER_S T AT E modifier. Allowed values are stored in the
ENUM _ORDER_S T AT E enumeration.

ENUM_ORDER_STATE

Identifier Description

ORDER_S TATE_S TARTED Order checked, but not yet accepted by broker
ORDER_S TATE_PLACED Order accepted
ORDER_S TATE_CANCELED Order canceled by client
ORDER_S TATE_PARTIAL Order partially executed
ORDER_S TATE_FILLED Order fully executed
ORDER_S TATE_REJECTED Order rejected
ORDER_S TATE_EXPIRED Order expired
ORDER_S TATE_REQUES T_ADD Order is being registered (placing to the trading system)
ORDER_S TATE_REQUES T_MODIFY Order is being modified (changing its parameters)
ORDER_S TATE_REQUES T_CANCEL Order is being deleted (deleting from the trading system)

W hen sending a trade request for execution at the current time (time in force), the price and the
required buy/sell volume should be specified. Also, keep in mind that financial markets provide no
guarantee that the entire requested volume is available for a certain financial instrument at the
desired price. Therefore, trading operations in real time are regulated using the price and volume
execution modes. The modes, or execution policies, define the rules for cases when the price has
changed or the requested volume cannot be completely fulfilled at the moment.

© 2000-2025, MetaQuotes Ltd.


886 Constants, Enumerations and Structures

Price execution mode can be obtained from the SYM BOL _T RADE_EXEMODE symbol property containing
the combination of flags from the ENUM _SYM BOL_TRADE_EXECUTION enumeration.
Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION
tion

Execution mode Executi SYM BOL _T RADE_EXECUTION_REQUES T


ng a
(Request Execution) market
order
at the
price
previou
sly
receive
d from
the
broker.

Prices
for a
certain
market
order
are
request
ed
from
the
broker
before
the
order
is sent.
Upon
receivi
ng the
prices,
order
executi
on at
the
given
price
can be
either
confir
med or
rejecte
d.

© 2000-2025, MetaQuotes Ltd.


887 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

Instant Execution Executi SYM BOL _T RADE_EXECUTION_INS T ANT


ng a
(Instant Execution) market
order
at the
specifi
ed
price
immedi
ately.

W hen
sendin
g a
trade
request
to be
execut
ed, the
platfor
m
automa
tically
adds
the
current
prices
to the
order.
· I
f
t
h
e
b
r
o
k
e
r
a
c
c
e
p
t
s
t

© 2000-2025, MetaQuotes Ltd.


888 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

h
e
p
r
i
c
e
,
t
h
e
o
r
d
e
r
i
s
e
x
e
c
u
t
e
d
.
· I
f
t
h
e
b
r
o
k
e
r
d
o
e
s
n
o
t
a
c
c

© 2000-2025, MetaQuotes Ltd.


889 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

e
p
t
t
h
e
r
e
q
u
e
s
t
e
d
p
r
i
c
e
,
a
"
R
e
q
u
o
t
e
"
i
s
s
e
n
t

t
h
e
b
r
o
k
e
r
r

© 2000-2025, MetaQuotes Ltd.


890 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

e
t
u
r
n
s
p
r
i
c
e
s
,
a
t
w
h
i
c
h
t
h
i
s
o
r
d
e
r
c
a
n
b
e
e
x
e
c
u
t
e
d
.
Market Execution A SYM BOL _T RADE_EXECUTION_M ARKET
broker
(Market Execution) makes
a

© 2000-2025, MetaQuotes Ltd.


891 Constants, Enumerations and Structures

Execution mode Descrip The value in ENUM _SYM BOL _T RADE_EXECUTION


tion

decisio
n about
the
order
executi
on
price
without
any
additio
nal
discuss
ion
with
the
trader.

S endin
g the
order
in such
a mode
means
advanc
e
consen
t to its
executi
on at
this
price.
Exchange Execution Trade SYM BOL _T RADE_EXECUTION_EXCHANGE
operati
(Exchange Execution) ons are
execut
ed at
the
prices
of the
current
market
offers.
Volume filling policy is specified in the ORDER_T YPE_FILLING order property and may contain only
the values from the ENUM _ORDER_TYPE_FILLING enumeration

© 2000-2025, MetaQuotes Ltd.


892 Constants, Enumerations and Structures

Fill policy Descrip The value in ENUM _ORDER_T YPE_FILLING


tion

Fill or Kill An ORDER_FILLING_FOK


order
can be
execut
ed in
the
specifi
ed
volume
only.

If the
necess
ary
amoun
t of a
financi
al
instru
ment
is
current
ly
unavail
able in
the
market
, the
order
will not
be
execut
ed.

The
desire
d
volume
can be
made
up of
several
availab
le
offers.

The
possibi

© 2000-2025, MetaQuotes Ltd.


893 Constants, Enumerations and Structures

Fill policy Descrip The value in ENUM _ORDER_T YPE_FILLING


tion

lity of
using
FO K
orders
is
determ
ined at
the
trade
server.
Immediate or Cancel A ORDER_FILLING_IOC
trader
agrees
to
execut
e a
deal
with
the
volume
maxim
ally
availab
le in
the
market
within
that
indicat
ed in
the
order.

If the
reques
t
cannot
be
filled
comple
tely,
an
order
with
the
availab
le
volume

© 2000-2025, MetaQuotes Ltd.


894 Constants, Enumerations and Structures

Fill policy Descrip The value in ENUM _ORDER_T YPE_FILLING


tion

will be
execut
ed,
and
the
remain
ing
volume
will be
cancel
ed.

The
possibi
lity of
using
IOC
orders
is
determ
ined at
the
trade
server.

Passive (Book or Cancel) The ORDER_FILLING_BOC


BoC
order
assum
es that
the
order
can
only be
placed
in the
Depth
of
Market
and
cannot
be
immed
iately
execut
ed. If
the
order

© 2000-2025, MetaQuotes Ltd.


895 Constants, Enumerations and Structures

Fill policy Descrip The value in ENUM _ORDER_T YPE_FILLING


tion

can be
execut
ed
immed
iately
when
placed,
then it
is
cancel
ed.

In
fact,
the
BOC
policy
guaran
tees
that
the
price
of the
placed
order
will be
worse
than
the
current
market
. BoC
orders
are
used
to
imple
ment
passiv
e
trading
, so
that
the
order
is not
execut
ed

© 2000-2025, MetaQuotes Ltd.


896 Constants, Enumerations and Structures

Fill policy Descrip The value in ENUM _ORDER_T YPE_FILLING


tion

immed
iately
when
placed
and
does
not
affect
current
liquidit
y.

Only
limit
and
stop
limit
orders
are
suppor
ted
(ORDE
R_T YP
E_BUY
_LIMIT
,
ORDER
_T YPE
_SELL _
LIMIT,
ORDER
_T YPE
_BUY_
S TOP_
LIMIT,
ORDER
_T YPE
_SELL _
S TOP_
LIMIT)
.
R eturn In case ORDER_FILLING_RETURN
of
partial
filling,
an
order
with

© 2000-2025, MetaQuotes Ltd.


897 Constants, Enumerations and Structures

Fill policy Descrip The value in ENUM _ORDER_T YPE_FILLING


tion

remain
ing
volume
is not
cancel
ed but
proces
sed
further
.

R eturn
orders
are not
allowe
d in
the
Market
Execut
ion
mode
(marke
t
execut
ion —
SYM BO
L_TRA
DE_EX
ECUTI
ON_M A
RKET).

W hen sending a trade request using the OrderS end() function, the necessary volume execution policy
can be set in the type_filling field, namely in the special M qlTradeRequest structure. The values from
the ENUM _ORDER_TYPE_FILLING enumeration are available. To get the property value in a specific
active/completed order, use the OrderGetInteger() or HistoryOrderGetInteger() function with the
ORDER_TYPE_FILLING modifier.
Before sending an order with the current execution time, for the correct setting of the
ORDER_TYPE_FILLING value (volume execution type), you can use the S ymbolInfoInteger() function
with each financial instrument to get the SYM BOL_FILLING_MODE property value, which shows volume
execution types allowed for the symbol as a combination of flags. The ORDER_FILLING_RETURN filling
type is enabled at all times except for the " Market execution" mode
(SYM BOL_TRADE_EXECUTION_M ARKET).
The use of filling types depending on the execution mode can be shown as the following table:

© 2000-2025, MetaQuotes Ltd.


898 Constants, Enumerations and Structures

Type of Execution\Fill Policy Fill or Kill (FOK Immediate or Return (Return


ORDER_FILLIN Cancel (IOC ORDER_FILLING
G_FOK) ORDER_FILLING _RETURN)
_IOC)

Instant Execution + (regardless + (regardless of + (always)


of a symbol a symbol
(SYM BOL_TRADE_EXECUTION_INS TANT) setting) setting)
R equest Execution + (regardless + (regardless of + (always)
of a symbol a symbol
SYM BOL _T RADE_EXECUTION_REQUES T setting) setting)

Market Execution + (set in the + (set in the - (disabled


symbol symbol regardless of
SYM BOL _T RADE_EXECUTION_M ARKET settings) settings) the symbol
settings)
Exchange Execution + (set in the + (set in the + (always)
symbol symbol
SYM BOL _T RADE_EXECUTION_EXCHANGE settings) settings)
In case of pending orders, the ORDER_FILLING_RETURN filling type should be used regardless of an
execution type (SYM BOL_TRADE_EXEMODE), since such orders are not meant for execution at the time
of sending. W hen using pending orders, a trader agrees in advance that, when conditions for a deal on
this order are met, the broker will use the filling type supported by the exchange.

The order validity period can be set in the type_time field of the special structure M qlTradeRequest
when sending a trade request using the OrderS end() function. Values of the ENUM _ORDER_TYPE_TIM E
enumeration are allowed. To obtain the value of this property use the function OrderGetInteger() or
H istoryOrderGetInteger() with the ORDER_T YPE_TIM E modifier.

ENUM_ORDER_TY PE_TIME

Identifier Description

ORDER_TIM E_GTC Good till cancel order

ORDER_TIM E_DAY Good till current trade day order

ORDER_TIM E_S PECIFIED Good till expired order

ORDER_TIM E_S PECIFIED_DAY The order will be effective till 23:59:59 of the specified day.
If this time is outside a trading session, the order expires in
the nearest trading time.

The reason for order placing is contained in the ORDER_REAS ON property. An order can be placed by
an MQL5 program, from a mobile application, as a result of S topOut, etc. Possible values of
ORDER_REAS ON are described in the ENUM _ORDER_REAS ON enumeration.
ENUM_ORDER_REASON

© 2000-2025, MetaQuotes Ltd.


899 Constants, Enumerations and Structures

Identifier Description

ORDER_REAS ON_CLIENT The order was placed from a des ktop terminal
ORDER_REAS ON_MOBILE The order was placed from a mobile application
ORDER_REAS ON_WEB The order was placed from a web platform
ORDER_REAS ON_EXPERT The order was placed from an MQL5-program, i.e. by an
Expert Advisor or a script

ORDER_REAS ON_S L The order was placed as a result of S top Loss activation
ORDER_REAS ON_TP The order was placed as a result of Take Profit activation
ORDER_REAS ON_S O The order was placed as a result of the S top Out event

© 2000-2025, MetaQuotes Ltd.


900 Constants, Enumerations and Structures

Position Properties
Execution of trade operations results in the opening of a position, changing of its volume and/or
direction, or its disappearance. Trade operations are conducted based on orders, sent by the
OrderS end() function in the form of trade requests. For each financial security (symbol) only one open
position is possible. A position has a set of properties available for reading by the PositionGet...()
functions.
For the function PositionGetInteger()
ENUM_POSITION_PROPERTY _INTEGER

Identifier Description Type

POS ITION_TICKET Position ticket. long


Unique number
assigned to each
newly opened
position. It
usually matches
the ticket of an
order used to
open the position
except when the
ticket is changed
as a result of
service
operations on the
server, for
example, when
charging swaps
with position re-
opening. To find
an order used to
open a position,
apply the
POS ITION_IDENTI
FIER property.

POS ITION_TICKET
value corresponds
to
M qlTradeRequest:
:position.

POS ITION_TIM E Position open datetime


time
POS ITION_TIM E_M S C Position opening long
time in
milliseconds since
01.01.1970

© 2000-2025, MetaQuotes Ltd.


901 Constants, Enumerations and Structures

Identifier Description Type

POS ITION_TIM E_UPDATE Position changing datetime


time
POS ITION_TIM E_UPDATE_M S C Position changing long
time in
milliseconds since
01.01.1970

POS ITION_TYPE Position type ENUM _POS ITION_T YPE

POS ITION_M AGIC Position magic long


number (see
ORDER_M AGIC)
POS ITION_IDENTIFIER Position identifier long
is a unique
number assigned
to each re-opened
position. It does
not change
throughout its life
cycle and
corresponds to
the ticket of an
order used to
open a position.

Position identifier
is specified in
each order
(ORDER_POS ITIO
N_ID) and deal
(DEAL_POS ITION_
ID) used to open,
modify, or close
it. Use this
property to
search for orders
and deals related
to the position.

W hen reversing a
position in
netting mode
(using a single
in/out trade),
POS ITION_IDENTI
FIER does not
change. However,
POS ITION_TICKET
is replaced with

© 2000-2025, MetaQuotes Ltd.


902 Constants, Enumerations and Structures

Identifier Description Type

the ticket of the


order that led to
the reversal.
Position reversal
is not provided in
hedging mode.
POS ITION_REAS ON The reason for ENUM _POS ITION_REAS ON
opening a
position
For the function PositionGetDouble()
ENUM_POSITION_PROPERTY _DOUBLE

Identifier Description Type

POS ITION_VOLUM E Position volume double


POS ITION_PRICE_OPEN Position open double
price
POS ITION_S L S top
Loss level of double
opened position
POS ITION_TP Take Profit level double
of opened
position
POS ITION_PRICE_CURRENT Current price of double
the position
symbol
POS ITION_SWAP Cumulative swap double
POS ITION_PROFIT Current profit double
For the function PositionGetS tring()
ENUM_POSITION_PROPERTY _STRING

Identifier Description Type

POS ITION_SYM BOL S ymbol of the string


position
POS ITION_COMM ENT Position comment string
POS ITION_EXTERNAL_ID Position identifier string
in an external
trading system
(on the Exchange)

© 2000-2025, MetaQuotes Ltd.


903 Constants, Enumerations and Structures

Direction of an open position (buy or sell) is defined by the value from the ENUM _POS ITION_TYPE
enumeration. In order to obtain the type of an open position use the PositionGetInteger() function
with the POS ITION_TYPE modifier.
ENUM_POSITION_TY PE

Identifier Description

POS ITION_TYPE_BUY Buy

POS ITION_TYPE_SELL S ell

The reason for opening a position is contained in the POS ITION_REAS ON property. A position can be
opened as a result of activation of an order placed from a des ktop terminal, a mobile application, by
an Expert Advisor, etc. Possible values of POS ITION_REAS ON are described in the
ENUM _POS ITION_REAS ON enumeration.

ENUM_POSITION_REASON

Identifier Description

POS ITION_REAS ON_CLIENT The position was opened as a result of activation of an order
placed from a des ktop terminal
POS ITION_REAS ON_MOBILE The position was opened as a result of activation of an order
placed from a mobile application
POS ITION_REAS ON_WEB The position was opened as a result of activation of an order
placed from the web platform
POS ITION_REAS ON_EXPERT The position was opened as a result of activation of an order
placed from an MQL5 program, i.e. an Expert Advisor or a
script

© 2000-2025, MetaQuotes Ltd.


904 Constants, Enumerations and Structures

Deal Properties
A deal is the reflection of the fact of a trade operation execution based on an order that contains a
trade request. Each trade is described by properties that allow to obtain information about it. In order
to read values of properties, functions of the HistoryDealGet...() type are used, that return values
from corresponding enumerations.
For the function HistoryDealGetInteger()
ENUM_DEAL_PROPERTY _INTEGER

Identifier Description Type

DEAL _TICKET Deal ticket. Unique number assigned to long


each deal
DEAL _ORDER Deal order number long
DEAL _TIM E Deal time datetime
DEAL _TIM E_M S C The time of a deal execution in long
milliseconds since 01.01.1970
DEAL _T YPE Deal type ENUM _DEAL _T YPE

DEAL _ENT RY Deal entry - entry in, entry out, reverse ENUM _DEAL _ENT RY

DEAL _M AGIC Deal magic number (see ORDER_M AGIC) long


DEAL _REAS ON The reason or source for deal execution ENUM _DEAL _REAS ON

DEAL _POS ITION_ID Identifier of a position, in the opening, long


modification or closing of which this deal
took part. Each position has a unique
identifier that is assigned to all deals
executed for the symbol during the entire
lifetime of the position.
For the function HistoryDealGetDouble()
ENUM_DEAL_PROPERTY _DOUBLE

Identifier Description Type

DEAL _VOL UM E Deal volume double


DEAL _PR ICE Deal price double
DEAL _COMMISS ION Deal commission double
DEAL _SWAP Cumulative swap on close double
DEAL _PR OFIT Deal profit double
DEAL _FEE Fee formaking a deal charged double
immediately after performing
a deal

© 2000-2025, MetaQuotes Ltd.


905 Constants, Enumerations and Structures

Identifier Description Type

DEAL _S L S top Loss level double


· Entry and reversal deals use
the S top Loss values from
the original order based on
which the position was
opened or reversed
· Exit deals use the S top Loss
of a position as at the time
of position closing
DEAL _TP Take Profit level double
· Entry and reversal deals use
the Take Profit values from
the original order based on
which the position was
opened or reversed
· Exit deals use the Tak e
Profit value of a position as
at the time of position
closing
For the function HistoryDealGetS tring()
ENUM_DEAL_PROPERTY _STRING

Identifier Description Type

DEAL _SYM BOL Deal symbol string


DEAL _COMM ENT Deal comment string
DEAL _EXT ERNAL _ID Deal identifier in an external string
trading system (on the
Exchange)

Each deal ischaracterized by a type, allowed values are enumerated in ENUM _DEAL_TYPE. In order to
obtain information about the deal type, use the HistoryDealGetInteger() function with the DEAL_TYPE
modifier.
ENUM_DEAL_TY PE

Identifier Description

DEAL _T YPE_BUY Buy

DEAL _T YPE_SELL S ell

DEAL _T YPE_BAL ANCE Balance

DEAL _T YPE_CREDIT Credit

© 2000-2025, MetaQuotes Ltd.


906 Constants, Enumerations and Structures

Identifier Description

DEAL _T YPE_CHARGE Additional charge

DEAL _T YPE_CORRECTION Correction


DEAL _T YPE_BONUS Bonus

DEAL _T YPE_COMMISS ION Additional commission

DEAL _T YPE_COMMISS ION_DAI Daily commission


LY
DEAL _T YPE_COMMISS ION_MO Monthly commission
NT H L Y

DEAL _T YPE_COMMISS ION_AG Daily agent commission


ENT _DAIL Y

DEAL _T YPE_COMMISS ION_AG Monthly agent commission


ENT _MONT H L Y

DEAL _T YPE_INT ERES T Interest rate


DEAL _T YPE_BUY_CANCEL ED Canceled buy deal. There can be a situation when a previously
executed buy deal is canceled. In this case, the type of the
previously executed deal (DEA L_TYPE_BUY) is changed to
DEAL _T YPE_BUY_CANCEL ED, and its profit/loss is zeroized.
Previously obtained profit/loss is charged/withdrawn using a
separated balance operation

DEAL _T YPE_SELL _CANCEL ED Canceled sell deal. There can be a situation when a previously
executed sell deal is canceled. In this case, the type of the
previously executed deal (DEA L _T YPE_SELL) is changed to
DEAL _T YPE_SELL _CANCEL ED, and its profit/loss is zeroized.
Previously obtained profit/loss is charged/withdrawn using a
separated balance operation

DEAL _DIVIDEND Dividend operations

DEAL _DIVIDEND_FRANKED Frank ed (non-taxable) dividend operations


DEAL _T AX Tax charges

Deals differ not only in their types set in ENUM _DEAL_TYPE, but also in the way they change positions.
This can be a simple position opening, or accumulation of a previously opened position (market
entering), position closing by an opposite deal of a corresponding volume (market exiting), or position
reversing, if the opposite-direction deal covers the volume of the previously opened position.
Allthese situations are described by values from the ENUM _DEAL_ENTRY enumeration. In order to
receive this information about a deal, use the HistoryDealGetInteger() function with the DEAL_ENTRY
modifier.
ENUM_DEAL_ENTRY

© 2000-2025, MetaQuotes Ltd.


907 Constants, Enumerations and Structures

Identifier Description

DEAL _ENT RY_IN Entry in

DEAL _ENT RY_OUT Entry out

DEAL _ENT RY_INOUT R everse

DEAL _ENT RY_OUT _BY Close a position by an opposite one

The reason for deal execution is contained in the DEAL_REAS ON property. A deal can be executed as a
result of triggering of an order placed from a mobile application or an MQL5 program, as well as as a
result of the S topOut event, variation margin calculation, etc. Possible values of DEAL_REAS ON are
described in the ENUM _DEAL_REAS ON enumeration. For non-trading deals resulting from balance,
credit, commission and other operations, DEAL_REAS ON_CLIENT is indicated as the reason.
ENUM_DEAL_REASON

Identifier Description

DEAL _REAS ON_CLIENT The deal was executed as a result of activation of an order placed from a
des ktop terminal
DEAL _REAS ON_MOBIL E The deal was executed as a result of activation of an order placed from a
mobile application
DEAL _REAS ON_WEB The deal was executed as a result of activation of an order placed from
the web platform
DEAL _REAS ON_EXPER T The deal was executed as a result of activation of an order placed from
an MQL5 program, i.e. an Expert Advisor or a script
DEAL _REAS ON_S L The deal was executed as a result of S top Loss activation
DEAL _REAS ON_TP The deal was executed as a result of Take Profit activation
DEAL _REAS ON_S O The deal was executed as a result of the S top Out event
DEAL _REAS ON_R OLLOV The deal was executed due to a rollover
ER

DEAL _REAS ON_VM ARGI The deal was executed after charging the variation margin
N

DEAL _REAS ON_S PLIT The deal was executed after the split (price reduction) of an instrument,
which had an open position during split announcement
DEAL _REAS ON_COR POR The deal was executed as a result of a corporate action: merging or
AT E_ACTION renaming a security, transferring a client to another account, etc.

© 2000-2025, MetaQuotes Ltd.


908 Constants, Enumerations and Structures

Trade Operation Types


Trading is done by sending orders to open positions using the OrderS end() function, as well as to
place, modify or delete pending orders. Each trade order refers to the type of the requested operation.
Trading operations are described in the ENUM _TRADE_REQUES T_ACTIONS enumeration.
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 for the execution under specified conditions
(pending order)
TRADE_ACTION_S LTP Modify S top Loss and Take Profit values of an opened position
TRADE_ACTION_MODIFY Modify the parameters of the order placed previously
TRADE_ACTION_REMOVE Delete the pending order placed previously
TRADE_ACTION_CLOSE_BY Close a position by an opposite one

Example of the TRADE_ACTION_DEAL trade operation for opening a Buy position:


#define EXPERT_MAGIC 123456 // MagicNumber of the expert
//+------------------------------------------------------------------+
//| Opening Buy position |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
//--- parameters of request
request.action =TRADE_ACTION_DEAL; // type of trade operation
request.symbol =Symbol(); // symbol
request.volume =0.1; // volume of 0.1 lot
request.type =ORDER_TYPE_BUY; // order type
request.price =SymbolInfoDouble(Symbol(),SYMBOL_ASK); // price for opening
request.deviation=5; // allowed deviation from the price
request.magic =EXPERT_MAGIC; // MagicNumber of the order
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, outpu
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
}
//+------------------------------------------------------------------+

Example of the TRADE_ACTION_DEAL trade operation for opening a S ell position:

© 2000-2025, MetaQuotes Ltd.


909 Constants, Enumerations and Structures

#define EXPERT_MAGIC 123456 // MagicNumber of the expert


//+------------------------------------------------------------------+
//| Opening Sell position |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
//--- parameters of request
request.action =TRADE_ACTION_DEAL; // type of trade operation
request.symbol =Symbol(); // symbol
request.volume =0.2; // volume of 0.2 lot
request.type =ORDER_TYPE_SELL; // order type
request.price =SymbolInfoDouble(Symbol(),SYMBOL_BID); // price for opening
request.deviation=5; // allowed deviation from the price
request.magic =EXPERT_MAGIC; // MagicNumber of the order
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, outpu
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
}
//+------------------------------------------------------------------+

Example of the TRADE_ACTION_DEAL trade operation for closing positions :

© 2000-2025, MetaQuotes Ltd.


910 Constants, Enumerations and Structures

#define EXPERT_MAGIC 123456 // MagicNumber of the expert


//+------------------------------------------------------------------+
//| Closing all positions |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request;
MqlTradeResult result;
int total=PositionsTotal(); // number of open positions
//--- iterate over all open positions
for(int i=total-1; i>=0; i--)
{
//--- parameters of the order
ulong position_ticket=PositionGetTicket(i); // ticket o
string position_symbol=PositionGetString(POSITION_SYMBOL); // symbol
int digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS); // number o
ulong magic=PositionGetInteger(POSITION_MAGIC); // MagicNum
double volume=PositionGetDouble(POSITION_VOLUME); // volume o
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); // type of
//--- output information about the position
PrintFormat("#%I64u %s %s %.2f %s [%I64d]",
position_ticket,
position_symbol,
EnumToString(type),
volume,
DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
magic);
//--- if the MagicNumber matches
if(magic==EXPERT_MAGIC)
{
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
//--- setting the operation parameters
request.action =TRADE_ACTION_DEAL; // type of trade operation
request.position =position_ticket; // ticket of the position
request.symbol =position_symbol; // symbol
request.volume =volume; // volume of the position
request.deviation=5; // allowed deviation from the price
request.magic =EXPERT_MAGIC; // MagicNumber of the position
//--- set the price and order type depending on the position type
if(type==POSITION_TYPE_BUY)
{
request.price=SymbolInfoDouble(position_symbol,SYMBOL_BID);
request.type =ORDER_TYPE_SELL;
}
else
{
request.price=SymbolInfoDouble(position_symbol,SYMBOL_ASK);
request.type =ORDER_TYPE_BUY;
}
//--- output information about the closure
PrintFormat("Close #%I64d %s %s",position_ticket,position_symbol,EnumToString(type));
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, ou
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order)
//---
}

© 2000-2025, MetaQuotes Ltd.


911 Constants, Enumerations and Structures

}
}
//+------------------------------------------------------------------+

Example of the TRADE_ACTION_PENDING trade operation for placing a pending order:

© 2000-2025, MetaQuotes Ltd.


912 Constants, Enumerations and Structures

#property description "Example of placing pending orders"


#property script_show_inputs
#define EXPERT_MAGIC 123456 // MagicNumber of the expert
input ENUM_ORDER_TYPE orderType=ORDER_TYPE_BUY_LIMIT; // order type
//+------------------------------------------------------------------+
//| Placing pending orders |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
//--- parameters to place a pending order
request.action =TRADE_ACTION_PENDING; // type of trade operation
request.symbol =Symbol(); // symbol
request.volume =0.1; // volume of 0.1 lot
request.deviation=2; // allowed deviation from th
request.magic =EXPERT_MAGIC; // MagicNumber of the order
int offset = 50; // offset from the current p
double price; // order triggering price
double point=SymbolInfoDouble(_Symbol,SYMBOL_POINT); // value of point
int digits=SymbolInfoInteger(_Symbol,SYMBOL_DIGITS); // number of decimal places
//--- checking the type of operation
if(orderType==ORDER_TYPE_BUY_LIMIT)
{
request.type =ORDER_TYPE_BUY_LIMIT; // order type
price=SymbolInfoDouble(Symbol(),SYMBOL_ASK)-offset*point; // price for opening
request.price =NormalizeDouble(price,digits); // normalized opening price
}
else if(orderType==ORDER_TYPE_SELL_LIMIT)
{
request.type =ORDER_TYPE_SELL_LIMIT; // order type
price=SymbolInfoDouble(Symbol(),SYMBOL_ASK)+offset*point; // price for opening
request.price =NormalizeDouble(price,digits); // normalized opening price
}
else if(orderType==ORDER_TYPE_BUY_STOP)
{
request.type =ORDER_TYPE_BUY_STOP; // order type
price =SymbolInfoDouble(Symbol(),SYMBOL_ASK)+offset*point; // price for opening
request.price=NormalizeDouble(price,digits); // normalized opening price
}
else if(orderType==ORDER_TYPE_SELL_STOP)
{
request.type =ORDER_TYPE_SELL_STOP; // order type
price=SymbolInfoDouble(Symbol(),SYMBOL_ASK)-offset*point; // price for opening
request.price =NormalizeDouble(price,digits); // normalized opening price
}
else Alert("This example is only for placing pending orders"); // if not pending order is sele
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the re
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
}
//+------------------------------------------------------------------+

Example of the TRADE_ACTION_S LTP trade operation for modifying the S top Loss and Take Profit
values of an open position:

© 2000-2025, MetaQuotes Ltd.


913 Constants, Enumerations and Structures

#define EXPERT_MAGIC 123456 // MagicNumber of the expert


//+------------------------------------------------------------------+
//| Modification of Stop Loss and Take Profit of position |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request;
MqlTradeResult result;
int total=PositionsTotal(); // number of open positions
//--- iterate over all open positions
for(int i=0; i<total; i++)
{
//--- parameters of the order
ulong position_ticket=PositionGetTicket(i);// ticket of the position
string position_symbol=PositionGetString(POSITION_SYMBOL); // symbol
int digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS); // number of decimal pla
ulong magic=PositionGetInteger(POSITION_MAGIC); // MagicNumber of the position
double volume=PositionGetDouble(POSITION_VOLUME); // volume of the position
double sl=PositionGetDouble(POSITION_SL); // Stop Loss of the position
double tp=PositionGetDouble(POSITION_TP); // Take Profit of the position
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); // type of th
//--- output information about the position
PrintFormat("#%I64u %s %s %.2f %s sl: %s tp: %s [%I64d]",
position_ticket,
position_symbol,
EnumToString(type),
volume,
DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
DoubleToString(sl,digits),
DoubleToString(tp,digits),
magic);
//--- if the MagicNumber matches, Stop Loss and Take Profit are not defined
if(magic==EXPERT_MAGIC && sl==0 && tp==0)
{

© 2000-2025, MetaQuotes Ltd.


914 Constants, Enumerations and Structures

//--- calculate the current price levels


double price=PositionGetDouble(POSITION_PRICE_OPEN);
double bid=SymbolInfoDouble(position_symbol,SYMBOL_BID);
double ask=SymbolInfoDouble(position_symbol,SYMBOL_ASK);
int stop_level=(int)SymbolInfoInteger(position_symbol,SYMBOL_TRADE_STOPS_LEVEL);
double price_level;
//--- if the minimum allowed offset distance in points from the current close price is not
if(stop_level<=0)
stop_level=150; // set the offset distance of 150 points from the current close price
else
stop_level+=50; // set the offset distance to (SYMBOL_TRADE_STOPS_LEVEL + 50) points fo

//--- calculation and rounding of the Stop Loss and Take Profit values
price_level=stop_level*SymbolInfoDouble(position_symbol,SYMBOL_POINT);
if(type==POSITION_TYPE_BUY)
{
sl=NormalizeDouble(bid-price_level,digits);
tp=NormalizeDouble(ask+price_level,digits);
}
else
{
sl=NormalizeDouble(ask+price_level,digits);
tp=NormalizeDouble(bid-price_level,digits);
}
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
//--- setting the operation parameters
request.action =TRADE_ACTION_SLTP; // type of trade operation
request.position=position_ticket; // ticket of the position
request.symbol=position_symbol; // symbol
request.sl =sl; // Stop Loss of the position
request.tp =tp; // Take Profit of the position
request.magic=EXPERT_MAGIC; // MagicNumber of the position
//--- output information about the modification
PrintFormat("Modify #%I64d %s %s",position_ticket,position_symbol,EnumToString(type));
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, ou
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order)
}
}
}
//+------------------------------------------------------------------+

Example of the TRADE_ACTION_MODIFY trade operation for modifying the price levels of pending
orders :

© 2000-2025, MetaQuotes Ltd.


915 Constants, Enumerations and Structures

#define EXPERT_MAGIC 123456 // MagicNumber of the expert


//+------------------------------------------------------------------+
//| Modification of pending orders |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
int total=OrdersTotal(); // total number of placed pending orders
//--- iterate over all placed pending orders
for(int i=0; i<total; i++)
{
//--- parameters of the order
ulong order_ticket=OrderGetTicket(i); // order ticket
string order_symbol=Symbol(); // symbol
int digits=(int)SymbolInfoInteger(order_symbol,SYMBOL_DIGITS); // number of decimal place
ulong magic=OrderGetInteger(ORDER_MAGIC); // MagicNumber of the orde
double volume=OrderGetDouble(ORDER_VOLUME_CURRENT); // current volume of the o
double sl=OrderGetDouble(ORDER_SL); // current Stop Loss of th
double tp=OrderGetDouble(ORDER_TP); // current Take Profit of
ENUM_ORDER_TYPE type=(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); // type of the order
int offset = 50; // offset from the current
double price; // order triggering price
double point=SymbolInfoDouble(order_symbol,SYMBOL_POINT); // value of point
//--- output information about the order
PrintFormat("#%I64u %s %s %.2f %s sl: %s tp: %s [%I64d]",
order_ticket,
order_symbol,
EnumToString(type),
volume,
DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
DoubleToString(sl,digits),
DoubleToString(tp,digits),
magic);
//--- if the MagicNumber matches, Stop Loss and Take Profit are not defined
if(magic==EXPERT_MAGIC && sl==0 && tp==0)
{
request.action=TRADE_ACTION_MODIFY; // type of trade operation
request.order = OrderGetTicket(i); // order ticket
request.symbol =Symbol(); // symbol
request.deviation=5; // allowed deviation from th
//--- setting the price level, Take Profit and Stop Loss of the order depending on its type
if(type==ORDER_TYPE_BUY_LIMIT)
{
price = SymbolInfoDouble(Symbol(),SYMBOL_ASK)-offset*point;
request.tp = NormalizeDouble(price+offset*point,digits);
request.sl = NormalizeDouble(price-offset*point,digits);
request.price =NormalizeDouble(price,digits); // normalized opening p
}
else if(type==ORDER_TYPE_SELL_LIMIT)
{
price = SymbolInfoDouble(Symbol(),SYMBOL_BID)+offset*point;
request.tp = NormalizeDouble(price-offset*point,digits);
request.sl = NormalizeDouble(price+offset*point,digits);
request.price =NormalizeDouble(price,digits); // normalized opening
}
else if(type==ORDER_TYPE_BUY_STOP)
{
price = SymbolInfoDouble(Symbol(),SYMBOL_BID)+offset*point;
request.tp = NormalizeDouble(price+offset*point,digits);

© 2000-2025, MetaQuotes Ltd.


916 Constants, Enumerations and Structures

request.sl = NormalizeDouble(price-offset*point,digits);
request.price =NormalizeDouble(price,digits); // normalized opening
}
else if(type==ORDER_TYPE_SELL_STOP)
{
price = SymbolInfoDouble(Symbol(),SYMBOL_ASK)-offset*point;
request.tp = NormalizeDouble(price-offset*point,digits);
request.sl = NormalizeDouble(price+offset*point,digits);
request.price =NormalizeDouble(price,digits); // normalized opening
}
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, ou
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order)
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
}
}
}
//+------------------------------------------------------------------+

Example of the TRADE_ACTION_REMOVE trade operation for deleting pending orders :


#define EXPERT_MAGIC 123456 // MagicNumber of the expert
//+------------------------------------------------------------------+
//| Deleting pending orders |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
int total=OrdersTotal(); // total number of placed pending orders
//--- iterate over all placed pending orders
for(int i=total-1; i>=0; i--)
{
ulong order_ticket=OrderGetTicket(i); // order ticket
ulong magic=OrderGetInteger(ORDER_MAGIC); // MagicNumber of the order
//--- if the MagicNumber matches
if(magic==EXPERT_MAGIC)
{
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
//--- setting the operation parameters
request.action=TRADE_ACTION_REMOVE; // type of trade operation
request.order = order_ticket; // order ticket
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, ou
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order)
}
}
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


917 Constants, Enumerations and Structures

Example of the TRADE_ACTION_CLOSE_BY trade operation for closing positions by opposite positions :

© 2000-2025, MetaQuotes Ltd.


918 Constants, Enumerations and Structures

#define EXPERT_MAGIC 123456 // MagicNumber of the expert


//+------------------------------------------------------------------+
//| Close all positions by opposite positions |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request;
MqlTradeResult result;
int total=PositionsTotal(); // number of open positions
//--- iterate over all open positions
for(int i=total-1; i>=0; i--)
{
//--- parameters of the order
ulong position_ticket=PositionGetTicket(i); // ticket of
string position_symbol=PositionGetString(POSITION_SYMBOL); // symbol
int digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS); // ticket of
ulong magic=PositionGetInteger(POSITION_MAGIC); // MagicNumbe
double volume=PositionGetDouble(POSITION_VOLUME); // volume of
double sl=PositionGetDouble(POSITION_SL); // Stop Loss
double tp=PositionGetDouble(POSITION_TP); // Take Profi
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); // type of th
//--- output information about the position
PrintFormat("#%I64u %s %s %.2f %s sl: %s tp: %s [%I64d]",
position_ticket,
position_symbol,
EnumToString(type),
volume,
DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
DoubleToString(sl,digits),
DoubleToString(tp,digits),
magic);
//--- if the MagicNumber matches
if(magic==EXPERT_MAGIC)
{
for(int j=0; j<i; j++)
{
string symbol=PositionGetSymbol(j); // symbol of the opposite position
//--- if the symbols of the opposite and initial positions match
if(symbol==position_symbol && PositionGetInteger(POSITION_MAGIC)==EXPERT_MAGIC)
{
//--- set the type of the opposite position
ENUM_POSITION_TYPE type_by=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
//--- leave, if the types of the initial and opposite positions match
if(type==type_by)
continue;
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
//--- setting the operation parameters
request.action=TRADE_ACTION_CLOSE_BY; // type of trade opera
request.position=position_ticket; // ticket of the posit
request.position_by=PositionGetInteger(POSITION_TICKET); // ticket of the oppos
//request.symbol =position_symbol;
request.magic=EXPERT_MAGIC; // MagicNumber of the
//--- output information about the closure by opposite position
PrintFormat("Close #%I64d %s %s by #%I64d",position_ticket,position_symbol,EnumToStr
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the reques

© 2000-2025, MetaQuotes Ltd.


919 Constants, Enumerations and Structures

//--- information about the operation


PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.
}
}
}
}
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


920 Constants, Enumerations and Structures

Trade Transaction Types


W hen performing some definite actions on a trade account, its state changes. S uch actions include:
· S ending a trade request from any MQL5 application in the client terminal using OrderS end and
OrderS endAsync functions and its further execution;
· S ending a trade request via the terminal graphical interface and its further execution;
· Pending orders and stop orders activation on the server;
· Performing operations on a trade server side.
The following trade transactions are performed as a result of these actions :
· handling a trade request;
· changing open orders ;
· changing orders history;
· changing deals history;
· changing positions.
For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions.
To let a programmer to track the actions performed in relation to a trade account,
OnTradeTransaction function has been provided. This handler allows to get trade transactions applied
to an account in MQL5 application. Trade transaction description is submitted in OnTradeTransaction
first parameter using M qlTradeTransaction structure.
Trade transaction type is submitted in the type parameter of M qlTradeTransaction structure. Possible
types of trade transactions are described by the following enumeration:
ENUM_TRADE_TRANSACTION_TY PE

Identifier Description

TRADE_TRANSACTION_ORDER_ADD Adding a new open order.


TRADE_TRANSACTION_ORDER_UPDATE Updating an open order. The updates include not only
evident changes from the client terminal or a trade
server sides but also changes of an order state when
setting it (for example, transition from
ORDER_S TATE_S TARTED to ORDER_S TATE_PLACED or
from ORDER_S TATE_PLACED to
ORDER_S TATE_PARTIAL, etc.).
TRADE_TRANSACTION_ORDER_DELETE R emoving an order from the list of the open ones. An
order can be deleted from the open ones as a result of
setting an appropriate request or execution (filling)
and moving to the history.
TRADE_TRANSACTION_DEAL_ADD Addinga deal to the history. The action is performed
as a result of an order execution or performing

© 2000-2025, MetaQuotes Ltd.


921 Constants, Enumerations and Structures

Identifier Description

operations with an account balance.


TRADE_TRANSACTION_DEAL_UPDATE Updating a deal in the history. There may be cases
when a previously executed deal is changed on a
server. For example, a deal has been changed in an
external trading system (exchange) where it was
previously transferred by a broker.
TRADE_TRANSACTION_DEAL_DELETE Deleting a deal from the history. There may be cases
when a previously executed deal is deleted from a
server. For example, a deal has been deleted in an
external trading system (exchange) where it was
previously transferred by a broker.
TRADE_TRANSACTION_HIS TORY_ADD Adding an order to the history as a result of execution
or cancellation.
TRADE_TRANSACTION_HIS TORY_UPDATE Changing an order located in the orders history. This
type is provided for enhancing functionality on a trade
server side.
TRADE_TRANSACTION_HIS TORY_DELETE Deletingan order from the orders history. This type is
provided for enhancing functionality on a trade server
side.
TRADE_TRANSACTION_POS ITION Changing a position not related to a deal execution.
This type of transaction shows that a position has
been changed on a trade server side. Position volume,
open price, S top Loss and Take Profit levels can be
changed. Data on changes are submitted in
M qlTradeTransaction structure via
OnTradeTransaction handler. Position change (adding,
changing or closing), as a result of a deal execution,
does not lead to the occurrence of
TRADE_TRANSACTION_POS ITION transaction.
TRADE_TRANSACTION_REQUES T Notification of the fact that a trade request has been
processed by a server and processing result has been
received. Only type field (trade transaction type) must
be analyzed for such transactions in
M qlTradeTransaction structure. The second and third
parameters of OnTradeTransaction (request and
result) must be analyzed for additional data.
Depending on a trade transaction type, various parameters are filled in M qlTradeTransaction structure
describing it. A detailed description of submitted data is shown in "S tructure of a Trade Transaction" .
See also

S tructure of a Trade Transaction, OnTradeTransaction

© 2000-2025, MetaQuotes Ltd.


922 Constants, Enumerations and Structures

Trade Orders in Depth Of Market


For equity securities, the Depth of Mark et window is available, where you can see the current Buy and
S ell orders. Desired direction of a trade operation, required amount and requested price are specified
for each order.
To obtain information about the current state of the DOM by MQL5 means, the MarketBookGet()
function is used, which places the DOM " screen shot" into the M qlBookInfo array of structures. Each
element of the array in the type field contains information about the direction of the order - the value
of the ENUM _BOOK_TYPE enumeration.
ENUM_BOOK_TY PE

Identifier Description

BOOK_T YPE_SELL S ell order (Offer)


BOOK_T YPE_BUY Buy order (Bid)

BOOK_T YPE_SELL _M ARKET S ell order by Market


BOOK_T YPE_BUY_M ARKET Buy order by Market

See also

S tructures and classes, S tructure of the DOM, Trade operation types, Market Info

© 2000-2025, MetaQuotes Ltd.


923 Constants, Enumerations and Structures

Signal Properties
The following enumerations are used when working with trading signals and signal copy settings.
Enumeration of double type properties of the trading signal:
ENUM_SIGNAL_BASE_DOUBLE

ID Description

S IGNAL _BASE_BAL ANCE Account balance

S IGNAL _BASE_EQUIT Y Account equity

S IGNAL _BASE_GAIN Account gain

S IGNAL _BASE_M AX_DRAWDOWN Account maximum drawdown


S IGNAL _BASE_PR ICE S ignal subscription price

S IGNAL _BASE_R OI R eturn on Investment (%)

Enumeration of integer type properties of the trading signal:


ENUM_SIGNAL_BASE_INTEGER

ID Description

S IGNAL _BASE_DAT E_PUBLISHED Publication date (date when it become available


for subscription)
S IGNAL _BASE_DAT E_S T AR T ED Monitoring starting date
S IGNAL _BASE_DAT E_UPDAT ED The date of the last update of the signal's
trading statistics
S IGNAL _BASE_ID S ignal ID

S IGNAL _BASE_L EVERAGE Account leverage

S IGNAL _BASE_PIPS Profit in pips


S IGNAL _BASE_RATING Position in rating
S IGNAL _BASE_SUBS CR IBERS Number of subscribers
S IGNAL _BASE_T RADES Number of trades
S IGNAL _BASE_T RADE_MODE Account type (0-real, 1-demo, 2-contest)

Enumeration of string type properties of the trading signal:


ENUM_SIGNAL_BASE_STRING

ID Description

S IGNAL _BASE_AUT H OR_LOGIN Author login


S IGNAL _BASE_BR OKER Brok er name (company)

© 2000-2025, MetaQuotes Ltd.


924 Constants, Enumerations and Structures

ID Description

S IGNAL _BASE_BR OKER_SERVER Brok er server


S IGNAL _BASE_NAM E S ignal name

S IGNAL _BASE_CURRENCY S ignal base currency

Enumeration of double type properties of the signal copy settings :


ENUM_SIGNAL_INFO_DOUBLE

ID Description

S IGNAL _INFO_EQUIT Y_LIMIT Equity limit

S IGNAL _INFO_S LIPPAGE S lippage(used when placing market orders in


synchronization of positions and copying of
trades)
S IGNAL _INFO_VOL UM E_PER CENT Maximum percent of deposit used (%), r/o
Enumeration of integer type properties of the signal copy settings :
ENUM_SIGNAL_INFO_INTEGER

ID Description

S IGNAL _INFO_CONFIR M ATIONS_DISABL ED The flag enables synchronization without


confirmation dialog
S IGNAL _INFO_COPY_S LTP Copy S top Loss and Take Profit flag
S IGNAL _INFO_DEPOS IT _PER CENT Deposit percent (%)

S IGNAL _INFO_ID S ignal id, r/o

S IGNAL _INFO_SUBS CR IPTION_ENABL ED " Copy trades by subscription" permission flag


S IGNAL _INFO_T ER M S_AGREE "Agree to terms of use of S ignals service" flag,
r/o
Enumeration of string type properties of the signal copy settings :
ENUM_SIGNAL_INFO_STRING

ID Description

S IGNAL _INFO_NAM E S ignal name, r/o

See also
Trade signals

© 2000-2025, MetaQuotes Ltd.


925 Constants, Enumerations and Structures

Named Constants
All constants used in MQL5 can be divided into the following groups :
· Predefined macro substitutions – values are substituted during compilation;
· Mathematical constants – values of some mathematical expressions ;
· Numerical type constants – some of the simple type restrictions ;
· Uninitialization reason codes – description of uninitialization reasons ;
· Checking Object Pointer – enumeration of types of pointers returned by the CheckPointer() function;
· Other constants – all other constants.

© 2000-2025, MetaQuotes Ltd.


926 Constants, Enumerations and Structures

Predefined Macro Substitutions


To simplify the debugging process and obtain information about operation of a mql5-program, there
are special macro constant, values of which are set at the moment of compilation. The easiest way to
use these constants is outputting values by the Print() function, as it's shown in the example.
Constant Description

__CPU_AR CH IT ECT URE__ Name of architecture (set of commands) EX5 file compiled
for
__DAT E__ Filecompilation date without time (hours, minutes and
seconds are equal to 0)
__DAT ETIM E__ File compilation date and time

__LINE__ Line number in the source code, in which the macro is


located
__FIL E__ Name of the currently compiled file
__PAT H__ An absolute path to the file that is currently being compiled
__FUNCTION__ Name of the function, in whose body the macro is located
__FUNCS IG__ S ignature of the function in whose body the macro is
located. Logging of the full description of functions can be
useful in the identification of overloaded functions
__MQL BUIL D__,__MQL5BUIL D__ Compiler build number
__COUNT ER__ The compiler for each encountered __COUNTER__
declaration substitutes the counter value from 0 to N-1
where N is a number of uses in the code. The
__COUNT ER__ order is guaranteed when recompiling the
source code with no changes.
The __COUNTER__ value is calculated the following way:
· the initial counter value is 0,

· after each counter usage, its value is increased by 1,

· first, the compiler expands all macros and templates


into source code on-site,
· a separate code is created for each template
function specialization,
· a separate code is created for each template
class /structure specialization,
· next, the compiler passes through the obtained
source code in the defined order and replaces each
detected __COUNTER__ usage with the current
counter value.
The example below shows how the compiler handles the
source code and replaces all instances of __COUNTER__ it
meets with sequentially increasing values.

© 2000-2025, MetaQuotes Ltd.


927 Constants, Enumerations and Structures

Constant Description

__RANDOM __ The compiler inserts a random ulong value for each


__RANDOM __ declaration.

Example:

#property copyright "Copyright © 2009, MetaQuotes Software Corp."


#property link "https://www.metaquotes.net"
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- an example of information output at Expert Advisor 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 Advisor deinitialization
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__);
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- information output at tick receipt
Print(" __MQLBUILD__ = ",__MQLBUILD__," __FILE__ = ",__FILE__);
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__);
test1(__FUNCTION__);
test2();
//---
}
//+------------------------------------------------------------------+
//| test1 |
//+------------------------------------------------------------------+
void test1(string par)
{
//--- information output inside the function
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__," par=",par);
}

© 2000-2025, MetaQuotes Ltd.


928 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
//| test2 |
//+------------------------------------------------------------------+
void test2()
{
//--- information output inside the function
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__);
}
//+------------------------------------------------------------------+
//| OnTimer event handler |
//+------------------------------------------------------------------+
void OnTimer()
{
//---
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__);
test1(__FUNCTION__);
}

The example for learning how to work with the __COUNTER__ macro
//--- create a macro for a quick display of the expression and its value in the journal
#define print(expr) Print(#expr,"=",expr)

//--- define the MACRO_COUNTER custom macro via the predefined __COUNTER__ macro
#define MACRO_COUNTER __COUNTER__

//--- set the input value of the variable using the __COUNTER__ macro
input int InpVariable = __COUNTER__;

//--- set the value of the global variable using the __COUNTER__ macro before defining the function
int ExtVariable = __COUNTER__;

//+------------------------------------------------------------------+
//| the function returns the __COUNTER__ value |
//+------------------------------------------------------------------+
int GlobalFunc(void)
{
return(__COUNTER__);
}
//+------------------------------------------------------------------+
//| the template function returns the __COUNTER__ value |
//+------------------------------------------------------------------+
template<typename T>
int GlobalTemplateFunc(void)
{
return(__COUNTER__);
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


929 Constants, Enumerations and Structures

//| the structure with the method returning __COUNTER__ |


//+------------------------------------------------------------------+
struct A
{
int dummy; // not used

int Method(void)
{
return(__COUNTER__);
}
};
//+------------------------------------------------------------------+
//| the template structure with the method returning __COUNTER__ |
//+------------------------------------------------------------------+
template<typename T>
struct B
{
int dummy; // not used

int Method(void)
{
return(__COUNTER__);
}
};
//+------------------------------------------------------------------+
//| the structure with the template method returning __COUNTER__ |
//+------------------------------------------------------------------+
struct C
{
int dummy; // not used

template<typename T>
int Method(void)
{
return(__COUNTER__);
}
};
//+------------------------------------------------------------------+
//| the function #2, which returns the __COUNTER__ value |
//+------------------------------------------------------------------+
int GlobalFunc2(void)
{
return(__COUNTER__);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart(void)
{

© 2000-2025, MetaQuotes Ltd.


930 Constants, Enumerations and Structures

// __COUNTER__ in the macro and the variables


print(MACRO_COUNTER);
print(InpVariable);
print(ExtVariable);

//--- __COUNTER__ in the functions


print(GlobalFunc());
print(GlobalFunc()); // the value is not changed
print(GlobalTemplateFunc<int>());
print(GlobalTemplateFunc<int>()); // the value is not changed
print(GlobalTemplateFunc<double>());// the value has changed
print(GlobalFunc2());
print(GlobalFunc2()); // the value is not changed

// __COUNTER__ in the structure


A a1, a2;
print(a1.Method());
print(a2.Method()); // the value is not changed

// __COUNTER__ in the template structure


B<int> b1, b2;
B<double> b3;
print(b1.Method());
print(b2.Method()); // the value is not changed
print(b3.Method()); // the value has changed

// __COUNTER__ in the structure with the template function


C c1, c2;
print(c1.Method<int>());
print(c1.Method<double>()); // the value has changed
print(c2.Method<int>()); // the same value as during the first c1.Method<int>() call

//--- let's have another look at __COUNTER__ in the macro and the global variable
print(MACRO_COUNTER); // the value has changed
print(ExtGlobal2);
}
//--- set the value of the global variable using the __COUNTER__ macro after defining the functions
int ExtGlobal2 = __COUNTER__;
//+------------------------------------------------------------------+

/* Result
__COUNTER__=3
InpVariable=0
ExtVariable=1
GlobalFunc()=5
GlobalFunc()=5
GlobalTemplateFunc<int>()=8
GlobalTemplateFunc<int>()=8
GlobalTemplateFunc<double>()=9

© 2000-2025, MetaQuotes Ltd.


931 Constants, Enumerations and Structures

GlobalFunc2()=7
GlobalFunc2()=7
a1.Method()=6
a2.Method()=6
b1.Method()=10
b2.Method()=10
b3.Method()=11
c1.Method<int>()=12
c1.Method<double>()=13
c2.Method<int>()=12
__COUNTER__=4
ExtGlobal2=2

*/

© 2000-2025, MetaQuotes Ltd.


932 Constants, Enumerations and Structures

Mathematical Constants
S pecial constants
containing values are reserved for some mathematical expressions. These constants
can be used in any place of the program instead of calculating their values using 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_S QRTPI 2/s qrt(pi) 1.12837916709551257390

M _S QRT2 s qrt(2) 1.41421356237309504880

M _S QRT1_2 1/s qrt(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));

© 2000-2025, MetaQuotes Ltd.


933 Constants, Enumerations and Structures

© 2000-2025, MetaQuotes Ltd.


934 Constants, Enumerations and Structures

Numerical Type Constants


Each simple numerical type is intended for a certain type of tas k s and allows optimizing the operation
of a mql5-program when used correctly. For a better code readability and correct handling of
calculation results, there are constants which allow to receive information about restrictions set to a
certain type of simple data.
Constant Description Value

CHAR_MIN Minimal value, which can be represented -128


by char type
CHAR_M AX Maximal value, which can be represented 127
by char type
UCHAR_M AX Maximal value, which can be represented 255
by uchar type
SH OR T _MIN Minimal value, which can be represented -32768
by short type
SH OR T _M AX Maximal value, which can be represented 32767
by short type
USH OR T _M AX Maximal value, which can be represented 65535
by ushort type
INT_MIN Minimal value, which can be represented -2147483648
by int type
INT_M AX Maximal value, which can be represented 2147483647
by int type
UINT _M AX Maximal value, which can be represented 4294967295
by uint type
LONG_MIN Minimal value, which can be represented -9223372036854775808
by long type
LONG_M AX Maximal value, which can be represented 9223372036854775807
by long type
ULONG_M AX Maximal value, which can be represented 18446744073709551615
by ulong type
DBL _MIN Minimal positive value, which can be 2.2250738585072014e-308
represented by double type
DBL _M AX Maximal value, which can be represented 1.7976931348623158e+308
by double type
DBL _EPS ILON Minimal value, which satisfies the 2.2204460492503131e-016
condition:
1.0+DBL _EPS ILON != 1.0 (for double type)

DBL _DIG Number of significant decimal digits for 15


double type

© 2000-2025, MetaQuotes Ltd.


935 Constants, Enumerations and Structures

Constant Description Value

DBL _M ANT _DIG Number of bits in a mantissa for double 53


type
DBL _M AX_10_E Maximal decimal value of exponent degree 308
XP for double type
DBL _M AX_EXP Maximal binary value of exponent degree 1024
for double type
DBL _MIN_10_EX Minimal decimal value of exponent degree (-307)
P for double type
DBL _MIN_EXP Minimal binary value of exponent degree (-1021)
for double type
FLT _MIN Minimal positive value, which can be 1.175494351e-38
represented by float type
FLT _M AX Maximal value, which can be represented 3.402823466e+38
by float type
FLT _EPS ILON Minimal value, which satisfies the 1.192092896e–07
condition:
1.0+DBL _EPS ILON != 1.0 (for float type)

FLT _DIG Number of significant decimal digits for 6


float type
FLT _M ANT _DIG Number of bits in a mantissa for float type 24

FLT _M AX_10_E Maximal decimal value of exponent degree 38


XP for float type
FLT _M AX_EXP Maximal binary value of exponent degree 128
for float type
FLT _MIN_10_EX Minimal decimal value of exponent degree -37
P for float type
FLT _MIN_EXP Minimal binary value of exponent degree (-125)
for float type
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);

© 2000-2025, MetaQuotes Ltd.


936 Constants, Enumerations and Structures

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);
/*
CHAR_MIN = -128
CHAR_MAX = 127
UCHAR_MAX = 255
SHORT_MIN = -32768
SHORT_MAX = 32767
USHORT_MAX = 65535
INT_MIN = -2147483648
INT_MAX = 2147483647
UINT_MAX = 4294967295
LONG_MIN = -9223372036854775808
LONG_MAX = 9223372036854775807
ULONG_MAX = 18446744073709551615
EMPTY_VALUE = 1.7976931348623157e+308
DBL_MIN = 2.2250738585072014e-308
DBL_MAX = 1.7976931348623157e+308
DBL_EPSILON = 2.2204460492503131e-16
DBL_DIG = 15
DBL_MANT_DIG = 53
DBL_MAX_10_EXP = 308
DBL_MAX_EXP = 1024
DBL_MIN_10_EXP = -307
DBL_MIN_EXP = -1021
FLT_MIN = 1.17549435e-38
FLT_MAX = 3.40282347e+38
FLT_EPSILON = 1.19209290e-07
*/
}

© 2000-2025, MetaQuotes Ltd.


937 Constants, Enumerations and Structures

Uninitialization Reason Codes


Uninitialization reason codes are returned by the UninitializeReason() function. The possible values are
the following:
Constant Value Description

REAS ON_PR OGRAM 0 Expert Advisor terminated its operation by calling


the ExpertRemove() function
REAS ON_REMOVE 1 Program has been deleted from the chart
REAS ON_RECOMPIL E 2 Program has been recompiled
REAS ON_CHAR TCHANGE 3 S ymbol or chart period has been changed
REAS ON_CHAR TCLOSE 4 Chart has been closed
REAS ON_PARAM ET ERS 5 Input parameters have been changed by a user
REAS ON_ACCOUNT 6 Another account has been activated or reconnection
to the trade server has occurred due to changes in
the account settings
REAS ON_T EMPL AT E 7 A new template has been applied
REAS ON_INIT FAIL ED 8 This value means that OnInit() handler has returned
a nonzero value
REAS ON_CLOSE 9 Terminal has been closed
The uninitialization reason code is also passed as a parameter of the predetermined function
OnDeinit(const int reason).
Example:

//+------------------------------------------------------------------+
//| get text description |
//+------------------------------------------------------------------+
string getUninitReasonText(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:

© 2000-2025, MetaQuotes Ltd.


938 Constants, Enumerations and Structures

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 uninitialization reason code
Print(__FUNCTION__,"_Uninitalization reason code = ",reason);
//--- The second way to get the uninitialization reason code
Print(__FUNCTION__,"_UninitReason = ",getUninitReasonText(_UninitReason));
}

© 2000-2025, MetaQuotes Ltd.


939 Constants, Enumerations and Structures

Checking Object Pointer


The CheckPointer() function is used for checking the type of the object pointer. The function returns a
value of the ENUM _POINTER_TYPE enumeration. If an incorrect pointer is used, the program execution
will be immediately terminated.
Objects created by the new() operator are of POINTER_DYNAMIC type. The delete() operator can and
should be used only for such pointers.
Allother pointers are of POINTER_AUTOM ATIC type, which means that this object has been created
automatically by the mql5 program environment. S uch objects are deleted automatically after being
used.
ENUM_POINTER_TY PE

Constant Description

POINTER_INVALID Incorrect pointer


POINTER_DYNAMIC Pointer of the object created by the new()
operator
POINTER_AUTOM ATIC Pointer of any objects created automatically
(not using new())

See also
R untime errors, Object Delete Operator delete, CheckPointer

© 2000-2025, MetaQuotes Ltd.


940 Constants, Enumerations and Structures

Other Constants
The CLR_NONE constant is used to outline the absence of color, it means that the graphical object or
graphical series of an indicator will not be plotted. This constant was not included into the W eb-color
constants list, but it can be applied everywhere where the color arguments are required.
The INVALID_HANDLE constant can be used for checking file handles (see FileOpen() and
FileFindFirst()).

Constant Description Value

CHARTS_M AX The maximum possible 100


number of simultaneously open
charts in the terminal
clrNONE Absence of color -1
EMPT Y_VAL UE Empty value in an indicator DBL _M AX
buffer
INVALID_HANDLE Incorrect handle -1
IS_DEBUG_MODE Flag that a mq5-program non zero in debug mode,
operates in debug mode otherwise zero
IS_PROFILE_MODE Flag that a mq5-program non zero in profiling mode,
operates in profiling mode otherwise zero
NULL Zero for any types 0

WH OL E_ARRAY Means the number of items -1


remaining until the end of the
array, i.e., the entire array
will be processed
WR ONG_VAL UE The constant can be implicitly -1
cast to any enumeration type
The EMPTY_VALUE constant usually corresponds to the values of indicators that are not shown in the
chart. For example, for built-in indicator S tandard Deviation with a period of 20, the line for the first
19 bars in the history is not shown in the chart. If you create a handle of this indicator with the
iS tdDev() function and copy it to an array of indicator values for these bars through CopyBuffer(), then
these values will be equal to EMPTY_VALUE.
You can choose to specify for a custom indicator your own empty value of the indicator, when the
indicator shouldn't be drawn in the chart. Use the PlotIndexS etDouble() function with the
PLOT_EMPTY_VALUE modifier.
The NULL constant can be assigned to a variable of any simple type or to an object structure or class
pointer. The NULL assignment for a string variable means the full deinitialization of this variable.
The WRONG_VALUE constant is intended for cases, when it is necessary to return value of an
enumeration, and this must be a wrong value. For example, when we need to inform that a return
value is a value from this enumeration. Let's consider as an example some function CheckLineS tyle(),
which returns the line style for an object, specified by its name. If at style check by

© 2000-2025, MetaQuotes Ltd.


941 Constants, Enumerations and Structures

ObjectGetInteger() the result is true, a value from ENUM _LINE_S T YL E is returned; otherwise
WR ONG_VAL UE is returned.

void OnStart()
{
if(CheckLineStyle("MyChartObject")==WRONG_VALUE)
printf("Error line style getting.");
}
//+------------------------------------------------------------------+
//| returns the line style for an object specified by its name |
//+------------------------------------------------------------------+
ENUM_LINE_STYLE CheckLineStyle(string name)
{
long style;
//---
if(ObjectGetInteger(0,name,OBJPROP_STYLE,0,style))
return((ENUM_LINE_STYLE)style);
else
return(WRONG_VALUE);
}

The WHOLE_ARRAY constant is intended for functions that require specifying the number of elements
in processed arrays :
· ArrayCopy();

· ArrayMinimum();

· ArrayMaximum();

· FileR eadArray();

· FileW riteArray().

If you want to specify that all the array values from a specified position till the end must be processed,
you should specify just the WHOLE_ARRAY value.
IS_PROFILE_MODE constant allows changing a program operation for correct data collection in the
profiling mode. Profiling allows measuring the execution time of the individual program fragments
(usually comprising functions), as well as calculating the number of such calls. S leep() function calls
can be disabled to determine the execution time in the profiling mode, like in this example:
//--- Sleep can greatly affect (change) profiling result
if(!IS_PROFILE_MODE) Sleep(100); // disabling Sleep() call in the profiling mode

IS_PROFILE_MODE constant value is set by the compiler during the compilation, while it is set to zero
in conventional mode. W hen launching a program in the profiling mode, a special compilation is
performed and IS_PROFILE_MODE is replaced with a non-zero value.
The IS_DEBUG_MODE constant can be useful when you need to slightly change the operation of a mql5
program in the debugging mode. For example, in debug mode you may need to display additional
debugging information in the terminal log or create additional graphical objects in a chart.

© 2000-2025, MetaQuotes Ltd.


942 Constants, Enumerations and Structures

The following example creates a Label object and sets its description and color depending on the script
running mode. In order to run a script in the debug mode from MetaEditor, press F5. If you run the
script from the browser window in the terminal, then the color and text of the object Label will be
different.
Example:

//+------------------------------------------------------------------+
//| Check_DEBUG_MODE.mq5 |
//| Copyright © 2009, MetaQuotes Software Corp. |
//| https://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, MetaQuotes Software Corp."
#property link "https://www.metaquotes.net"
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
string label_name="invisible_label";
if(ObjectFind(0,label_name)<0)
{
Print("Object",label_name,"not found. Error code = ",GetLastError());
//--- create 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);
ResetLastError();
if(IS_DEBUG_MODE) // debug mode
{
//--- show message about the script execution mode
ObjectSetString(0,label_name,OBJPROP_TEXT,"DEBUG MODE");
//--- set text color to red
if(!ObjectSetInteger(0,label_name,OBJPROP_COLOR,clrRed))
Print("Unable to set the color. Error",GetLastError());
}
else // operation mode
{
ObjectSetString(0,label_name,OBJPROP_TEXT,"RELEASE MODE");
//--- set text color to invisible
if(!ObjectSetInteger(0,label_name,OBJPROP_COLOR,CLR_NONE))
Print("Unable to set the color. Error ",GetLastError());
}
ChartRedraw();
DebugBreak(); // here termination will occur, if we are in debug mode
}

© 2000-2025, MetaQuotes Ltd.


943 Constants, Enumerations and Structures

Crypt Methods
The ENUM _CRYPT_M ETHOD enumeration is used to specify the data transformation method, used in
CryptEncode() and CryptDecode() functions.
ENUM_CRY PT_METHOD

Constant Description

CRYPT_BASE64 BASE64

CRYPT_AES128 AES encryption with 128 bit key (16 bytes)


CRYPT_AES256 AES encryption with 256 bit key (32 bytes)
CRYPT_DES DES encryption with 56 bit key (7 bytes)
CRYPT_HASH_SHA1 SHA1 HASH calculation
CRYPT_HASH_SHA2 SHA256 HASH calculation
56
CRYPT_HASH_M D5 M D5 HASH calculation
CRYPT_ARCH_ZIP ZIP archives

See also
Debug Break , Executed MQL5 program properties, CryptEncode(), CryptDecode()

© 2000-2025, MetaQuotes Ltd.


944 Constants, Enumerations and Structures

Data Structures
MQL5 Language offers 12 predefined structures :
· M qlDateTime is intended for working with date and time;
· M qlParam can send input parameters when creating a handle of the indicator using the
IndicatorCreate() function;
· M qlRates is intended for manipulating the historical data, it contains information about the price,
volume and spread;
· M qlBookInfo is intended for obtaining information about the Depth of Market;
· M qlTradeRequest is used for creating a trade request for trade operations ;
· M qlTradeCheckResult is intended for checking the prepared trade request before sending it;
· M qlTradeResult contains a trade server reply to a trade request, sent by OrderS end() function;
· M qlTradeTransaction contains description of a trade transaction;
· M qlTick is designed for fast retrieval of the most requested information about current prices.
· Economic calendar structures are used to obtain data on the economic calendar events sent to the
MetaTrader 5 platform in real time. Economic calendar functions allow analyzing macroeconomic
parameters immediately after new reports are released, since relevant values are broadcast directly
from the source with no delay.

© 2000-2025, MetaQuotes Ltd.


945 Constants, Enumerations and Structures

MqlDateTime
The date type structure contains 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, ... ,6-Saturday)
int day_of_year; // Day number of the year (January 1st is assigned the number value of zero)
};

Note

The day number of the year day_of_year for the leap year, since March, will differ from a number of
the corresponding day for a non-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

TimeToS truct, S tructures and Classes

© 2000-2025, MetaQuotes Ltd.


946 Constants, Enumerations and Structures

The Structure of Input Parameters of Indicators (MqlParam)


The M qlParam structure has been specially designed to provide input parameters when creating the
handle of a technical indicator using the IndicatorCreate() function.
struct MqlParam
{
ENUM_DATATYPE type; // type of the input parameter, value of ENUM_DATATYP
long integer_value; // field to store an integer type
double double_value; // field to store a double type
string string_value; // field to store a string type
};

All input parameters of an indicator are transmitted in the form of an array of the M qlParam type, the
type field of each element of this array specifies the type of data transmitted by the element. The
indicator values must be first placed in the appropriate fields for each element (in integer_value, in
double_value or string_value) depending on what value of ENUM _DA T A T YPE enumeration is specified

in the type field.


If the IND_CUS TOM value is passed third as the indicator type to the IndicatorCreate() function, the
first element of the array of input parameters must have the type field with the value of TYPE_S TRING
from the ENUM _DATATYPE enumeration, and the string_value field must contain the name of the
custom indicator.

© 2000-2025, MetaQuotes Ltd.


947 Constants, Enumerations and Structures

MqlRates
This structure stores information about the prices, volumes and spread.
struct MqlRates
{
datetime time; // Period 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 real_volume; // Trade volume
};

Example:

void OnStart()
{
MqlRates rates[];
int copied=CopyRates(NULL,0,0,100,rates);
if(copied<=0)
Print("Error copying price data ",GetLastError());
else Print("Copied ",ArraySize(rates)," bars");
}

See also

CopyRates, Access to timeseries

© 2000-2025, MetaQuotes Ltd.


948 Constants, Enumerations and Structures

MqlBookInfo
It provides information about the market depth data.
struct MqlBookInfo
{
ENUM_BOOK_TYPE type; // Order type from ENUM_BOOK_TYPE enumeration
double price; // Price
long volume; // Volume
double volume_real; // Volume with greater accuracy
};

Note

The M qlBookInfo structure is predefined, thus it doesn't require any declaration and description. To
use the structure, just declare a variable of this type.
The DOM is available only for some symbols.
Example:

MqlBookInfo priceArray[];
bool getBook=MarketBookGet(NULL,priceArray);
if(getBook)
{
int size=ArraySize(priceArray);
Print("MarketBookInfo about ",Symbol());
}
else
{
Print("Failed to receive DOM for the symbol ",Symbol());
}

See also

MarketBookAdd, MarketBookRelease, MarketBookGet, Trade Orders in DOM, Data Types

© 2000-2025, MetaQuotes Ltd.


949 Constants, Enumerations and Structures

The Trade Request Structure (MqlTradeRequest)


Interaction between the client terminal and a trade server for executing the order placing operation is
performed by using trade requests. The trade request is represented by the special predefined
structure of M qlTradeRequest type, which contain all the fields necessary to perform trade deals. The
request processing result is represented by the structure of M qlTradeResult type.
struct MqlTradeRequest
{
ENUM_TRADE_REQUEST_ACTIONS action; // Trade operation type
ulong magic; // Expert Advisor ID (magic number)
ulong order; // Order ticket
string symbol; // Trade symbol
double volume; // Requested volume for a deal in lots
double price; // Price
double stoplimit; // StopLimit level of the order
double sl; // Stop Loss level of the order
double tp; // Take Profit level of the order
ulong deviation; // Maximal possible deviation from the requested
ENUM_ORDER_TYPE type; // Order type
ENUM_ORDER_TYPE_FILLING type_filling; // Order execution type
ENUM_ORDER_TYPE_TIME type_time; // Order expiration type
datetime expiration; // Order expiration time (for the orders of ORDE
string comment; // Order comment
ulong position; // Position ticket
ulong position_by; // The ticket of an opposite position
};

Fields description

Field Description

action Trade operation type. Can be one of the ENUM _T RADE_REQUES T _ACTIONS
enumeration values.
magic Expert Advisor ID. It allows organizing analytical processing of trade orders. Each
Expert Advisor can set its own unique ID when sending a trade request.

order Order ticket. It is used for modifying pending orders.


symbol S ymbol ofthe order. It is not necessary for order modification and position close
operations.
volume R equested order volume in lots. Note that the real volume of a deal will depend on
the order execution type.
price Price, reaching which the order must be executed. Market orders of symbols,
whose execution type is " Mark et
Execution" (SYM BOL _T RADE_EXECUTION_M ARKET), of T RADE_ACTION_DEAL type,
do not require specification of price.

© 2000-2025, MetaQuotes Ltd.


950 Constants, Enumerations and Structures

Field Description

stoplimit The price value, at which the Limit pending order will be placed, when price
reaches the price value (this condition is obligatory). Until then the pending order
is not placed.
sl S top Loss price in case of the unfavorable price movement
tp Take Profit price in the case of the favorable price movement
deviation The maximal price deviation, specified in points
type Order type. Can be one of the ENUM _ORDER_TYPE enumeration values.
type_filling Order execution type. Can be one of the enumeration
ENUM _ORDER_T YPE_FILLING values.

type_time Order expiration type. Can be one of the enumeration ENUM _ORDER_T YPE_TIM E
values.
expiration Order expiration time (for orders of ORDER_TIM E_S PECIFIED type)
comment Order comment
position Ticket of a position. S hould be filled in when a position is modified or closed to
identify the position. As a rule it is equal to the ticket of the order, based on
which the position was opened.
position_by Ticket of an opposite position. Used when a position is closed by an opposite one
open for the same symbol in the opposite direction.

W hen modifying or closing a position in the hedging system, make sure to specify its ticket
(M qlTradeRequest::position). The ticket can also be specified in the netting system, though a
position is identified by the symbol name.

For sending orders to perform trade operations it is necessary to use the OrderS end() function. For
each trade operation it is necessary to specify obligatory fields ; optional fields also may be filled.
There are seven possible cases to send a trade order:
Request Execution

This is a trade order to open a position in the Request Execution mode (trade upon requested
prices). 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 " magic" and " comment" field values.

© 2000-2025, MetaQuotes Ltd.


951 Constants, Enumerations and Structures

Instant Execution

This is a trade order to open a position in the Instant Execution mode (trade by current prices). It
requires specification of the following 9 fields :
· action
· symbol
· volume
· price
· sl
· tp
· deviation
· type
· type_filling

Also it is possible to specify the " magic" and " comment" field values.
Market Execution

This is a trade order to open a position in the Market Execution mode. It requires to specify the
following 5 fields :
· action
· symbol
· volume
· type
· type_filling

Also it is possible to specify the " magic" and " comment" field values.
Exchange Execution

This is a trade order to open a position in the Exchange Execution mode. It requires to specify the
following 5 fields :
· action
· symbol
· volume
· type
· type_filling

Also it is possible to specify the " magic" and " comment" field values.
Example of the TRADE_ACTION_DEAL trade operation for opening a Buy position:

© 2000-2025, MetaQuotes Ltd.


952 Constants, Enumerations and Structures

#define EXPERT_MAGIC 123456 // MagicNumber of the expert


//+------------------------------------------------------------------+
//| Opening Buy position |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
//--- parameters of request
request.action =TRADE_ACTION_DEAL; // type of trade operation
request.symbol =Symbol(); // symbol
request.volume =0.1; // volume of 0.1 lot
request.type =ORDER_TYPE_BUY; // order type
request.price =SymbolInfoDouble(Symbol(),SYMBOL_ASK); // price for opening
request.deviation=5; // allowed deviation from the price
request.magic =EXPERT_MAGIC; // MagicNumber of the order
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, outpu
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
}
//+------------------------------------------------------------------+

Example of the TRADE_ACTION_DEAL trade operation for opening a S ell position:


#define EXPERT_MAGIC 123456 // MagicNumber of the expert
//+------------------------------------------------------------------+
//| Opening Sell position |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
//--- parameters of request
request.action =TRADE_ACTION_DEAL; // type of trade operation
request.symbol =Symbol(); // symbol
request.volume =0.2; // volume of 0.2 lot
request.type =ORDER_TYPE_SELL; // order type
request.price =SymbolInfoDouble(Symbol(),SYMBOL_BID); // price for opening
request.deviation=5; // allowed deviation from the price
request.magic =EXPERT_MAGIC; // MagicNumber of the order
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, outpu
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
}
//+------------------------------------------------------------------+

Example of the TRADE_ACTION_DEAL trade operation for closing positions :

© 2000-2025, MetaQuotes Ltd.


953 Constants, Enumerations and Structures

#define EXPERT_MAGIC 123456 // MagicNumber of the expert


//+------------------------------------------------------------------+
//| Closing all positions |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request;
MqlTradeResult result;
int total=PositionsTotal(); // number of open positions
//--- iterate over all open positions
for(int i=total-1; i>=0; i--)
{
//--- parameters of the order
ulong position_ticket=PositionGetTicket(i); // ticket o
string position_symbol=PositionGetString(POSITION_SYMBOL); // symbol
int digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS); // number o
ulong magic=PositionGetInteger(POSITION_MAGIC); // MagicNum
double volume=PositionGetDouble(POSITION_VOLUME); // volume o
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); // type of
//--- output information about the position
PrintFormat("#%I64u %s %s %.2f %s [%I64d]",
position_ticket,
position_symbol,
EnumToString(type),
volume,
DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
magic);
//--- if the MagicNumber matches
if(magic==EXPERT_MAGIC)
{
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
//--- setting the operation parameters
request.action =TRADE_ACTION_DEAL; // type of trade operation
request.position =position_ticket; // ticket of the position
request.symbol =position_symbol; // symbol
request.volume =volume; // volume of the position
request.deviation=5; // allowed deviation from the price
request.magic =EXPERT_MAGIC; // MagicNumber of the position
//--- set the price and order type depending on the position type
if(type==POSITION_TYPE_BUY)
{
request.price=SymbolInfoDouble(position_symbol,SYMBOL_BID);
request.type =ORDER_TYPE_SELL;
}
else
{
request.price=SymbolInfoDouble(position_symbol,SYMBOL_ASK);
request.type =ORDER_TYPE_BUY;
}
//--- output information about the closure
PrintFormat("Close #%I64d %s %s",position_ticket,position_symbol,EnumToString(type));
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, ou
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order)
//---
}

© 2000-2025, MetaQuotes Ltd.


954 Constants, Enumerations and Structures

}
}
//+------------------------------------------------------------------+

SL & TP Modification

Trade order to modify the S topLoss and/or TakeProfit price levels. It requires to specify the
following 4 fields :
· action
· symbol
· sl
· tp
· position

Example of the TRADE_ACTION_S LTP trade operation for modifying the S top Loss and Take Profit
values of an open position:
#define EXPERT_MAGIC 123456 // MagicNumber of the expert
//+------------------------------------------------------------------+
//| Modification of Stop Loss and Take Profit of position |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request;
MqlTradeResult result;
int total=PositionsTotal(); // number of open positions
//--- iterate over all open positions
for(int i=0; i<total; i++)
{
//--- parameters of the order
ulong position_ticket=PositionGetTicket(i);// ticket of the position
string position_symbol=PositionGetString(POSITION_SYMBOL); // symbol
int digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS); // number of decimal pla
ulong magic=PositionGetInteger(POSITION_MAGIC); // MagicNumber of the position
double volume=PositionGetDouble(POSITION_VOLUME); // volume of the position
double sl=PositionGetDouble(POSITION_SL); // Stop Loss of the position
double tp=PositionGetDouble(POSITION_TP); // Take Profit of the position
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); // type of th
//--- output information about the position
PrintFormat("#%I64u %s %s %.2f %s sl: %s tp: %s [%I64d]",
position_ticket,
position_symbol,
EnumToString(type),
volume,
DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
DoubleToString(sl,digits),
DoubleToString(tp,digits),
magic);
//--- if the MagicNumber matches, Stop Loss and Take Profit are not defined
if(magic==EXPERT_MAGIC && sl==0 && tp==0)
{

© 2000-2025, MetaQuotes Ltd.


955 Constants, Enumerations and Structures

//--- calculate the current price levels


double price=PositionGetDouble(POSITION_PRICE_OPEN);
double bid=SymbolInfoDouble(position_symbol,SYMBOL_BID);
double ask=SymbolInfoDouble(position_symbol,SYMBOL_ASK);
int stop_level=(int)SymbolInfoInteger(position_symbol,SYMBOL_TRADE_STOPS_LEVEL);
double price_level;
//--- if the minimum allowed offset distance in points from the current close price is not
if(stop_level<=0)
stop_level=150; // set the offset distance of 150 points from the current close price
else
stop_level+=50; // set the offset distance to (SYMBOL_TRADE_STOPS_LEVEL + 50) points fo

//--- calculation and rounding of the Stop Loss and Take Profit values
price_level=stop_level*SymbolInfoDouble(position_symbol,SYMBOL_POINT);
if(type==POSITION_TYPE_BUY)
{
sl=NormalizeDouble(bid-price_level,digits);
tp=NormalizeDouble(bid+price_level,digits);
}
else
{
sl=NormalizeDouble(ask+price_level,digits);
tp=NormalizeDouble(ask-price_level,digits);
}
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
//--- setting the operation parameters
request.action =TRADE_ACTION_SLTP; // type of trade operation
request.position=position_ticket; // ticket of the position
request.symbol=position_symbol; // symbol
request.sl =sl; // Stop Loss of the position
request.tp =tp; // Take Profit of the position
request.magic=EXPERT_MAGIC; // MagicNumber of the position
//--- output information about the modification
PrintFormat("Modify #%I64d %s %s",position_ticket,position_symbol,EnumToString(type));
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, ou
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order)
}
}
}
//+------------------------------------------------------------------+

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

© 2000-2025, MetaQuotes Ltd.


956 Constants, Enumerations and Structures

· type_filling
· type_time
· expiration
Also it is possible to specify the " magic" and " comment" field values.
Example of the TRADE_ACTION_PENDING trade operation for placing a pending order:

© 2000-2025, MetaQuotes Ltd.


957 Constants, Enumerations and Structures

#property description "Example of placing pending orders"


#property script_show_inputs
#define EXPERT_MAGIC 123456 // MagicNumber of the expert
input ENUM_ORDER_TYPE orderType=ORDER_TYPE_BUY_LIMIT; // order type
//+------------------------------------------------------------------+
//| Placing pending orders |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
//--- parameters to place a pending order
request.action =TRADE_ACTION_PENDING; // type of trade operation
request.symbol =Symbol(); // symbol
request.volume =0.1; // volume of 0.1 lot
request.deviation=2; // allowed deviation from th
request.magic =EXPERT_MAGIC; // MagicNumber of the order
int offset = 50; // offset from the current p
double price; // order triggering price
double point=SymbolInfoDouble(_Symbol,SYMBOL_POINT); // value of point
int digits=SymbolInfoInteger(_Symbol,SYMBOL_DIGITS); // number of decimal places
//--- checking the type of operation
if(orderType==ORDER_TYPE_BUY_LIMIT)
{
request.type =ORDER_TYPE_BUY_LIMIT; // order type
price=SymbolInfoDouble(Symbol(),SYMBOL_ASK)-offset*point; // price for opening
request.price =NormalizeDouble(price,digits); // normalized opening price
}
else if(orderType==ORDER_TYPE_SELL_LIMIT)
{
request.type =ORDER_TYPE_SELL_LIMIT; // order type
price=SymbolInfoDouble(Symbol(),SYMBOL_BID)+offset*point; // price for opening
request.price =NormalizeDouble(price,digits); // normalized opening price
}
else if(orderType==ORDER_TYPE_BUY_STOP)
{
request.type =ORDER_TYPE_BUY_STOP; // order type
price =SymbolInfoDouble(Symbol(),SYMBOL_ASK)+offset*point; // price for opening
request.price=NormalizeDouble(price,digits); // normalized opening price
}
else if(orderType==ORDER_TYPE_SELL_STOP)
{
request.type =ORDER_TYPE_SELL_STOP; // order type
price=SymbolInfoDouble(Symbol(),SYMBOL_BID)-offset*point; // price for opening
request.price =NormalizeDouble(price,digits); // normalized opening price
}
else Alert("This example is only for placing pending orders"); // if not pending order is sele
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the re
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
}
//+------------------------------------------------------------------+

Modify Pending Order

Trade order to modify the prices of a pending order. It requires to specify the following 7 fields :
· action

© 2000-2025, MetaQuotes Ltd.


958 Constants, Enumerations and Structures

· order
· price
· sl
· tp
· type_time
· expiration

Example of the TRADE_ACTION_MODIFY trade operation for modifying the price levels of pending
orders :

© 2000-2025, MetaQuotes Ltd.


959 Constants, Enumerations and Structures

#define EXPERT_MAGIC 123456 // MagicNumber of the expert


//+------------------------------------------------------------------+
//| Modification of pending orders |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
int total=OrdersTotal(); // total number of placed pending orders
//--- iterate over all placed pending orders
for(int i=0; i<total; i++)
{
//--- parameters of the order
ulong order_ticket=OrderGetTicket(i); // order ticket
string order_symbol=Symbol(); // symbol
int digits=(int)SymbolInfoInteger(order_symbol,SYMBOL_DIGITS); // number of decimal place
ulong magic=OrderGetInteger(ORDER_MAGIC); // MagicNumber of the orde
double volume=OrderGetDouble(ORDER_VOLUME_CURRENT); // current volume of the o
double sl=OrderGetDouble(ORDER_SL); // current Stop Loss of th
double tp=OrderGetDouble(ORDER_TP); // current Take Profit of
ENUM_ORDER_TYPE type=(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); // type of the order
int offset = 50; // offset from the current
double price; // order triggering price
double point=SymbolInfoDouble(order_symbol,SYMBOL_POINT); // value of point
//--- output information about the order
PrintFormat("#%I64u %s %s %.2f %s sl: %s tp: %s [%I64d]",
order_ticket,
order_symbol,
EnumToString(type),
volume,
DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
DoubleToString(sl,digits),
DoubleToString(tp,digits),
magic);
//--- if the MagicNumber matches, Stop Loss and Take Profit are not defined
if(magic==EXPERT_MAGIC && sl==0 && tp==0)
{
request.action=TRADE_ACTION_MODIFY; // type of trade operation
request.order = OrderGetTicket(i); // order ticket
request.symbol =Symbol(); // symbol
request.deviation=5; // allowed deviation from th
//--- setting the price level, Take Profit and Stop Loss of the order depending on its type
if(type==ORDER_TYPE_BUY_LIMIT)
{
price = SymbolInfoDouble(Symbol(),SYMBOL_ASK)-offset*point;
request.tp = NormalizeDouble(price+offset*point,digits);
request.sl = NormalizeDouble(price-offset*point,digits);
request.price =NormalizeDouble(price,digits); // normalized opening p
}
else if(type==ORDER_TYPE_SELL_LIMIT)
{
price = SymbolInfoDouble(Symbol(),SYMBOL_BID)+offset*point;
request.tp = NormalizeDouble(price-offset*point,digits);
request.sl = NormalizeDouble(price+offset*point,digits);
request.price =NormalizeDouble(price,digits); // normalized opening
}
else if(type==ORDER_TYPE_BUY_STOP)
{
price = SymbolInfoDouble(Symbol(),SYMBOL_ASK)+offset*point;
request.tp = NormalizeDouble(price+offset*point,digits);

© 2000-2025, MetaQuotes Ltd.


960 Constants, Enumerations and Structures

request.sl = NormalizeDouble(price-offset*point,digits);
request.price =NormalizeDouble(price,digits); // normalized opening
}
else if(type==ORDER_TYPE_SELL_STOP)
{
price = SymbolInfoDouble(Symbol(),SYMBOL_BID)-offset*point;
request.tp = NormalizeDouble(price-offset*point,digits);
request.sl = NormalizeDouble(price+offset*point,digits);
request.price =NormalizeDouble(price,digits); // normalized opening
}
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, ou
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order)
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
}
}
}
//+------------------------------------------------------------------+

Delete Pending Order

Trade order to delete a pending order. It requires to specify the following 2 fields :
· action
· order

Example of the TRADE_ACTION_REMOVE trade operation for deleting pending orders :


#define EXPERT_MAGIC 123456 // MagicNumber of the expert

© 2000-2025, MetaQuotes Ltd.


961 Constants, Enumerations and Structures

//+------------------------------------------------------------------+
//| Deleting pending orders |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the trade request and result of trade request
MqlTradeRequest request={};
MqlTradeResult result={};
int total=OrdersTotal(); // total number of placed pending orders
//--- iterate over all placed pending orders
for(int i=total-1; i>=0; i--)
{
ulong order_ticket=OrderGetTicket(i); // order ticket
ulong magic=OrderGetInteger(ORDER_MAGIC); // MagicNumber of the order
//--- if the MagicNumber matches
if(magic==EXPERT_MAGIC)
{
//--- zeroing the request and result values
ZeroMemory(request);
ZeroMemory(result);
//--- setting the operation parameters
request.action=TRADE_ACTION_REMOVE; // type of trade operation
request.order = order_ticket; // order ticket
//--- send the request
if(!OrderSend(request,result))
PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, ou
//--- information about the operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order)
}
}
}
//+------------------------------------------------------------------+

See also

S tructures and Classes, Trade Functions, Order Properties

© 2000-2025, MetaQuotes Ltd.


962 Constants, Enumerations and Structures

The Structure of Results of a Trade Request Check


(MqlTradeCheckResult)
Before sending a request for a trade operation to a trade server, it is recommended to check it. The
check is performed using the OrderCheck() function, to which the checked request and a variable of
the M qlTradeCheckResult structure type are passed. The check result will be written to this variable.
struct MqlTradeCheckResult
{
uint retcode; // Reply code
double balance; // Balance after the execution of the deal
double equity; // Equity after the execution of the deal
double profit; // Floating profit
double margin; // Margin requirements
double margin_free; // Free margin
double margin_level; // Margin level
string comment; // Comment to the reply code (description of the error)
};

Description of Fields

Field Description

retcode R eturn code

balance Balance value that will be after the execution of the trade operation
equity Equity value that will be after the execution of the trade operation
profit Value of the floating profit that will be after the execution of the trade operation
margin Margin required for the trade operation
margin_free Free margin that will be left after the execution of the trade operation
margin_level Margin level that will be set after the execution of the trade operation
comment Comment to the reply code, error description

See also

Trade Request S tructure, S tructure for Current Prices, OrderS end, OrderCheck

© 2000-2025, MetaQuotes Ltd.


963 Constants, Enumerations and Structures

The Structure of a Trade Request Result (MqlTradeResult)


As result of a trade request, a trade server returns data about the trade request processing result as a
special predefined structure of M qlTradeResult type.
struct MqlTradeResult
{
uint retcode; // Operation return code
ulong deal; // Deal ticket, if it is performed
ulong order; // Order ticket, if it is 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 is filled by descriptio
uint request_id; // Request ID set by the terminal during the dispatch
int retcode_external; // Return code of an external trading system
};

Fields description

Field Description

retcode R eturn code of a trade server


deal Deal ticket, if a deal has been performed. It is available for a trade
operation of TRADE_ACTION_DEAL type
order Order ticket, if a ticket has been placed. It is available for a trade
operation of TRADE_ACTION_PENDING type
volume Deal volume, confirmed by broker. It depends on the order filling type
price Deal price, confirmed by broker. It depends on the deviation field of the
trade request and/or on the trade operation
bid The current market Bid price (requote price)
as k The current market As k price (requote price)
comment The broker comment to operation (by default it is filled by description of
trade server return code)
request_id R equest ID set by the terminal when sending to the trade server
retcode_external The code of the error returned by an external trading system. The use and
types of these errors depend on the broker and the external trading
system, to which trading operations are sent.

The trade operation result is returned to a variable of the M qlTradeResult type, which is passed as the
second parameter to OrderS end() to perform trade operations.
The terminal fixes request ID in request_id field when sending it to the trade server using
Orders S end() and OrderS endAsync() functions. The terminal receives messages about performed

© 2000-2025, MetaQuotes Ltd.


964 Constants, Enumerations and Structures

transactions from the trade server and submits them for processing by OnTradeTransaction() function
containing the following components as parameters :
· description of the trade transaction in M qlTradeTransaction structure;
· description of the trade request sent from OrderS end() or Orders S endAsync() function. Request ID is
sent by the terminal to the trade server, while the request itself and its request_id are stored in the
terminal memory;
· the trade request execution result as M qlTradeResult structure with request_id field containing ID of
this request.
OnTradeTransaction() function receives three input parameters but the last two should be analyzed
only for transactions having TRADE_TRANSACTION_REQUES T type. In all other cases, data on the trade
request and its execution result are not filled. Example of parameters analysis can be found at
S tructure of a Trade R equest.

S ettingrequest_id by the terminal for the trade request when sending it to the server is mainly
introduced for working with OrderS endAsync() asynchronous function. This identifier allows to
associate the performed action (OrderS end or OrderS endAsync functions call) with the result of this
action sent to OnTradeTransaction().
Example:

//+------------------------------------------------------------------+
//| Sending a trade request with the result processing |
//+------------------------------------------------------------------+
bool MyOrderSend(MqlTradeRequest request,MqlTradeResult result)
{
//--- reset the last error code to zero
ResetLastError();
//--- send request
bool success=OrderSend(request,result);
//--- if the result fails - try to find out why
if(!success)
{
int answer=result.retcode;
Print("TradeLog: Trade request failed. Error = ",GetLastError());
switch(answer)
{
//--- requote
case 10004:
{
Print("TRADE_RETCODE_REQUOTE");
Print("request.price = ",request.price," result.ask = ",
result.ask," result.bid = ",result.bid);
break;
}
//--- order is not accepted by the server
case 10006:
{
Print("TRADE_RETCODE_REJECT");

© 2000-2025, MetaQuotes Ltd.


965 Constants, Enumerations and Structures

Print("request.price = ",request.price," result.ask = ",


result.ask," result.bid = ",result.bid);
break;
}
//--- invalid price
case 10015:
{
Print("TRADE_RETCODE_INVALID_PRICE");
Print("request.price = ",request.price," result.ask = ",
result.ask," result.bid = ",result.bid);
break;
}
//--- invalid SL and/or TP
case 10016:
{
Print("TRADE_RETCODE_INVALID_STOPS");
Print("request.sl = ",request.sl," request.tp = ",request.tp);
Print("result.ask = ",result.ask," result.bid = ",result.bid);
break;
}
//--- invalid volume
case 10014:
{
Print("TRADE_RETCODE_INVALID_VOLUME");
Print("request.volume = ",request.volume," result.volume = ",
result.volume);
break;
}
//--- not enough money for a trade operation
case 10019:
{
Print("TRADE_RETCODE_NO_MONEY");
Print("request.volume = ",request.volume," result.volume = ",
result.volume," result.comment = ",result.comment);
break;
}
//--- some other reason, output the server response code
default:
{
Print("Other answer = ",answer);
}
}
//--- notify about the unsuccessful result of the trade request by returning false
return(false);
}
//--- OrderSend() returns true - repeat the answer
return(true);
}

© 2000-2025, MetaQuotes Ltd.


966 Constants, Enumerations and Structures

Structure of a Trade Transaction (MqlTradeTransaction)


W hen performing some definite actions on a trade account, its state changes. S uch actions include:
· S ending a trade request from any MQL5 application in the client terminal using OrderS end and
OrderS endAsync functions and its further execution;
· S ending a trade request via the terminal graphical interface and its further execution;
· Pending orders and stop orders activation on the server;
· Performing operations on a trade server side.
The following trade transactions are performed as a result of these actions :
· handling a trade request;
· changing open orders ;
· changing orders history;
· changing deals history;
· changing positions.
For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions.
S pecialOnTradeTransaction() handler is provided in MQL5 to get trade transactions applied to an
account. The first parameter of the handler gets M qlTradeTransaction structure describing trade
transactions.
struct MqlTradeTransaction
{
ulong deal; // Deal ticket
ulong order; // Order ticket
string symbol; // Trade symbol name
ENUM_TRADE_TRANSACTION_TYPE type; // Trade transaction type
ENUM_ORDER_TYPE order_type; // Order type
ENUM_ORDER_STATE order_state; // Order state
ENUM_DEAL_TYPE deal_type; // Deal type
ENUM_ORDER_TYPE_TIME time_type; // Order type by action period
datetime time_expiration; // Order expiration time
double price; // Price
double price_trigger; // Stop limit order activation price
double price_sl; // Stop Loss level
double price_tp; // Take Profit level
double volume; // Volume in lots
ulong position; // Position ticket
ulong position_by; // Ticket of an opposite position
};

Fields Description

© 2000-2025, MetaQuotes Ltd.


967 Constants, Enumerations and Structures

Field Description

deal Deal tick et.

order Order ticket.


symbol The name of the trading symbol, for which transaction is performed.
type Trade transaction type. The value can be one of
ENUM _T RADE_T RANSACTION_T YPE enumeration values.

order_type Trade order type. The value can be one of ENUM _ORDER_T YPE enumeration
values.
order_state Trade order state. The value can be one of ENUM _ORDER_S TATE enumeration
values.
deal_type Deal type. The value can be one of ENUM _DEAL_TYPE enumeration values.
time_type Order type upon expiration. The value can be one of ENUM _ORDER_TYPE_TIM E
values.
time_expiration Pending order expiration term (for orders of ORDER_TIM E_S PECIFIED and
ORDER_TIM E_S PECIFIED_DAY types).
price Price. Depending on a trade transaction type, it may be a price of an order, a
deal or a position.
price_trigger S top limit order stop (activation) price (ORDER_TYPE_BUY_S TOP_LIMIT and
ORDER_TYPE_SELL_S TOP_LIMIT).
price_sl S topLoss price. Depending on a trade transaction type, it may relate to an
order, a deal or a position.
price_tp Take Profit price. Depending on a trade transaction type, it may relate to an
order, a deal or a position.
volume Volume in lots. Depending on a trade transaction type, it may indicate the
current volume of an order, a deal or a position.
position The ticket of the position affected by the transaction.
position_by The ticket of the opposite position. Used when closing a position by an
opposite one, i.e. by a position of the same symbol that was opened in the
opposite direction.

The essential parameter for received transaction analysis is its type specified in type field. For
example, if a transaction is of TRADE_TRANSACTION_REQUES T type (a result of handling a trade
request by the server has been received), the structure has only only one field that is filled completely
- type. Other fields are not analyzed. In this case, we may analyze two additional request and result
parameters submitted to OnTradeTransaction() handler, as shown below.
H aving data on a trading operation type, you can decide on the analysis of the current state of orders,
positions and deals on a trading account. Remember that one trade request sent to the server from
the terminal can generate several new transactions. The priority of their arrival at the terminal is not
guaranteed.

© 2000-2025, MetaQuotes Ltd.


968 Constants, Enumerations and Structures

M qlTradeTransaction structure is filled in different ways depending on a trade transaction type


(ENUM _TRADE_TRANSACTION_TYPE):
TRADE_TRANSACTION_ORDER_* and TRADE_TRANSACTION_HISTORY _*

The following fields in M qlTradeTransaction structure are filled for trade transactions related to
open orders handling (TRADE_TRANSACTION_ORDER_ADD, TRADE_TRANSACTION_ORDER_UPDATE
and TRADE_TRANSACTION_ORDER_DELETE) and orders history
(TRADE_TRANSACTION_HIS TORY_ADD, TRADE_TRANSACTION_HIS TORY_UPDATE,
TRADE_TRANSACTION_HIS TORY_DELETE):
· order - order tick et;
· symbol - order symbol name;
· type - trade transaction type;
· order_type - order type;
· orders _state - order current state;
· time_type - order expiration type;
· time_expiration - order expiration time (for orders having ORDER_TIM E_S PECI FI ED and
ORDER_TIM E_S PECIFIED_DAY expiration types);
· price - order price specified by a client;
· price_trigger - stop limit order stop price (only for ORDER_T YPE_BUY_S TOP_LIMIT and
ORDER_TYPE_SELL_S TOP_LIMIT);
· price_sl - S top Loss order price (filled, if specified in the order);
· price_tp - Tak e Profit order price (filled, if specified in the order);
· volume - order current volume (unfilled). Initial order volume can be found in the orders history
using HistoryOrders * function.
· position - the tick et of the position that was opened, modified or closed as a result of order
execution. It is only filled for market orders, not filled for TRADE_TRANSACTION_ORDER_ADD.
· position_by - the tick et of the opposite position. It is only filled for the close by orders (to close a
position by an opposite one).
TRADE_TRANSACTION_DEAL_*

The following fields in M qlTradeTransaction structure are filled for trade transactions related to
deals handling (TRADE_TRANSACTION_DEAL_ADD, TRADE_TRANSACTION_DEAL_UPDATE and
TRADE_TRANSACTION_DEAL_DELETE):
· deal - deal tick et;
· order - order tick et, based on which a deal has been performed;
· symbol - deal symbol name;
· type - trade transaction type;
· deal_type - deal type;
· price - deal price;
· price_sl - S top Loss price (filled, if specified in the order, based on which a deal has been
performed);
· price_tp - Tak e Profit price (filled, if specified in the order, based on which a deal has been
performed);
· volume - deal volume in lots.
· position - the tick et of the position that was opened, modified or closed as a result of deal
execution.

© 2000-2025, MetaQuotes Ltd.


969 Constants, Enumerations and Structures

· position_by - the ticket of the opposite position. It is only filled for the out by deals (closing a
position by an opposite one).
TRADE_TRANSACTION_POSITION

The following fields in M qlTradeTransaction structure are filled for trade transactions related to
changing the positions not connected with deals execution (TRADE_TRANSACTION_POS ITION):
· symbol - position symbol name;
· type - trade transaction type;
· deal_type - position type (DEAL _T YPE_BUY or DEAL _T YPE_SELL);
· price - weighted average position open price;
· price_sl - S top Loss price;
· price_tp - Tak e Profit price;
· volume - position volume in lots, if it has been changed.

Position change (adding, changing or closing), as a result of a deal execution, does not lead to
the occurrence of TRADE_TRANSACTION_POS ITION transaction.

TRADE_TRANSACTION_REQUEST

Only one field in M qlTradeTransaction structure is filled for trade transactions describing the fact
that a trade request has been processed by a server and processing result has been received
(TRADE_TRANSACTION_REQUES T):
· type - trade transaction type;

Only type field (trade transaction type) must be analyzed for such transactions. The second and
third parameters of OnTradeTransaction function (request and result) must be analyzed for
additional data.

Example:

input int MagicNumber=1234567;

//--- enable CTrade trading class and declare the variable of this class
#include <Trade\Trade.mqh>
CTrade trade;
//--- flags for installing and deleting the pending order
bool pending_done=false;
bool pending_deleted=false;
//--- pending order ticket will be stored here
ulong order_ticket;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- set MagicNumber to mark all our orders
trade.SetExpertMagicNumber(MagicNumber);
//--- trade requests will be sent in asynchronous mode using OrderSendAsync() function
trade.SetAsyncMode(true);
//--- initialize the variable by zero

© 2000-2025, MetaQuotes Ltd.


970 Constants, Enumerations and Structures

order_ticket=0;
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---installing a pending order
if(!pending_done)
{
double ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
double buy_stop_price=NormalizeDouble(ask+1000*_Point,(int)SymbolInfoInteger(_Symbol,SYMBOL_D
bool res=trade.BuyStop(0.1,buy_stop_price,_Symbol);
//--- if BuyStop() function performed successfully
if(res)
{
pending_done=true;
//--- get a result of the request sending from ctrade
MqlTradeResult trade_result;
trade.Result(trade_result);
//--- get request_id for the sent request
uint request_id=trade_result.request_id;
Print("Request has been sent to set a pending order. Request_ID=",request_id);
//--- storing the order ticket (will be zero if using the asynchronous mode of sending to
order_ticket=trade_result.order;
//--- all is done, early exit from OnTick() handler
return;
}
}
//--- delete the pending order
if(!pending_deleted)
//--- additional check
if(pending_done && (order_ticket!=0))
{
//--- trying to delete the pending order
bool res=trade.OrderDelete(order_ticket);
Print("OrderDelete=",res);
//--- when delete request is sent successfully
if(res)
{
pending_deleted=true;
//--- get the request execution result
MqlTradeResult trade_result;
trade.Result(trade_result);
//--- take request ID from the result
uint request_id=trade_result.request_id;
//--- display in Journal

© 2000-2025, MetaQuotes Ltd.


971 Constants, Enumerations and Structures

Print("The request has been sent to delete a pending order #",order_ticket,


". Request_ID=",request_id,
"\r\n");
//--- fix the order ticket from the request result
order_ticket=trade_result.order;
}
}
//---
}
//+------------------------------------------------------------------+
//| TradeTransaction function |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
//--- get transaction type as enumeration value
ENUM_TRADE_TRANSACTION_TYPE type=(ENUM_TRADE_TRANSACTION_TYPE)trans.type;
//--- if the transaction is the request handling result, only its name is displayed
if(type==TRADE_TRANSACTION_REQUEST)
{
Print(EnumToString(type));
//--- display the handled request string name
Print("------------RequestDescription\r\n",RequestDescription(request));
//--- display request result description
Print("------------ResultDescription\r\n",TradeResultDescription(result));
//--- store the order ticket for its deletion at the next handling in OnTick()
if(result.order!=0)
{
//--- delete this order by its ticket at the next OnTick() call
order_ticket=result.order;
Print(" Pending order ticket ",order_ticket,"\r\n");
}
}
else // display the full description for transactions of another type
//--- display description of the received transaction in the Journal
Print("------------TransactionDescription\r\n",TransactionDescription(trans));

//---
}
//+------------------------------------------------------------------+
//| Returns transaction textual description |
//+------------------------------------------------------------------+
string TransactionDescription(const MqlTradeTransaction &trans)
{
//---
string desc=EnumToString(trans.type)+"\r\n";
desc+="Symbol: "+trans.symbol+"\r\n";
desc+="Deal ticket: "+(string)trans.deal+"\r\n";

© 2000-2025, MetaQuotes Ltd.


972 Constants, Enumerations and Structures

desc+="Deal type: "+EnumToString(trans.deal_type)+"\r\n";


desc+="Order ticket: "+(string)trans.order+"\r\n";
desc+="Order type: "+EnumToString(trans.order_type)+"\r\n";
desc+="Order state: "+EnumToString(trans.order_state)+"\r\n";
desc+="Order time type: "+EnumToString(trans.time_type)+"\r\n";
desc+="Order expiration: "+TimeToString(trans.time_expiration)+"\r\n";
desc+="Price: "+StringFormat("%G",trans.price)+"\r\n";
desc+="Price trigger: "+StringFormat("%G",trans.price_trigger)+"\r\n";
desc+="Stop Loss: "+StringFormat("%G",trans.price_sl)+"\r\n";
desc+="Take Profit: "+StringFormat("%G",trans.price_tp)+"\r\n";
desc+="Volume: "+StringFormat("%G",trans.volume)+"\r\n";
desc+="Position: "+(string)trans.position+"\r\n";
desc+="Position by: "+(string)trans.position_by+"\r\n";
//--- return the obtained string
return desc;
}
//+------------------------------------------------------------------+
//| Returns the trade request textual description |
//+------------------------------------------------------------------+
string RequestDescription(const MqlTradeRequest &request)
{
//---
string desc=EnumToString(request.action)+"\r\n";
desc+="Symbol: "+request.symbol+"\r\n";
desc+="Magic Number: "+StringFormat("%d",request.magic)+"\r\n";
desc+="Order ticket: "+(string)request.order+"\r\n";
desc+="Order type: "+EnumToString(request.type)+"\r\n";
desc+="Order filling: "+EnumToString(request.type_filling)+"\r\n";
desc+="Order time type: "+EnumToString(request.type_time)+"\r\n";
desc+="Order expiration: "+TimeToString(request.expiration)+"\r\n";
desc+="Price: "+StringFormat("%G",request.price)+"\r\n";
desc+="Deviation points: "+StringFormat("%G",request.deviation)+"\r\n";
desc+="Stop Loss: "+StringFormat("%G",request.sl)+"\r\n";
desc+="Take Profit: "+StringFormat("%G",request.tp)+"\r\n";
desc+="Stop Limit: "+StringFormat("%G",request.stoplimit)+"\r\n";
desc+="Volume: "+StringFormat("%G",request.volume)+"\r\n";
desc+="Comment: "+request.comment+"\r\n";
//--- return the obtained string
return desc;
}
//+------------------------------------------------------------------+
//| Returns the textual description of the request handling result |
//+------------------------------------------------------------------+
string TradeResultDescription(const MqlTradeResult &result)
{
//---
string desc="Retcode "+(string)result.retcode+"\r\n";
desc+="Request ID: "+StringFormat("%d",result.request_id)+"\r\n";
desc+="Order ticket: "+(string)result.order+"\r\n";

© 2000-2025, MetaQuotes Ltd.


973 Constants, Enumerations and Structures

desc+="Deal ticket: "+(string)result.deal+"\r\n";


desc+="Volume: "+StringFormat("%G",result.volume)+"\r\n";
desc+="Price: "+StringFormat("%G",result.price)+"\r\n";
desc+="Ask: "+StringFormat("%G",result.ask)+"\r\n";
desc+="Bid: "+StringFormat("%G",result.bid)+"\r\n";
desc+="Comment: "+result.comment+"\r\n";
//--- return the obtained string
return desc;
}

See also

Trade Transaction Types, OnTradeTransaction()

© 2000-2025, MetaQuotes Ltd.


974 Constants, Enumerations and Structures

The Structure for Returning Current Prices (MqlTick)


This is a structure for storing the latest prices of the symbol. It is designed for fast retrieval of the
most requested information about current prices.
struct MqlTick
{
datetime time; // Time of the last prices update
double bid; // Current Bid price
double ask; // Current Ask price
double last; // Price of the last deal (Last)
ulong volume; // Volume for the current Last price
long time_msc; // Time of a price last update in milliseconds
uint flags; // Tick flags
double volume_real; // Volume for the current Last price with greater accuracy
};

The variable of the M qlTick type allows obtaining values of As k, Bid, Last and Volume within a single
call of the S ymbolInfoTick() function.
The parameters of each tick are filled in regardless of whether there are changes compared to the
previous tick. Thus, it is possible to find out a correct price for any moment in the past without the
need to search for previous values at the tick history. For example, even if only a Bid price changes
during a tick arrival, the structure still contains other parameters as well, including the previous As k
price, volume, etc.
You can analyze the tick flags to find out what data have been changed exactly:
· TICK_FLAG_BID – tick has changed a Bid price
· TICK_FLAG_ASK – a tick has changed an As k price
· TICK_FLAG_LAS T – a tick has changed the last deal price
· TICK_FLAG_VOLUM E – a tick has changed a volume
· TICK_FLAG_BUY – a tick is a result of a buy deal
· TICK_FLAG_SELL – a tick is a result of a sell deal
Example:

void OnTick()
{
MqlTick last_tick;
//---
if(SymbolInfoTick(Symbol(),last_tick))
{
Print(last_tick.time,": Bid = ",last_tick.bid,
" Ask = ",last_tick.ask," Volume = ",last_tick.volume);
}
else Print("SymbolInfoTick() failed, error = ",GetLastError());
//---
}

See also

© 2000-2025, MetaQuotes Ltd.


975 Constants, Enumerations and Structures

S tructures and Classes, CopyTicks(), S ymbolInfoTick()

© 2000-2025, MetaQuotes Ltd.


976 Constants, Enumerations and Structures

Economic Calendar structures


This section describes the structures for working with the economic calendar available directly in the
MetaTrader platform. The economic calendar is a ready-made encyclopedia featuring descriptions of
macroeconomic indicators, their release dates and degrees of importance. Relevant values of
macroeconomic indicators are sent to the MetaTrader platform right at the moment of publication and
are displayed on a chart as tags allowing you to visually track the required indicators by countries,
currencies and importance.
Economic calendar functions allow conducting the auto analysis of incoming events according to
custom importance criteria from a perspective of necessary countries /currency pairs.
Country descriptions are set by the M qlCalendarCountry structure. It is used in the
CalendarCountryById() and CalendarCountries() functions
struct MqlCalendarCountry
{
ulong id; // country ID (ISO 3166-1)
string name; // country text name (in the current
string code; // country code name (ISO 3166-1 alph
string currency; // country currency code
string currency_symbol; // country currency symbol
string url_name; // country name used in the mql5.com
};

Event descriptions are set by the M qlCalendarEvent structure. It is used in the CalendarEventById(),
CalendarEventByCountry() and CalendarEventByCurrency() functions
struct MqlCalendarEvent
{
ulong id; // event ID
ENUM_CALENDAR_EVENT_TYPE type; // event type from the ENUM_CALENDAR_
ENUM_CALENDAR_EVENT_SECTOR sector; // sector an event is related to
ENUM_CALENDAR_EVENT_FREQUENCY frequency; // event frequency
ENUM_CALENDAR_EVENT_TIMEMODE time_mode; // event time mode
ulong country_id; // country ID
ENUM_CALENDAR_EVENT_UNIT unit; // economic indicator value's unit of
ENUM_CALENDAR_EVENT_IMPORTANCE importance; // event importance
ENUM_CALENDAR_EVENT_MULTIPLIER multiplier; // economic indicator value multiplie
uint digits; // number of decimal places
string source_url; // URL of a source where an event is
string event_code; // event code
string name; // event text name in the terminal la
};

© 2000-2025, MetaQuotes Ltd.


977 Constants, Enumerations and Structures

Event values are set by the M qlCalendarValue structure. It is used in the CalendarValueById(),
CalendarValueHistoryByEvent(), CalendarValueHistory(), CalendarValueLastByEvent() and
CalendarValueLast() functions
struct MqlCalendarValue
{
ulong id; // value ID
ulong event_id; // event ID
datetime time; // event date and time
datetime period; // event reporting period
int revision; // revision of the published indicato
long actual_value; // actual value multiplied by 10^6 or
long prev_value; // previous value multiplied by 10^6
long revised_prev_value; // revised previous value multiplied
long forecast_value; // forecast value multiplied by 10^6
ENUM_CALENDAR_EVENT_IMPACT impact_type; // potential impact on the currency r
//--- functions checking the values
bool HasActualValue(void) const; // returns true if actual_value is se
bool HasPreviousValue(void) const; // returns true if prev_value is set
bool HasRevisedValue(void) const; // returns true if revised_prev_value
bool HasForecastValue(void) const; // returns true if forecast_value is
//--- functions receiving the values
double GetActualValue(void) const; // returns actual_value or nan if the
double GetPreviousValue(void) const; // returns prev_value or nan if the v
double GetRevisedValue(void) const; // returns revised_prev_value or nan
double GetForecastValue(void) const; // returns forecast_value or nan if t
};

The M qlCalendarValue structure provides methods for checking and setting values from the
actual_value, forecast_value, prev_value and revised_prev_value fields. If no value is specified, the

field stores LONG_MIN (-9223372036854775808).


Please note that the values stored in these field are multiplied by one million. It means that when you
receive values in M qlCalendarValue using functions CalendarValueById, CalendarValueHistoryByEvent,
CalendarValueHistory, CalendarValueLastByEvent and CalendarValueLast, you should check if the field
values are equal to LONG_MIN; if a value is specified in the field, then you should divide the value by
1,000,000 in order to get the desired value. Another method to get the values is to check and to get
values using the functions of the M qlCalendarValue structure.
An example of handling calendar events:

//--- Create a structure to store calendar events with real values instead of integers
struct AdjustedCalendarValue
{
ulong id; // value ID
ulong event_id; // event ID
datetime time; // event date and time
datetime period; // event reporting period
int revision; // revision of the published indicato
double actual_value; // actual value

© 2000-2025, MetaQuotes Ltd.


978 Constants, Enumerations and Structures

double prev_value; // previous value


double revised_prev_value; // revised previous value
double forecast_value; // forecast value
ENUM_CALENDAR_EVENT_IMPACT impact_type; // potential impact on the currency r
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
//--- country code for EU (ISO 3166-1 Alpha-2)
string EU_code="EU";
//--- get all EU event values
MqlCalendarValue values[];
//--- set the boundaries of the interval we take the events from
datetime date_from=D'01.01.2021'; // take all events from 2021
datetime date_to=0; // 0 means all known events, including the ones that have not
//--- request EU event history since 2021
if(!CalendarValueHistory(values, date_from, date_to, EU_code))
{
PrintFormat("Error! Failed to get events for country_code=%s", EU_code);
PrintFormat("Error code: %d", GetLastError());
return;
}
else
PrintFormat("Received event values for country_code=%s: %d",
EU_code, ArraySize(values));
//--- reduce the size of the array for output to the Journal
if(ArraySize(values)>5)
ArrayResize(values, 5);
//--- output event values to the Journal as they are, without checking or converting to actual valu
Print("Output calendar values as they are");
ArrayPrint(values);

//--- check the field values and convert to actual values


//--- option 1 to check and get the values
AdjustedCalendarValue values_adjusted_1[];
int total=ArraySize(values);
ArrayResize(values_adjusted_1, total);
//--- copy the values with checks and adjustments
for(int i=0; i<total; i++)
{
values_adjusted_1[i].id=values[i].id;
values_adjusted_1[i].event_id=values[i].event_id;
values_adjusted_1[i].time=values[i].time;
values_adjusted_1[i].period=values[i].period;
values_adjusted_1[i].revision=values[i].revision;
values_adjusted_1[i].impact_type=values[i].impact_type;

© 2000-2025, MetaQuotes Ltd.


979 Constants, Enumerations and Structures

//--- check values and divide by 1,000,000


if(values[i].actual_value==LONG_MIN)
values_adjusted_1[i].actual_value=double("nan");
else
values_adjusted_1[i].actual_value=values[i].actual_value/1000000.;

if(values[i].prev_value==LONG_MIN)
values_adjusted_1[i].prev_value=double("nan");
else
values_adjusted_1[i].prev_value=values[i].prev_value/1000000.;

if(values[i].revised_prev_value==LONG_MIN)
values_adjusted_1[i].revised_prev_value=double("nan");
else
values_adjusted_1[i].revised_prev_value=values[i].revised_prev_value/1000000.;

if(values[i].forecast_value==LONG_MIN)
values_adjusted_1[i].forecast_value=double("nan");
else
values_adjusted_1[i].forecast_value=values[i].forecast_value/1000000.;
}
Print("The first method to check and get calendar values");
ArrayPrint(values_adjusted_1);

//--- option 2 to check and get the values


AdjustedCalendarValue values_adjusted_2[];
ArrayResize(values_adjusted_2, total);
//--- copy the values with checks and adjustments
for(int i=0; i<total; i++)
{
values_adjusted_2[i].id=values[i].id;
values_adjusted_2[i].event_id=values[i].event_id;
values_adjusted_2[i].time=values[i].time;
values_adjusted_2[i].period=values[i].period;
values_adjusted_2[i].revision=values[i].revision;
values_adjusted_2[i].impact_type=values[i].impact_type;
//--- check and get values
if(values[i].HasActualValue())
values_adjusted_2[i].actual_value=values[i].GetActualValue();
else
values_adjusted_2[i].actual_value=double("nan");

if(values[i].HasPreviousValue())
values_adjusted_2[i].prev_value=values[i].GetPreviousValue();
else
values_adjusted_2[i].prev_value=double("nan");

if(values[i].HasRevisedValue())
values_adjusted_2[i].revised_prev_value=values[i].GetRevisedValue();

© 2000-2025, MetaQuotes Ltd.


980 Constants, Enumerations and Structures

else
values_adjusted_2[i].revised_prev_value=double("nan");

if(values[i].HasForecastValue())
values_adjusted_2[i].forecast_value=values[i].GetForecastValue();
else
values_adjusted_2[i].forecast_value=double("nan");
}
Print("The second method to check and get calendar values");
ArrayPrint(values_adjusted_2);

//--- option 3 to get the values - without checks


AdjustedCalendarValue values_adjusted_3[];
ArrayResize(values_adjusted_3, total);
//--- copy the values with checks and adjustments
for(int i=0; i<total; i++)
{
values_adjusted_3[i].id=values[i].id;
values_adjusted_3[i].event_id=values[i].event_id;
values_adjusted_3[i].time=values[i].time;
values_adjusted_3[i].period=values[i].period;
values_adjusted_3[i].revision=values[i].revision;
values_adjusted_3[i].impact_type=values[i].impact_type;
//--- get values without checks
values_adjusted_3[i].actual_value=values[i].GetActualValue();
values_adjusted_3[i].prev_value=values[i].GetPreviousValue();
values_adjusted_3[i].revised_prev_value=values[i].GetRevisedValue();
values_adjusted_3[i].forecast_value=values[i].GetForecastValue();
}
Print("The third method to get calendar values - without checks");
ArrayPrint(values_adjusted_3);
}
/*
We have received event values for country_code=EU: 1051
Output the calendar values as they are
[id] [event_id] [time] [period] [revision] [actual_value]
[0] 144520 999500001 2021.01.04 12:00:00 2020.12.01 00:00:00 3 55200000
[1] 144338 999520001 2021.01.04 23:30:00 2020.12.29 00:00:00 0 143100000
[2] 147462 999010020 2021.01.04 23:45:00 1970.01.01 00:00:00 0 -9223372036854775808 -9
[3] 111618 999010018 2021.01.05 12:00:00 2020.11.01 00:00:00 0 11000000
[4] 111619 999010019 2021.01.05 12:00:00 2020.11.01 00:00:00 0 3100000
The first method to check and get calendar values
[id] [event_id] [time] [period] [revision] [actual_value] [prev_va
[0] 144520 999500001 2021.01.04 12:00:00 2020.12.01 00:00:00 3 55.20000 55.5
[1] 144338 999520001 2021.01.04 23:30:00 2020.12.29 00:00:00 0 143.10000 143.9
[2] 147462 999010020 2021.01.04 23:45:00 1970.01.01 00:00:00 0 nan
[3] 111618 999010018 2021.01.05 12:00:00 2020.11.01 00:00:00 0 11.00000 10.5
[4] 111619 999010019 2021.01.05 12:00:00 2020.11.01 00:00:00 0 3.10000 3.1
The second method to check and get calendar values

© 2000-2025, MetaQuotes Ltd.


981 Constants, Enumerations and Structures

[id] [event_id] [time] [period] [revision] [actual_value] [prev_va


[0] 144520 999500001 2021.01.04 12:00:00 2020.12.01 00:00:00 3 55.20000 55.5
[1] 144338 999520001 2021.01.04 23:30:00 2020.12.29 00:00:00 0 143.10000 143.9
[2] 147462 999010020 2021.01.04 23:45:00 1970.01.01 00:00:00 0 nan
[3] 111618 999010018 2021.01.05 12:00:00 2020.11.01 00:00:00 0 11.00000 10.5
[4] 111619 999010019 2021.01.05 12:00:00 2020.11.01 00:00:00 0 3.10000 3.1
The third method to get calendar values - without checks
[id] [event_id] [time] [period] [revision] [actual_value] [prev_va
[0] 144520 999500001 2021.01.04 12:00:00 2020.12.01 00:00:00 3 55.20000 55.5
[1] 144338 999520001 2021.01.04 23:30:00 2020.12.29 00:00:00 0 143.10000 143.9
[2] 147462 999010020 2021.01.04 23:45:00 1970.01.01 00:00:00 0 nan
[3] 111618 999010018 2021.01.05 12:00:00 2020.11.01 00:00:00 0 11.00000 10.5
[4] 111619 999010019 2021.01.05 12:00:00 2020.11.01 00:00:00 0 3.10000 3.1
*/

Event frequency is specified in the M qlCalendarEvent structure. Possible values are set in the listing
ENUM_CALENDAR_EVENT_FREQUENCY

ID Description

CALENDAR_FREQUENCY_NONE R elease frequency is not set


CALENDAR_FREQUENCY_WEEK R eleased once a week
CALENDAR_FREQUENCY_MONTH R eleased once a month
CALENDAR_FREQUENCY_QUARTER R eleased once a quarter

CALENDAR_FREQUENCY_YEAR R eleased once a year


CALENDAR_FREQUENCY_DAY R eleased once a day

Event type is specified in the M qlCalendarEvent structure. Possible values are set in the listing
ENUM_CALENDAR_EVENT_TY PE

ID Description

CALENDAR_TYPE_EVENT Event (meeting, speech, etc.)


CALENDAR_TYPE_INDICATOR Indicator
CALENDAR_TYPE_HOLIDAY H oliday

A sector of the economy an event is related to is specified in the M qlCalendarEvent structure. Possible
values are set in the listing ENUM_CALENDAR_EVENT_SECTOR
ID Description

CALENDAR_SECTOR_NONE S ector is not set

© 2000-2025, MetaQuotes Ltd.


982 Constants, Enumerations and Structures

ID Description

CALENDAR_SECTOR_M ARKET Market, exchange


CALENDAR_SECTOR_GDP Gross Domestic Product (GDP)

CALENDAR_SECTOR_JOBS Labor market


CALENDAR_SECTOR_PRICES Prices
CALENDAR_SECTOR_MONEY Money
CALENDAR_SECTOR_TRADE Trading
CALENDAR_SECTOR_GOVERNM ENT Government

CALENDAR_SECTOR_BUS INESS Business

CALENDAR_SECTOR_CONSUM ER Consumption
CALENDAR_SECTOR_HOUS ING H ousing

CALENDAR_SECTOR_TAXES Taxes
CALENDAR_SECTOR_HOLIDAYS H olidays

Event importance is specified in the M qlCalendarEvent structure. Possible values are set in the listing
ENUM_CALENDAR_EVENT_IMPORTANCE

ID Description

CALENDAR_IMPORTANCE_NONE Importance is not set


CALENDAR_IMPORTANCE_LOW Low importance
CALENDAR_IMPORTANCE_MODERATE Medium importance
CALENDAR_IMPORTANCE_HIGH H igh importance

Measurement unit type used in displaying event values is specified in the M qlCalendarEvent structure.
Possible values are set in the listing ENUM_CALENDAR_EVENT_UNIT
ID Description

CALENDAR_UNIT_NONE Measurement unit is not set


CALENDAR_UNIT_PERCENT Percentage
CALENDAR_UNIT_CURRENCY National currency

CALENDAR_UNIT_HOUR H ours

CALENDAR_UNIT_JOB Jobs

CALENDAR_UNIT_RIG Drilling rigs

© 2000-2025, MetaQuotes Ltd.


983 Constants, Enumerations and Structures

ID Description

CALENDAR_UNIT_USD USD

CALENDAR_UNIT_PEOPLE People
CALENDAR_UNIT_MORTGAGE Mortgage loans
CALENDAR_UNIT_VOTE Votes

CALENDAR_UNIT_BARREL Barrels

CALENDAR_UNIT_CUBICFEET Cubic feet


CALENDAR_UNIT_POS ITION Non-commercial net positions

CALENDAR_UNIT_BUILDING Buildings

In some cases, economic parameter values require a multiplier set in the M qlCalendarEvent structure.
Possible multiplier values are set in the listing ENUM_CALENDAR_EVENT_MULTIPLIER
ID Description

CALENDAR_M ULTIPLIER_NONE Multiplier is not set


CALENDAR_M ULTIPLIER_THOUSANDS Thousands
CALENDAR_M ULTIPLIER_MILLIONS Millions
CALENDAR_M ULTIPLIER_BILLIONS Billions

CALENDAR_M ULTIPLIER_TRILLIONS Trillions

Event's potential impact on a national currency rate is indicated in the M qlCalendarValue structure.
Possible values are set in the listing ENUM_CALENDAR_EVENT_IMPACT
ID Description

CALENDAR_IMPACT_NA Impact is not set


CALENDAR_IMPACT_POS ITIVE Positive impact
CALENDAR_IMPACT_NEGATIVE Negative impact

Event time is specified in the M qlCalendarEvent structure. Possible values are set in the listing
ENUM_CALENDAR_EVENT_TIMEMODE

ID Description

CALENDAR_TIM EMODE_DATETIM E S ource publishes an exact time of an event


CALENDAR_TIM EMODE_DATE Event tak es all day

© 2000-2025, MetaQuotes Ltd.


984 Constants, Enumerations and Structures

ID Description

CALENDAR_TIM EMODE_NOTIM E S ource publishes no time of an event


CALENDAR_TIM EMODE_TENTATIVE S ourcepublishes a day of an event rather than
its exact time. The time is specified upon the
occurrence of the event.

See also

Economic Calendar

© 2000-2025, MetaQuotes Ltd.


985 Constants, Enumerations and Structures

Codes of Errors and Warnings


This section contains the following descriptions :
· R eturn codes of the trade server – analyzing results of the trade request sent by function
OrderS end();
· Compiler warnings – codes of warning messages that appear at compilation (not errors);
· Compilation errors – codes of error messages at an unsuccessful attempt to compile;
· R untime errors – error codes in the execution of mql5-programs, which can be obtained using the
GetLastError() function.

© 2000-2025, MetaQuotes Ltd.


986 Constants, Enumerations and Structures

Return Codes of the Trade Server


Allrequests to execute trade operations are sent as a structure of a trade request M qlTradeRequest
using function OrderS end(). The function execution result is placed to structure M qlTradeResult, whose
retcode field contains the trade server return code.

Code Constant Description

10004 TRADE_RETCODE_REQUOTE R equote

10006 TRADE_RETCODE_REJECT R equest rejected

10007 TRADE_RETCODE_CANCEL R equest canceled by trader

10008 TRADE_RETCODE_PLACED Order placed


10009 TRADE_RETCODE_DONE R equest completed

10010 TRADE_RETCODE_DONE_PARTIAL Only part of the request was completed


10011 TRADE_RETCODE_ERROR R equest processing error
10012 TRADE_RETCODE_TIM EOUT R equest canceled by timeout

10013 TRADE_RETCODE_INVALID Invalid request


10014 TRADE_RETCODE_INVALID_VOLUM E Invalid volume in the request
10015 TRADE_RETCODE_INVALID_PRICE Invalid price in the request
10016 TRADE_RETCODE_INVALID_S TOPS Invalid stops in the request
10017 TRADE_RETCODE_TRADE_DISABLED Trade is disabled
10018 TRADE_RETCODE_M ARKET_CLOSED Market is closed
10019 TRADE_RETCODE_NO_MONEY There is not enough money to complete
the request
10020 TRADE_RETCODE_PRICE_CHANGED Prices changed
10021 TRADE_RETCODE_PRICE_OFF There are no quotes to process the request
10022 TRADE_RETCODE_INVALID_EXPIRATION Invalid order expiration date in the request
10023 TRADE_RETCODE_ORDER_CHANGED Order state changed
10024 TRADE_RETCODE_TOO_M ANY_REQUES TS Too frequent requests
10025 TRADE_RETCODE_NO_CHANGES No changes in request
10026 TRADE_RETCODE_SERVER_DISABLES_AT Autotrading disabled by server
10027 TRADE_RETCODE_CLIENT_DISABLES_AT Autotrading disabled by client terminal
10028 TRADE_RETCODE_LOCKED R equest lock ed for processing
10029 TRADE_RETCODE_FROZEN Order or position frozen
10030 TRADE_RETCODE_INVALID_FILL Invalid order filling type

© 2000-2025, MetaQuotes Ltd.


987 Constants, Enumerations and Structures

Code Constant Description

10031 TRADE_RETCODE_CONNECTION No connection with the trade server


10032 TRADE_RETCODE_ONLY_REAL Operation is allowed only for live accounts
10033 TRADE_RETCODE_LIMIT_ORDERS The number of pending orders has reached
the limit
10034 TRADE_RETCODE_LIMIT_VOLUM E The volume of orders and positions for the
symbol has reached the limit
10035 TRADE_RETCODE_INVALID_ORDER Incorrect or prohibited order type
10036 TRADE_RETCODE_POS ITION_CLOSED Position with the specified
POS ITION_IDENTIFIER has already been
closed
10038 TRADE_RETCODE_INVALID_CLOSE_VOLUM E A close volume exceeds the current
position volume
10039 TRADE_RETCODE_CLOSE_ORDER_EXIS T A close order already exists for a specified
position. This may happen when working in
the hedging system:
· when attempting to close a position with
an opposite one, while close orders for
the position already exist
· when attempting to fully or partially
close a position if the total volume of
the already present close orders and the
newly placed one exceeds the current
position volume
10040 TRADE_RETCODE_LIMIT_POS ITIONS The number of open positions
simultaneously present on an account can
be limited by the server settings. After a
limit is reached, the server returns the
TRADE_RETCODE_LIMIT_POS ITIONS error
when attempting to place an order. The
limitation operates differently depending
on the position accounting type:
· Netting — number of open positions is
considered. W hen a limit is reached, the
platform does not let placing new orders
whose execution may increase the
number of open positions. In fact, the
platform allows placing orders only for
the symbols that already have open
positions. The current pending orders
are not considered since their execution
may lead to changes in the current
positions but it cannot increase their
number.

© 2000-2025, MetaQuotes Ltd.


988 Constants, Enumerations and Structures

Code Constant Description

· H edging — pending orders are


considered together with open positions,
since a pending order activation always
leads to opening a new position. W hen a
limit is reached, the platform does not
allow placing both new market orders for
opening positions and pending orders.
10041 TRADE_RETCODE_REJECT_CANCEL The pending order activation request is
rejected, the order is canceled
10042 TRADE_RETCODE_LONG_ONLY The request is rejected, because the " Only
long positions are allowed " rule is set for
the symbol (POS ITION_TYPE_BUY)
10043 TRADE_RETCODE_SHORT_ONLY The request is rejected, because the " Only
short positions are allowed " rule is set for
the symbol (POS ITION_TYPE_SELL)
10044 TRADE_RETCODE_CLOSE_ONLY The request is rejected, because the " Only
position closing is allowed " rule is set for
the symbol
10045 TRADE_RETCODE_FIFO_CLOSE The request is rejected, because " Position
closing is allowed only by FIFO rule" flag
is set for the trading account
(ACCOUNT_FIFO_CLOSE=true)
10046 TRADE_RETCODE_HEDGE_PROHIBITED The request is rejected, because the
" Opposite positions on a single symbol
are disabled " rule is set for the trading
account. For example, if the account has a
Buy position, then a user cannot open a
S ell position or place a pending sell order.
The rule is only applied to accounts with
hedging accounting system
(ACCOUNT_M ARGIN_MODE=ACCOUNT_M AR
GIN_MODE_RET AIL _HEDGING).

© 2000-2025, MetaQuotes Ltd.


989 Constants, Enumerations and Structures

Compiler Warnings
Compiler warnings are shown for informational purposes only and are not error messages.

Code Description

21 Incomplete record of a date in the datetime string


22 W rong number in the datetime string for the date. Requirements :
Year 1970 <= X <= 3000
Month 0 <X <= 12
Day 0 <X <= 31/30/28 (29 )....

23 W rong number of datetime string for time. Requirements :


H our 0 <= X <24
Minute 0 <= X <60
24 Invalid color in RGB format: one of RGB components is less than 0 or greater than
255

25 Unk nown character of the escape sequences.


Known: \n \r \t \\ \" \' \X \x

26 Too large volume of local variables (> 512Kb) of the function, reduce the number
29 Enumeration already defined (duplication) - members will be added to the first
definition
30 Overriding macro
31 The variable is declared but is not used anywhere
32 Constructor must be of void type
33 Destructor must be of void type
34 Constant does not fit in the range of integers (X> _UI64_M AX | | X <_I64_MIN) and
will be converted to the double type
35 Too long HEX - more than 16 significant characters (senior nibbles are cut)
36 No nibbles in HEX string "0x"
37 No function - nothing to be performed
38 A non-initialized variable is used
41 Function has no body, and is not called
43 Possible loss of data at typecasting. Example: int x = (double) z;
44 Loss of accuracy (of data) when converting a constant. Example: int x = M _PI
45 Difference between the signs of operands in the operations of comparison.
Example: (char) c1> (uchar) c2

46 Problems with function importing - declaration of #import is required or import of


functions is closed

© 2000-2025, MetaQuotes Ltd.


990 Constants, Enumerations and Structures

Code Description

47 Too large description - extra characters will not be included in the executable file
48 The number of indicator buffers declared is less than required
49 No color to plot a graphical series in the indicator
50 No graphical series to draw the indicator
51 'OnS tart' handler function not found in the script
52 'OnS tart' handler function is defined with wrong parameters
53 'OnS tart' function can be defined only in a script
54 'OnInit' function is defined with wrong parameters
55 'OnInit' function is not used in scripts
56 'OnDeinit' function is defined with wrong parameters
57 'OnDeinit' function is not used in scripts
58 Two 'OnCalculate' functions are defined. OnCalculate () at one price array will be
used
59 Overfilling detected when calculating a complex integer constant
60 Probably, the variable is not initialized.
61 This declaration makes it impossible to refer to the local variable declared on the
specified line
62 This declaration makes it impossible to refer to the global variable declared on the
specified line
63 Cannot be used for static allocated array
64 This variable declaration hides predefined variable
65 The value of the expression is always true/false
66 Using a variable or bool type expression in mathematical operations is unsafe
67 The result of applying the unary minus operator to an unsigned ulong type is
undefined
68 The version specified in the #property version property is unacceptable for the
Market section; the correct format of #property version id "XXX.YYY"
69 Empty controlled statement found

70 Invalid function return type or incorrect parameters during declaration of the event
handler function
71 An implicit cast of structures to one type is required
72 This declaration makes direct access to the member of a class declared in the
specified string impossible. Access will be possible only with the scope resolution
operation ::

© 2000-2025, MetaQuotes Ltd.


991 Constants, Enumerations and Structures

Code Description

73 Binary constant is too big, high-order digits will be truncated


74 Parameter in the method of the inherited class has a different const modifier, the
derived function has overloaded the parent function
75 Negative or too large shift value in shift bitwise operation, execution result is
undefined
76 Function must return a value
77 void function returns a value
78 Not all control paths return a value
79 Expressions are not allowed on a global scope
80 Check operator precedence for possible error; use parentheses to clarify precedence
81 Two OnCalCulate() are defined. OHLC version will be used
82 S truct has no members, size assigned to 1 byte
83 R eturn value of the function should be checked
84 R esource indicator is compiled for debugging. That slows down the performance.
Please recompile the indicator to increase performance
85 Too great character code in the string, must be in the range 0 to 65535
86 Unrecognized character in the string
87 No indicator window property (setting the display in the main window or a
subwindow) is defined. Property #property indicator_chart_window is applied

© 2000-2025, MetaQuotes Ltd.


992 Constants, Enumerations and Structures

Compilation Errors
MetaEdtior 5 shows error messages about the program errors detected by the built-in compiler during
compilation. The list of these errors is given below in table. To compile a source code into an
executable one, press F7. Programs that contain errors cannot be compiled until the errors identified
by the compiler are eliminated.

Code Description

100 File reading error


101 Error of opening an *. EX5 for writing
103 Not enough free memory to complete compilation
104 Empty syntactic unit unrecognized by compiler

105 Incorrect file name in #include


106 Error accessing a file in #include (probably the file does not exist)
108 Inappropriate name for #define
109 Unk nown command of preprocessor (valid #include, #define, #property, #import)
110 S ymbol unk nown to compiler
111 Function not implemented (description is present, but no body)
112 Double quote (" ) omitted
113 Opening angle bracket (<) or double quote (" ) omitted
114 S ingle quote (') omitted
115 Closing angle bracket ">" omitted
116 Type not specified in declaration
117 No return operator or return is found not in all branches of the implementation
118 Opening bracket of call parameters was expected
119 Error writing EX5
120 Invalid access to an array
121 The function is not of void type and the return operator must return a value
122 Incorrect declaration of the destructor
123 Colon ":" is missing
124 Variable is already declared
125 Variable with such identifier already declared
126 Variable name is too long (> 250 characters)
127 S tructure with such identifier already defined

© 2000-2025, MetaQuotes Ltd.


993 Constants, Enumerations and Structures

Code Description

128 S tructure is not defined


129 S tructure member with the same name already defined
130 No such structure member
131 Breached pairing of brackets
132 Opening parenthesis " (" expected
133 Unbalanced braces (no "}" )
134 Difficult to compile (too much branching, internal stack levels are overfilled)
135 Error of file opening for reading
136 Not enough memory to download the source file into memory
137 Variable is expected
138 R eference cannot be initialized

140 Assignment expected (appears at declaration)


141 Opening brace "{" expected
142 Parameter can be a dynamic array only
143 Use of " void" type is unacceptable
144 No pair for " )" or "]" , i.e. " (or" [ " is absent
145 No pair for " (or" [ " , i.e. " ) " or"] " is absent
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 void type not allowed
152 Operator is expected
153 Misuse of break
154 S emicolon ";" expected
155 Comma " ," expected
156 Must be a class type, not struct
157 Expression is expected
158 " non HEX character" found in HEX or too long number (number of digits > 511)
159 S tring-constant has more than 65534 characters

© 2000-2025, MetaQuotes Ltd.


994 Constants, Enumerations and Structures

Code Description

160 Function definition is unacceptable here


161 Unexpected end of program
162 Forward declaration is prohibited for structures
163 Function with this name is already defined and has another return type
164 Function with this name is already defined and has a different set of parameters
165 Function with this name is already defined and implemented
166 Function overload for this call was not found
167 Function with a return value of void type cannot return a value
168 Function is not defined
170 Value is expected
171 In case expression only integer constants are valid
172 The value of case in this switch is already used
173 Integer is expected
174 In #import expression file name is expected
175 Expressions are not allowed on global level
176 Omitted parenthesis " )" before ";"
177 To the left of equality sign a variable is expected
178 The result of expression is not used
179 Declaring of variables is not allowed in case
180 Implicit conversion from a string to a number
181 Implicit conversion of a number to a string
182 Ambiguous call of an overloaded function (several overloads fit)
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 initialized variable
187 A constant for case expected
188 A constant expression required
189 A constant variable cannot be changed
190 Closing bracket or a comma is expected (declaring array member)

© 2000-2025, MetaQuotes Ltd.


995 Constants, Enumerations and Structures

Code Description

191 Enumerator identifier already defined


192 Enumeration cannot have access modifiers (const, extern, static)
193 Enumeration member 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 Name of enumeration member expected
197 Integer expression expected
198 Division by zero in constant expression
199 W rong number of parameters in the function
200 Parameter by reference must be a variable
201 Variable of the same type to pass by reference expected
202 A constant variable cannot be passed by a non-constant reference
203 R equires a positive integer constant
204 Failed to access protected class member
205 Import already defined in another way
208 Executable file not created

209 'OnCalculate' entry point not found for the indicator


210 The continue operation can be used only inside a loop
211 Error accessing private (closed) class member
213 Method of structure or class is not declared
214 Error accessing private (closed) class method
216 Copying of structures with objects is not allowed
218 Index out of array range
219 Array initialization in structure or class declaration not allowed
220 Class constructor cannot have parameters
221 Class destructor can not have parameters
222 Class method or structure with the same name and parameters have already been
declared
223 Operand expected
224 Class method or structure with the same name exists, but with different
parameters (declaration!=implementation)

© 2000-2025, MetaQuotes Ltd.


996 Constants, Enumerations and Structures

Code Description

225 Imported function is not described


226 ZeroMemory() is not allowed for objects with protected members or inheritance
227 Ambiguous call of the overloaded function (exact match of parameters for several
overloads)
228 Variable name expected

229 A reference cannot be declared in this place


230 Already used as the enumeration name
232 Class or structure expected
235 Cannot call 'delete' operator to delete the array
236 Operator ' while' expected
237 Operator 'delete' must have a pointer
238 There is 'default' for this 'switch' already
239 S yntax error
240 Escape-sequence can occur only in strings (starts with '\')
241 Array required - s quare brack et '[' does not apply to an array, or non arrays are
passed as array parameters
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 the program)
246 Conversion of the parameter is not allowed
247 Incorrect use of the 'delete' operator
248 It's not allowed to declare a pointer to a reference
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 S tructure declaration in the list of parameter is not allowed
252 Invalid operation of typecasting
253 A pointer can be declared only for a class or structure
256 Undeclared identifier

257 Executable code optimizer error


258 Executable code generation error

© 2000-2025, MetaQuotes Ltd.


997 Constants, Enumerations and Structures

Code Description

260 Invalid expression for the 'switch' operator


261 Pool of string constants overfilled, simplify program
262 Cannot convert to enumeration
263 Do not use 'virtual' for data (members of a class or structure)
264 Cannot call protected method of class
265 Overridden virtual functions return a different type
266 Class cannot be inherited from a structure
267 S tructure cannot be inherited from a class
268 Constructor cannot be virtual (virtual specifier is not allowed)
269 Method of structure cannot be virtual
270 Function must have a body
271 Overloading of system functions (terminal functions) is prohibited
272 Const specifier is invalid for functions that are not members of a class or structure
274 Not allowed to change class members in constant method
276 Inappropriate initialization sequence
277 Missed default value for the parameter (specific declaration of default parameters)
278 Overriding the default parameter (different values in declaration and
implementation)
279 Not allowed to call non-constant method for a constant object
280 An object is necessary for accessing members (a dot for a non class /structure is
specified)
281 The name of an already declared structure cannot be used in declaration
284 Unauthorized conversion (at closed inheritance)

285 S tructures and arrays cannot be used as input variables


286 Const specifier is not valid for constructor/destructor
287 Incorrect string expression for a datetime
288 Unk nown property (#property)

289 Incorrect value of a property


290 Invalid index for a property in #property
291 Call parameter omitted - <func (x,)>
293 Object must be passed by reference

© 2000-2025, MetaQuotes Ltd.


998 Constants, Enumerations and Structures

Code Description

294 Array must be passed by reference

295 Function was declared as exportable


296 Function was not declared as exportable
297 It is prohibited to export imported function
298 Imported function cannot have this parameter (prohibited to pass a pointer, class
or structure containing a dynamic array, pointer, class, etc.)
299 Must be a class
300 #import was not closed
302 Type mismatch
303 Extern variable is already initialized
304 No exported function or entry point found
305 Explicit constructor call is not allowed
306 Method was declared as constant
307 Method was not declared as constant
308 Incorrect size of the resource file
309 Incorrect resource name
310 R esource file opening error
311 R esource file reading error
312 Unk nown resource type

313 Incorrect path to the resource file


314 The specified resource name is already used
315 Argument expected for the function-like macro
316 Unexpected symbol in macro definition
317 Error in formal parameters of the macro
318 Invalid number of parameters for a macro
319 Too many parameters for a macro
320 Too complex, simplify the macro
321 Parameter for EnumToS tring() can be only an enumeration
322 The resource name is too long
323 Unsupported image format (only BMP with 24 or 32 bit color depth is supported)
324 An array cannot be declared in operator

© 2000-2025, MetaQuotes Ltd.


999 Constants, Enumerations and Structures

Code Description

325 The function can be declared only in the global scope


326 The declaration is not allowed for the current scope
327 Initialization of static variables with the values of local variables is not allowed
328 Illegal declaration of an array of objects that do not have a default constructor
329 Initialization list allowed only for constructors
330 No function definition after initialization list
331 Initialization list is empty
332 Array initialization in a constructor is not allowed
333 Initializing members of a parent class in the initialization list is not allowed
334 Expression of the integer type expected
335 Memory required for the array exceeds the maximum value
336 Memory required for the structure exceeds the maximum value
337 Memory required for the variables declared on the global level exceeds the
maximum value
338 Memory required for local variables exceeds the maximum value
339 Constructor not defined
340 Invalid name of the icon file
341 Could not open the icon file at the specified path
342 The icon file is incorrect and is not of the ICO format
343 R einitialization of a member in a class /structure constructor using the initialization
list
344 Initialization of static members in the constructor initialization list is not allowed
345 Initialization of a non-static member of a class /structure on a global level is not
allowed
346 The name of the class /structure method matches the name of an earlier declared
member
347 The name of the class /structure member matches the name of an earlier declared
method
348 Virtual function cannot be declared as static
349 The const modifier is not allowed for static functions
350 Constructor or destructor cannot be static
351 Non-static member/method of a class or a structure cannot be accessed from a
static function

© 2000-2025, MetaQuotes Ltd.


1000 Constants, Enumerations and Structures

Code Description

352 An overload operation (+,-,[],++,-- etc.) is expected after the operator keyword
353 Not all operations can be overloaded in MQL5
354 Definition does not match declaration
355 An invalid number of parameters is specified for the operator
356 Event handling function not found
357 Method cannot be exported
358 A pointer to the constant object cannot be normalized by a non-constant object
359 Class templates are not supported yet
360 Function template overload is not supported yet
361 Function template cannot be applied

362 Ambiguous parameter in function template (several parameter types can be


applied)
363 Unable to determine the parameter type, by which the function template argument
should be normalized
364 Incorrect number of parameters in the function template
365 Function template cannot be virtual

366 Function templates cannot be exported


367 Function templates cannot be imported
368 S tructures containing the objects are not allowed
369 S tring arrays and structures containing the objects are not allowed
370 A static class /structure member must be explicitly initialized
371 Compiler limitation: the string cannot contain more than 65 535 characters
372 Inconsistent #ifdef/#endif
373 Object of class cannot be returned, copy constructor not found
374 Non-static members and methods cannot be used
375 OnTesterInit() impossible to use without OnTesterDeinit()
376 R edefinition of formal parameter '%s '
377 Macro __FUNCS IG__ and __FUNCTION__ cannot appear outside of a function body
378 Invalid returned type. For example, this error will be produced for functions
imported from DLL that return structure or pointer.
379 Template usage error
380 Not used

© 2000-2025, MetaQuotes Ltd.


1001 Constants, Enumerations and Structures

Code Description

381 Illegal syntax when declaring pure virtual function, only "=NULL" or "=0" are allowed
382 Only virtual functions can be declared with the pure-specifier ("=NULL" or "=0" )
383 Abstract class cannot be instantiated
384 A pointer to a user-defined type should be applied as a target type for dynamic
casting using the dynamic_cast operator
385 " Pointer to function" type is expected
386 Pointers to methods are not supported
387 Error – cannot define the type of a pointer to function
388 Type cast is not available due to private inheritance
389 A variable with const modifier should be initialized during declaration
393 Only methods with public access can be declared in an interface
394 Invalid nesting of an interface inside of another interface
395 An interface can only be derived from another interface
396 An interface is expected
397 Interfaces only support public inheritance
398 An interface cannot contain members

399 Interface objects cannot be created directly, only use inheritance


400 A specifier cannot be used in a forward declaration
401 Inheritance from the class is impossible, since it is declared with the final specifier
402 Cannot redefine a method declared with the final specifier
403 The final specifier can be applied only to virtual functions
404 The method marked by the override specifier actually does not override any base
class function
405 A specifier is not allowed in defining a function, but only in declaring
406 Cannot cast the type to the specified one
407 The type cannot be used for a resource variable
408 Error in the project file
409 Cannot be used as a union member
410 Ambiguous choice for the name, the usage context should be explicitly defined
411 The structure cannot be used from DLL
412 Cannot call a function marked by the delete specifier

© 2000-2025, MetaQuotes Ltd.


1002 Constants, Enumerations and Structures

Code Description

413 MQL4 is not supported. To compile this program, use MetaEditor from your
MetaTrader 4 installation folder

© 2000-2025, MetaQuotes Ltd.


1003 Constants, Enumerations and Structures

Runtime Errors
GetLastError() is the function that returns the last error code that is stored in the predefined variable
_LastError. This value can be reset to zero by the R esetLastError() function.

Constant Code Description

ERR_SUCCESS 0 The operation completed


successfully
ERR_INT ERNAL _ERR OR 4001 Unexpected internal error

ERR_WR ONG_INT ERNAL _PARAM ET ER 4002 W rong parameter in the inner call
of the client terminal function
ERR_INVALID_PARAM ET ER 4003 W rongparameter when calling the
system function
ERR_NOT _ENOUGH_M EMORY 4004 Not enough memory to perform
the system function
ERR_S T RUCT _W IT H OBJECT S_OR CL ASS 4005 The structure contains objects of
strings and/or dynamic arrays
and/or structure of such objects
and/or classes
ERR_INVALID_ARRAY 4006 Array ofa wrong type, wrong size,
or a damaged object of a dynamic
array
ERR_ARRAY_RES IZE_ERR OR 4007 Not enough memory for the
relocation of an array, or an
attempt to change the size of a
static array
ERR_S T R ING_RES IZE_ERR OR 4008 Not enough memory for the
relocation of string
ERR_NOTINITIALIZED_S T R ING 4009 Not initialized string

ERR_INVALID_DAT ETIM E 4010 Invalid date and/or time


ERR_ARRAY_BAD_S IZE 4011 Total amount of elements in the
array cannot exceed 2147483647
ERR_INVALID_POINT ER 4012 W rong pointer
ERR_INVALID_POINT ER_T YPE 4013 W rong type of pointer
ERR_FUNCTION_NOT _ALLOWED 4014 Function is not allowed for call
ERR_RES OUR CE_NAM E_DUPLICAT ED 4015 The names of the dynamic and
the static resource match
ERR_RES OUR CE_NOT _FOUND 4016 R esourcewith this name has not
been found in EX5

© 2000-2025, MetaQuotes Ltd.


1004 Constants, Enumerations and Structures

Constant Code Description

ERR_RES OUR CE_UNSUPPOR T ED_T YPE 4017 Unsupported resource type or its
size exceeds 16 Mb
ERR_RES OUR CE_NAM E_IS_TOO_LONG 4018 The resource name exceeds 63
characters
ERR_M AT H_OVERFLOW 4019 Overflow occurred when
calculating math function
ERR_S L EEP_ERR OR 4020 Out of test end date after calling
S leep()

ERR_PR OGRAM _S TOPPED 4022 Test forcibly stopped from the


outside. For example,
optimization interrupted, visual
testing window closed or testing
agent stopped
ERR_INVALID_T YPE 4023 Invalid type
ERR_INVALID_HANDL E 4024 Invalid handle
ERR_TOO_M ANY_OBJECT S 4025 Object pool filled out
Charts

ERR_CHAR T _WR ONG_ID 4101 W rong chart ID


ERR_CHAR T _NO_REPL Y 4102 Chart does not respond
ERR_CHAR T _NOT _FOUND 4103 Chart not found
ERR_CHAR T _NO_EXPER T 4104 No Expert Advisor in the chart
that could handle the event
ERR_CHAR T _CANNOT _OPEN 4105 Chart opening error
ERR_CHAR T _CANNOT _CHANGE 4106 Failed to change chart symbol and
period
ERR_CHAR T _WR ONG_PARAM ET ER 4107 Error value of the parameter for
the function of working with
charts
ERR_CHAR T _CANNOT _CREAT E_TIM ER 4108 Failed to create timer
ERR_CHAR T _WR ONG_PR OPER T Y 4109 W rong chart property ID
ERR_CHAR T _S CREENSH OT _FAIL ED 4110 Error creating screenshots
ERR_CHAR T _NAVIGAT E_FAIL ED 4111 Error navigating through chart
ERR_CHAR T _T EMPL AT E_FAIL ED 4112 Error applying template
ERR_CHAR T _W INDOW_NOT _FOUND 4113 S ubwindow containing the
indicator was not found

© 2000-2025, MetaQuotes Ltd.


1005 Constants, Enumerations and Structures

Constant Code Description

ERR_CHAR T _INDICATOR_CANNOT _ADD 4114 Error adding an indicator to chart


ERR_CHAR T _INDICATOR_CANNOT _DEL 4115 Error deleting an indicator from
the chart
ERR_CHAR T _INDICATOR_NOT _FOUND 4116 Indicator not found on the
specified chart
Graphical Objects
ERR_OBJECT _ERR OR 4201 Error working with a graphical
object
ERR_OBJECT _NOT _FOUND 4202 Graphical object was not found
ERR_OBJECT _WR ONG_PR OPER T Y 4203 W rong ID of a graphical object
property
ERR_OBJECT _GET DAT E_FAIL ED 4204 Unable to get date corresponding
to the value
ERR_OBJECT _GET VAL UE_FAIL ED 4205 Unable to get value corresponding
to the date
MarketInfo

ERR_M ARKET _UNKNOWN_SYM BOL 4301 Unk nown symbol

ERR_M ARKET _NOT _SEL ECT ED 4302 S ymbol is not selected in


MarketW atch
ERR_M ARKET _WR ONG_PR OPER T Y 4303 W rong identifier of a symbol
property
ERR_M ARKET _L AS TTIM E_UNKNOWN 4304 Time of the last tick is not known
(no ticks)
ERR_M ARKET _SEL ECT _ERR OR 4305 Erroradding or deleting a symbol
in MarketW atch
ERR_M ARKET _SEL ECT _LIMIT 4306 Exceeded the limit of selected
symbols in MarketW atch
ERR_M ARKET _SESS ION_INDEX 4307 W rong session ID when calling the
S ymbolInfoS essionQuote/S ymbolIn
foS essionTrade function
History Access
ERR_H IS TORY_NOT _FOUND 4401 R equested history not found

ERR_H IS TORY_WR ONG_PR OPER T Y 4402 W rong ID of the history property


ERR_H IS TORY_TIM EOUT 4403 Exceeded history request timeout

ERR_H IS TORY_BARS_LIMIT 4404 Number of requested bars limited


by terminal settings

© 2000-2025, MetaQuotes Ltd.


1006 Constants, Enumerations and Structures

Constant Code Description

ERR_H IS TORY_LOAD_ERR ORS 4405 Multiple errors when loading


history
ERR_H IS TORY_S M ALL _BUFFER 4407 R eceiving array is too small to
store all requested data
Global_Variables
ERR_GLOBAL VAR IABL E_NOT _FOUND 4501 Global variable of the client
terminal is not found
ERR_GLOBAL VAR IABL E_EXIS T S 4502 Global variable of the client
terminal with the same name
already exists
ERR_GLOBAL VAR IABL E_NOT _MODIFIED 4503 Global variables were not
modified
ERR_GLOBAL VAR IABL E_CANNOT READ 4504 Cannot read file with global
variable values
ERR_GLOBAL VAR IABL E_CANNOT WR IT E 4505 Cannot write file with global
variable values
ERR_M AIL _SEND_FAIL ED 4510 Email sending failed
ERR_PL AY_S OUND_FAIL ED 4511 S ound playing failed
ERR_MQL5_WR ONG_PR OPER T Y 4512 W rong identifier of the program
property
ERR_T ER MINAL _WR ONG_PR OPER T Y 4513 W rong identifier of the terminal
property
ERR_FTP_SEND_FAIL ED 4514 File sending via ftp failed
ERR_NOTIFICATION_SEND_FAIL ED 4515 Failed to send a notification
ERR_NOTIFICATION_WR ONG_PARAM ET ER 4516 Invalid parameter for sending a
notification – an empty string or
NULL has been passed to the
S endNotification() function

ERR_NOTIFICATION_WR ONG_SETTINGS 4517 W rong settings of notifications in


the terminal (ID is not specified
or permission is not set)
ERR_NOTIFICATION_TOO_FREQUENT 4518 Too frequent sending of
notifications
ERR_FTP_NOSERVER 4519 FTP server is not specified
ERR_FTP_NOLOGIN 4520 FTP login is not specified
ERR_FTP_FIL E_ERR OR 4521 File not found in the MQL5\Files
directory to send on FTP server

© 2000-2025, MetaQuotes Ltd.


1007 Constants, Enumerations and Structures

Constant Code Description

ERR_FTP_CONNECT _FAIL ED 4522 FTP connection failed

ERR_FTP_CHANGEDIR 4523 FTP path not found on server

Custom Indicator Buffers

ERR_BUFFERS_NO_M EMORY 4601 Not enough memory for the


distribution of indicator buffers
ERR_BUFFERS_WR ONG_INDEX 4602 W rong indicator buffer index
Custom Indicator Properties

ERR_CUS TOM _WR ONG_PR OPER T Y 4603 W rong ID of the custom indicator
property
Account

ERR_ACCOUNT _WR ONG_PR OPER T Y 4701 W rong account property ID


ERR_T RADE_WR ONG_PR OPER T Y 4751 W rong trade property ID
ERR_T RADE_DISABL ED 4752 Trading by Expert Advisors
prohibited
ERR_T RADE_POS ITION_NOT _FOUND 4753 Position not found
ERR_T RADE_ORDER_NOT _FOUND 4754 Order not found
ERR_T RADE_DEAL _NOT _FOUND 4755 Deal not found

ERR_T RADE_SEND_FAIL ED 4756 Trade request sending failed


ERR_T RADE_CALC_FAIL ED 4758 Failed to calculate profit or
margin
Indicators

ERR_INDICATOR_UNKNOWN_SYM BOL 4801 Unk nown symbol

ERR_INDICATOR_CANNOT _CREAT E 4802 Indicator cannot be created


ERR_INDICATOR_NO_M EMORY 4803 Not enough memory to add the
indicator
ERR_INDICATOR_CANNOT _APPL Y 4804 The indicator cannot be applied to
another indicator
ERR_INDICATOR_CANNOT _ADD 4805 Error applying an indicator to
chart
ERR_INDICATOR_DAT A_NOT _FOUND 4806 R equested data not found
ERR_INDICATOR_WR ONG_HANDL E 4807 W rong indicator handle
ERR_INDICATOR_WR ONG_PARAM ET ERS 4808 W rong number of parameters
when creating an indicator

© 2000-2025, MetaQuotes Ltd.


1008 Constants, Enumerations and Structures

Constant Code Description

ERR_INDICATOR_PARAM ET ERS_MISS ING 4809 No parameters when creating an


indicator
ERR_INDICATOR_CUS TOM _NAM E 4810 The first parameter in the array
must be the name of the custom
indicator
ERR_INDICATOR_PARAM ET ER_T YPE 4811 Invalid parameter type in the
array when creating an indicator
ERR_INDICATOR_WR ONG_INDEX 4812 W rong index of the requested
indicator buffer
Depth of Market

ERR_BOOKS_CANNOT _ADD 4901 Depth Of Market can not be added


ERR_BOOKS_CANNOT _DEL ET E 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 _SUBS CR IBE 4904 Error in subscribing to receive
new data from Depth Of Market
File Operations

ERR_TOO_M ANY_FIL ES 5001 More than 64 files cannot be


opened at the same time
ERR_WR ONG_FIL ENAM E 5002 Invalid file name
ERR_TOO_LONG_FIL ENAM E 5003 Too long file name
ERR_CANNOT _OPEN_FIL E 5004 File opening error
ERR_FIL E_CACHEBUFFER_ERR OR 5005 Not enough memory for cache to
read
ERR_CANNOT _DEL ET E_FIL E 5006 File deleting error
ERR_INVALID_FIL EHANDL E 5007 A file with this handle was closed,
or was not opening at all
ERR_WR ONG_FIL EHANDL E 5008 W rong file handle
ERR_FIL E_NOTTOWR IT E 5009 The file must be opened for
writing
ERR_FIL E_NOTTOREAD 5010 The file must be opened for
reading
ERR_FIL E_NOT BIN 5011 The file must be opened as a
binary one
ERR_FIL E_NOTT XT 5012 The file must be opened as a text

© 2000-2025, MetaQuotes Ltd.


1009 Constants, Enumerations and Structures

Constant Code Description

ERR_FIL E_NOTT XTOR CSV 5013 The file must be opened as a text
or CSV
ERR_FIL E_NOTCSV 5014 The file must be opened as CSV
ERR_FIL E_READERR OR 5015 File reading error
ERR_FIL E_BINS T R INGS IZE 5016 S tringsize must be specified,
because the file is opened as
binary
ERR_INCOMPATIBL E_FIL E 5017 A text file must be for string
arrays, for other arrays - binary
ERR_FIL E_IS_DIRECTORY 5018 This is not a file, this is a
directory
ERR_FIL E_NOT _EXIS T 5019 File does not exist
ERR_FIL E_CANNOT _REWR IT E 5020 File can not be rewritten

ERR_WR ONG_DIRECTORYNAM E 5021 W rong directory name


ERR_DIRECTORY_NOT _EXIS T 5022 Directory does not exist
ERR_FIL E_ISNOT _DIRECTORY 5023 This is a file, not a directory
ERR_CANNOT _DEL ET E_DIRECTORY 5024 The directory cannot be removed
ERR_CANNOT _CL EAN_DIRECTORY 5025 Failed to clear the directory
(probably one or more files are
blocked and removal operation
failed)
ERR_FIL E_WR IT EERR OR 5026 Failed to write a resource to a file
ERR_FIL E_ENDOFFIL E 5027 Unable to read the next piece of
data from a CSV file
(FileReadS tring, FileReadNumber,
FileR eadDatetime, FileR eadBool),
since the end of file is reached
String Casting

ERR_NO_S T R ING_DAT E 5030 No date in the string


ERR_WR ONG_S T R ING_DAT E 5031 W rong date in the string
ERR_WR ONG_S T R ING_TIM E 5032 W rong time in the string
ERR_S T R ING_TIM E_ERR OR 5033 Error converting string to date
ERR_S T R ING_OUT _OF_M EMORY 5034 Not enough memory for the string
ERR_S T R ING_S M ALL _L EN 5035 The string length is less than
expected

© 2000-2025, MetaQuotes Ltd.


1010 Constants, Enumerations and Structures

Constant Code Description

ERR_S T R ING_TOO_BIGNUM BER 5036 Too large number, more than


ULONG_M AX

ERR_WR ONG_FOR M AT S T R ING 5037 Invalid format string


ERR_TOO_M ANY_FOR M ATT ERS 5038 Amount of format specifiers more
than the parameters
ERR_TOO_M ANY_PARAM ET ERS 5039 Amount of parameters more than
the format specifiers
ERR_WR ONG_S T R ING_PARAM ET ER 5040 Damaged parameter of string type
ERR_S T R INGPOS_OUTOFRANGE 5041 Position outside the string
ERR_S T R ING_ZER OADDED 5042 0 added to the string end, a
useless operation
ERR_S T R ING_UNKNOWNT YPE 5043 Unk nown data type when
converting to a string
ERR_WR ONG_S T R ING_OBJECT 5044 Damaged string object
Operations with Arrays

ERR_INCOMPATIBL E_ARRAYS 5050 Copying incompatible arrays.


S tring array can be copied only to
a string array, and a numeric
array - in numeric array only
ERR_S M ALL _ASSER IES_ARRAY 5051 The receiving array is declared as
AS_SER IES , and it is of
insufficient size
ERR_S M ALL _ARRAY 5052 Too small array, the starting
position is outside the array
ERR_ZER OS IZE_ARRAY 5053 An array of zero length
ERR_NUM BER_ARRAYS_ONL Y 5054 Must be a numeric array
ERR_ONEDIM _ARRAYS_ONL Y 5055 Must be a one-dimensional array
ERR_SER IES_ARRAY 5056 Timeseries cannot be used
ERR_DOUBL E_ARRAY_ONL Y 5057 Must be an array of type double
ERR_FLOAT _ARRAY_ONL Y 5058 Must be an array of type float
ERR_LONG_ARRAY_ONL Y 5059 Must be an array of type long
ERR_INT _ARRAY_ONL Y 5060 Must be an array of type int
ERR_SH OR T _ARRAY_ONL Y 5061 Must be an array of type short
ERR_CHAR_ARRAY_ONL Y 5062 Must be an array of type char
ERR_S T R ING_ARRAY_ONL Y 5063 S tring array only

© 2000-2025, MetaQuotes Ltd.


1011 Constants, Enumerations and Structures

Constant Code Description

Operations with OpenCL

ERR_OPENCL _NOT _SUPPOR T ED 5100 OpenCL functions are not


supported on this computer
ERR_OPENCL _INT ERNAL 5101 Internal error occurred when
running OpenCL
ERR_OPENCL _INVALID_HANDL E 5102 Invalid OpenCL handle
ERR_OPENCL _CONT EXT _CREAT E 5103 Error creating the OpenCL context
ERR_OPENCL _QUEUE_CREAT E 5104 Failedto create a run queue in
OpenCL
ERR_OPENCL _PR OGRAM _CREAT E 5105 Erroroccurred when compiling an
OpenCL program
ERR_OPENCL _TOO_LONG_KERNEL _NAM E 5106 Too long kernel name (OpenCL
k ernel)

ERR_OPENCL _KERNEL _CREAT E 5107 Error creating an OpenCL kernel


ERR_OPENCL _SET _KERNEL _PARAM ET ER 5108 Error occurred when setting
parameters for the OpenCL kernel
ERR_OPENCL _EXECUT E 5109 OpenCL program runtime error
ERR_OPENCL _WR ONG_BUFFER_S IZE 5110 Invalid size of the OpenCL buffer
ERR_OPENCL _WR ONG_BUFFER_OFFSET 5111 Invalid offset in the OpenCL
buffer
ERR_OPENCL _BUFFER_CREAT E 5112 Failed to create an OpenCL buffer
ERR_OPENCL _TOO_M ANY_OBJECT S 5113 Too many OpenCL objects
ERR_OPENCL _SEL ECT DEVICE 5114 OpenCL device selection error
Working with databases

ERR_DAT ABASE_INT ERNAL 5120 Internal database error


ERR_DAT ABASE_INVALID_HANDL E 5121 Invalid database handle
ERR_DAT ABASE_TOO_M ANY_OBJECT S 5122 Exceeded the maximum
acceptable number of Database
objects
ERR_DAT ABASE_CONNECT 5123 Database connection error

ERR_DAT ABASE_EXECUT E 5124 R equest execution error

ERR_DAT ABASE_PREPARE 5125 R equest generation error

ERR_DAT ABASE_NO_MORE_DAT A 5126 No more data to read

© 2000-2025, MetaQuotes Ltd.


1012 Constants, Enumerations and Structures

Constant Code Description

ERR_DAT ABASE_S T EP 5127 Failed to move to the next


request entry
ERR_DAT ABASE_NOT _READY 5128 Data for reading request results
are not ready yet
ERR_DAT ABASE_BIND_PARAM ET ERS 5129 Failed to auto substitute
parameters to an S QL request
Operations with WebRequest

ERR_WEBREQUES T _INVALID_ADDRESS 5200 Invalid URL


ERR_WEBREQUES T _CONNECT _FAIL ED 5201 Failed to connect to specified URL
ERR_WEBREQUES T _TIM EOUT 5202 Timeout exceeded
ERR_WEBREQUES T _REQUES T _FAIL ED 5203 H TTP request failed

Operations with network (sockets)

ERR_NET S OCKET _INVALIDHANDL E 5270 Invalid socket handle passed to


function
ERR_NET S OCKET _TOO_M ANY_OPENED 5271 Too many open sockets (max 128)
ERR_NET S OCKET _CANNOT _CONNECT 5272 Failed to connect to remote host
ERR_NET S OCKET _IO_ERR OR 5273 Failed to send/receive data from
socket
ERR_NET S OCKET _HANDSHAKE_FAIL ED 5274 Failed to establish secure
connection (TLS Handshake)
ERR_NET S OCKET _NO_CER TIFICAT E 5275 No data on certificate protecting
the connection
Custom Symbols

ERR_NOT _CUS TOM _SYM BOL 5300 A custom symbol must be


specified
ERR_CUS TOM _SYM BOL _WR ONG_NAM E 5301 The name of the custom symbol is
invalid. The symbol name can only
contain Latin letters without
punctuation, spaces or special
characters (may only contain " ." ,
"_" , "&" and "#" ). It is not
recommended to use characters
<, >, :, " , /,\ , |, ?, *.

ERR_CUS TOM _SYM BOL _NAM E_LONG 5302 The name of the custom symbol is
too long. The length of the symbol
name must not exceed 32
characters including the ending 0
character

© 2000-2025, MetaQuotes Ltd.


1013 Constants, Enumerations and Structures

Constant Code Description

ERR_CUS TOM _SYM BOL _PAT H_LONG 5303 The path of the custom symbol is
too long. The path length should
not exceed 128 characters
including " Custom\\" , the symbol
name, group separators and the
ending 0
ERR_CUS TOM _SYM BOL _EXIS T 5304 A custom symbol with the same
name already exists
ERR_CUS TOM _SYM BOL _ERR OR 5305 Error occurred while creating,
deleting or changing the custom
symbol
ERR_CUS TOM _SYM BOL _SEL ECT ED 5306 Youare trying to delete a custom
symbol selected in Market W atch
ERR_CUS TOM _SYM BOL _PR OPER T Y_WR ONG 5307 An invalid custom symbol property
ERR_CUS TOM _SYM BOL _PARAM ET ER_ERR OR 5308 A wrong parameter while setting
the property of a custom symbol
ERR_CUS TOM _SYM BOL _PARAM ET ER_LONG 5309 A too long string parameter while
setting the property of a custom
symbol
ERR_CUS TOM _TICKS_WR ONG_ORDER 5310 Ticks in the array are not
arranged in the order of time
Economic Calendar

ERR_CAL ENDAR_MORE_DAT A 5400 Array size is insufficient for


receiving descriptions of all
values
ERR_CAL ENDAR_TIM EOUT 5401 R equest time limit exceeded

ERR_CAL ENDAR_NO_DAT A 5402 Country is not found


Working with databases

ERR_DAT ABASE_ERR OR 5601 Generic error

ERR_DAT ABASE_LOGIC 5602 S QLite internal logic error

ERR_DAT ABASE_PER M 5603 Access denied


ERR_DAT ABASE_ABOR T 5604 Callback routine requested abort
ERR_DAT ABASE_BUSY 5605 Database file lock ed

ERR_DAT ABASE_LOCKED 5606 Database table lock ed

ERR_DAT ABASE_NOM EM 5607 Insufficient memory for


completing operation

© 2000-2025, MetaQuotes Ltd.


1014 Constants, Enumerations and Structures

Constant Code Description

ERR_DAT ABASE_READONL Y 5608 Attempt to write to readonly


database
ERR_DAT ABASE_INT ERRUPT 5609 Operation terminated by
s qlite3_interrupt()
ERR_DAT ABASE_IOERR 5610 Dis k I/O error
ERR_DAT ABASE_CORRUPT 5611 Database dis k image corrupted
ERR_DAT ABASE_NOT FOUND 5612 Unk nown operation code in
s qlite3_file_control()
ERR_DAT ABASE_FULL 5613 Insertion failed because database
is full
ERR_DAT ABASE_CANTOPEN 5614 Unable to open the database file
ERR_DAT ABASE_PR OTOCOL 5615 Database lock protocol error
ERR_DAT ABASE_EMPT Y 5616 Internal use only
ERR_DAT ABASE_S CHEM A 5617 Database schema changed
ERR_DAT ABASE_TOOBIG 5618 S tring or BLOB exceeds size limit
ERR_DAT ABASE_CONS T RAINT 5619 Abort due to constraint violation
ERR_DAT ABASE_MIS M ATCH 5620 Data type mismatch
ERR_DAT ABASE_MISUSE 5621 Library used incorrectly
ERR_DAT ABASE_NOL FS 5622 Uses OS features not supported
on host
ERR_DAT ABASE_AUT H 5623 Authorization denied

ERR_DAT ABASE_FOR M AT 5624 Not used

ERR_DAT ABASE_RANGE 5625 Bind parameter error, incorrect


index
ERR_DAT ABASE_NOT ADB 5626 File opened that is not database
file
Matrix and Vector Methods

ERR_M AT R IX_INT ERNAL 5700 Internal error of the


matrix/vector executing
subsystem
ERR_M AT R IX_NOT _INITIALIZED 5701 Matrix/vector not initialized
ERR_M AT R IX_INCONS IS T ENT 5702 Inconsistent size of
matrices /vectors in operation
ERR_M AT R IX_INVALID_S IZE 5703 Invalid matrix/vector size

© 2000-2025, MetaQuotes Ltd.


1015 Constants, Enumerations and Structures

Constant Code Description

ERR_M AT R IX_INVALID_T YPE 5704 Invalid matrix/vector type


ERR_M AT R IX_FUNC_NOT _ALLOWED 5705 Function not available for this
matrix/vector
ERR_M AT R IX_CONT AINS_NAN 5706 Matrix/vector contains non-
numbers (Nan/Inf)
ONNX models

ERR_ONNX_INT ERNAL 5800 ONNX internal error


ERR_ONNX_NOT _INITIALIZED 5801 ONNX Runtime API initialization
error
ERR_ONNX_NOT _SUPPOR T ED 5802 Property or value not supported by
MQL5
ERR_ONNX_RUN_FAIL ED 5803 ONNX runtime API run error
ERR_ONNX_INVALID_PARAM ET ERS_COUNT 5804 Invalid number of parameters
passed to OnnxRun
ERR_ONNX_INVALID_PARAM ET ER 5805 Invalid parameter value
ERR_ONNX_INVALID_PARAM ET ER_T YPE 5806 Invalid parameter type
ERR_ONNX_INVALID_PARAM ET ER_S IZE 5807 Invalid parameter size
ERR_ONNX_WR ONG_DIM ENS ION 5808 Tensor dimension not set or
invalid
User errors

ERR_USER_ERR OR_FIRS T 65536 User defined errors start with this


code

See also
Trade S erver Return Codes

© 2000-2025, MetaQuotes Ltd.


1016 Constants, Enumerations and Structures

Input and Output Constants


Constants :
· File opening flags
· File properties
· Positioning inside a file
· Code page usage
· MessageBox

© 2000-2025, MetaQuotes Ltd.


1017 Constants, Enumerations and Structures

File Opening Flags


File opening flag values specify the file access mode. Flags are defined as follows :
Identifier Value Description

FIL E_READ 1 File is opened for reading. Flag is used in FileOpen().


W hen opening a file specification of FIL E_WR IT E and/or
FIL E_READ is required.

FIL E_WR IT E 2 File is opened for writing. Flag is used in FileOpen().


W hen opening a file specification of FIL E_WR IT E and/or
FIL E_READ is required.

FIL E_BIN 4 Binary read/write mode (without string to string


conversion). Flag is used in FileOpen().
FIL E_CSV 8 CSV file (all its elements are converted to strings of the
appropriate type, Unicode or ANS I, and separated by
separator). Flag is used in FileOpen().
FIL E_T XT 16 S imple text file (the same ascsv file, but without taking
into account the separators). Flag is used in FileOpen().
FIL E_ANS I 32 S trings of ANS I type (one byte symbols). Flag is used in
FileOpen().

FIL E_UNICODE 64 S trings of UNICODE type (two byte symbols). Flag is used
in FileOpen().
FIL E_SHARE_READ 128 S hared access for reading from several programs. Flag is
used in FileOpen(), but it does not replace the necessity
to indicate FILE_WRITE and/or the FILE_READ flag when
opening a file.
FIL E_SHARE_WR IT E 256 S hared access for writing from several programs. Flag is
used in FileOpen(), but it does not replace the necessity
to indicate FILE_WRITE and/or the FILE_READ flag when
opening a file.
FIL E_REWR IT E 512 Possibility for the file rewrite using functions FileCopy()
and FileMove(). The file should exist or should be opened
for writing, otherwise the file will not be opened.
FIL E_COMMON 4096 The file path in the common folder of all client terminals
\Terminal\Common\Files. Flag is used in FileOpen(),
FileCopy(), FileMove() and in FileIs Exist() functions.

One or several flags can be specified when opening a file. This is a combination of flags. The
combination of flags is written using the sign of logical OR (|), which is positioned between
enumerated flags. For example, to open a file in CSV format for reading and writing at the same time,
specify the combination FILE_READ|FILE_WRITE|FILE_CSV.
Example:

int filehandle=FileOpen(filename,FILE_READ|FILE_WRITE|FILE_CSV);

© 2000-2025, MetaQuotes Ltd.


1018 Constants, Enumerations and Structures

There are some specific features of work when you specify read and write flags :
· If FILE_READ is specified, an attempt is made to open an existing file. If a file does not exist, file
opening fails, a new file is not created.
· FIL E_READ|FIL E_WR IT E – a new file is created if the file with the specified name does not exist.

· FIL E_WR IT E – the file is created again with a zero size.

W hen opening a file, specification of FIL E_WR IT E and/or FIL E_READ is required.

Flags that define the type of reading of an open file possess priority. The highest flag is FILE_CSV,
then goes FILE_BIN, and FILE_TXT is of lowest priority. Thus, if several flags are specified at the same
time, (FILE_TXT|FILE_CSV or FILE_TXT|FILE_BIN or FILE_BIN|FILE_CSV), the flag with the highest
priority will be used.
Flags that define the type of encoding also have priority. FIL E_UNICODE is of a higher priority than
FIL E_ANS I. S o if you specify combination FIL E_UNICODE|FIL E_ANS I, flag FIL E_UNICODE will be used.

If neither FILE_UNICODE nor FILE_ANS I is indicated, FILE_UNICODE is implied. If neither FILE_CSV, nor
FIL E_BIN, nor FIL E_T XT is specified, FIL E_CSV is implied.

If a file is opened for reading as a text file (FILE_TXT or FILE_CSV), and at the file beginning a special
two-byte indication 0xff,0xfe is found, the encoding flag will be FILE_UNICODE, even if FILE_ANS I is
specified.
See also
File Functions

© 2000-2025, MetaQuotes Ltd.


1019 Constants, Enumerations and Structures

File Properties
The FileGetInteger() function is used for obtaining file properties. The identifier of the required
property from the ENUM _FILE_PROPERTY_INTEGER enumeration is passed to it during call.
ENUM_FILE_PROPERTY _INTEGER

ID ID description

FIL E_EXIS T S Check the existence


FIL E_CREAT E_DAT E Date of creation
FIL E_MODIFY_DAT E Date of the last modification
FIL E_ACCESS_DAT E Date of the last access to the file
FIL E_S IZE File size in bytes

FIL E_POS ITION Position of a pointer in the file


FIL E_END Get the end of file sign
FIL E_LINE_END Get the end of line sign
FIL E_IS_COMMON The file is opened in a shared folder of all terminals (see
FIL E_COMMON)

FIL E_IS_T EXT The file is opened as a text file (see FILE_TXT)
FIL E_IS_BINARY The file is opened as a binary file (see FILE_BIN)
FIL E_IS_CSV The file is opened as CSV (see FILE_CSV)
FIL E_IS_ANS I The file is opened as ANS I (see FILE_ANS I)
FIL E_IS_READABL E The opened file is readable (see FILE_READ)
FIL E_IS_WR IT ABL E The opened file is writable (see FILE_WRITE)

The FileGetInteger() function has two different options of call. In the first option, for getting
properties of a file, its handle is specified, which is obtained while opening the file using the
FileOpen() function. This option allows getting all properties of a file.

The second option of the FileGetInteger() function returns values of file properties by the file name.
Using this option, only the following general properties can be obtained:

· FIL E_EXI S T S – existence of a file with a specified name


· FIL E_CREAT E_DAT E – date of creation of the file with the specified name

· FIL E_MODI FY_DAT E – date of modification of the file with the specified name

· FIL E_ACCESS_DAT E – date of the last access to the file with the specified name

· FIL E_S I ZE – size of the file with the specified name

W hen trying to get properties other than specified above, the second option of FileGetInteger() call
will return an error.

© 2000-2025, MetaQuotes Ltd.


1020 Constants, Enumerations and Structures

Positioning Inside a File


Most of file functions are associated with data read/write operations. At the same time, using the
FileS eek () you can specify the position of a file pointer to a position inside the file, from which the
next read or write operation will be performed. The ENUM _FILE_POS ITION enumeration contains valid
pointer positions, relative to which you can specify the shift in bytes for the next operation.
ENUM_FILE_POSITION

Identifier Description

SEEK_SET File beginning

SEEK_CUR Current position of a file pointer


SEEK_END File end

See also
FileIs Ending, FileIsLineEnding

© 2000-2025, MetaQuotes Ltd.


1021 Constants, Enumerations and Structures

Using a Codepage in String Conversion Operations


W hen converting string variables into arrays of char type and back, the encoding that by default
corresponds to the current ANS I of W indows operating system (CP_ACP) is used in MQL5. If you want
to specify a different type of encoding, it can be set as additional parameter for the
CharArrayToS tring(), S tringToCharArray() and FileOpen() functions.
The table lists the built-in constants for some of the most popular code pages. Not mentioned code
pages can be specified by a code corresponding to the page.
Built-in Constants of Codepages

Constant Value Description

CP_ACP 0 The current W indows ANS I code page.


CP_OEMCP 1 The current system OEM code page.
CP_M ACCP 2 The current system Macintosh code page.
Note: This value is mostly used in earlier created
program codes and is of no use now, since modern
Macintosh computers use Unicode for encoding.
CP_THREAD_ACP 3 The W indows ANS I code page for the current thread.
CP_SYM BOL 42 S ymbol code page

CP_UTF7 65000 UT F-7 code page.


CP_UTF8 65001 UT F-8 code page.

See also
Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1022 Constants, Enumerations and Structures

Constants of the MessageBox Dialog Window


This section contains return codes of the MessageBox() function. If a message window has a Cancel
button, the function returns IDCANCEL, in case if the ES C key or the Cancel button is pressed. If there
is no Cancel button in the message window, the pressing of ES C does not give any effect.

Constant Value Description

I DO K 1 " OK" button has been pressed


IDCANCEL 2 " Cancel" button has been pressed
IDABORT 3 "Abort" button has been pressed
IDRETRY 4 "R etry" 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 define contents and behavior of the dialog window. This
value can be a combination of the following flag groups :

Constant Value Description

M B_OK 0x 00000000 Message window contains only one button: OK.


Default

M B_OKCANCEL 0x 00000001 Message window contains two buttons : OK and


Cancel
M B_ABORTRETRYIGNORE 0x 00000002 Message window contains three buttons : Abort,
R etry and Ignore

M B_YESNOCANCEL 0x 00000003 Message window contains three buttons : Yes,


No and Cancel

M B_YESNO 0x 00000004 Message window contains two buttons : Yes and


No

M B_RETRYCANCEL 0x 00000005 Message window contains two buttons : Retry


and Cancel
M B_CANCELTRYCONTINUE 0x 00000006 Message window contains three buttons :
Cancel, Try Again, Continue

To display an icon in the message window it is necessary to specify additional flags :

© 2000-2025, MetaQuotes Ltd.


1023 Constants, Enumerations and Structures

Constant Value Description

M B_ICONS TOP, 0x 00000010 The S TOP sign icon


M B_ICONERROR,
M B_ICONHAND
M B_ICONQUES TION 0x 00000020 The question sign icon
M B_ICONEXCLAM ATION, 0x 00000030 The exclamation/warning sign icon
M B_ICONWARNING
M B_ICONINFORM ATION, 0x 00000040 The encircled i sign
M B_ICONAS TERISK

Default buttons are defined by the following flags :

Constant Value Description

M B_DEFBUTTON1 0x 00000000 The first button M B_DEFBUTTON1 - is default,


if the other buttons M B_DEFBUTTON2,
M B_DEFBUTTON3, or M B_DEFBUTTON4 are not
specified
M B_DEFBUTTON2 0x 00000100 The second button is default
M B_DEFBUTTON3 0x 00000200 The third button is default
M B_DEFBUTTON4 0x 00000300 The fourth button is default

© 2000-2025, MetaQuotes Ltd.


1024 MQL5 programs

MQL5 Programs
For the mql5-program to operate, it must be compiled (Compile button or F7 key). Compilation should
pass without errors (some warnings are possible; they should be analyzed). At this process, an
executable file with the same name and with EX5 extension must be created in the corresponding
directory, terminal_dir\MQL5\Experts, terminal_dir\MQL5\indicators or terminal_dir\MQL5\scripts.
This file can be run.
Operating features of MQL5 programs are described in the following sections :
· Program running – order of calling predefined event-handlers.
· Testing trading strategies – operating features of MQL5 programs in the S trategy Tester.
· Client terminal events – description of events, which can be processed in programs.
· Call of imported functions – description order, allowed parameters, search details and call agreement
for imported functions.
· R untime errors – getting information about runtime and critical errors.

Expert Advisors,custom indicators and scripts are attached to one of opened charts by Drag'n'Drop
method from the Navigator window.
For an expert Advisor to stop operating, it should be removed from a chart. To do it select "Expert
list" in chart context menu, then select an Expert Advisor from list and click "Remove" button.
Operation of Expert Advisors is also affected by the state of the "AutoTrading" button.
In order to stop a custom indicator, it should be removed from a chart.
Custom indicators and Expert Advisors work until they are explicitly removed from a chart;
information about attached Expert Advisors and Indicators is saved between client terminal sessions.
S criptsare executed once and are deleted automatically upon operation completion or change of the
current chart state, or upon client terminal shutdown. After the restart of the client terminal scripts
are not started, because the information about them is not saved.
Maximum one Expert Advisor, one script and unlimited number of indicators can operate in one chart.
S ervices do not require to be bound to a chart to work and are designed to perform auxiliary functions.
For example, in a service, you can create a custom symbol, open its chart, receive data for it in an
endless loop using the network functions and constantly update it.

© 2000-2025, MetaQuotes Ltd.


1025 MQL5 programs

Program Running
Each script, each service and each Expert Advisor runs in its own separate thread. All indicators
calculated on one symbol, even if they are attached to different charts, work in the same thread.
Thus, all indicators on one symbol share the resources of one thread.
Allother actions associated with a symbol, like processing of ticks and history synchronization, are
also consistently performed in the same thread with indicators. This means that if an infinite action is
performed in an indicator, all other events associated with its symbol will never be performed.
W hen running an Expert Advisor, make sure that it has an actual trading environment and can access
the history of the required symbol and period, and synchronize data between the terminal and the
server. For all these procedures, the terminal provides a start delay of no more than 5 seconds, after
which the Expert Advisor will be started with available data. Therefore, in case there is no connection
to the server, this may lead to a delay in the start of an Expert Advisor.
The below table contains a brief summary of MQL5 programs :

Program Running Note

S ervice A separate thread, the number of A looped service cannot break


threads for services is equal to running of other programs
the number of services
S cript A separate thread, the number of A looped script cannot break
threads for scripts is equal to the running of other programs
number of scripts
Expert Advisor A separate thread, the number of A looped Expert Advisor cannot
threads for Expert Advisors is break running of other programs
equal to the number of Expert
Advisors

Indicator One thread for all indicators on a An infinite loop in one indicator
symbol. The number of threads is will stop all other indicators on
equal to the number of symbols this symbol
with indicators

R ight aftera program is attached to a chart, it is uploaded to the client terminal memory, as well as
global variable are initialized. If some global variable of the class type has a constructor, this
constructor will be called during initialization of global variables.
Afterthat the program is waiting for an event from the client terminal. Each mql5-program should
have at least one event-handler, otherwise the loaded program will not be executed. Event handlers
have predefined names, parameters and return types.

Type Function name Parameters Application Comment

int OnInit none Expert Advisors Init event handler. It


and indicators allows to use the void
return type.

© 2000-2025, MetaQuotes Ltd.


1026 MQL5 programs

Type Function name Parameters Application Comment

void OnDeinit const int reason Expert Advisors Deinit event handler.
and indicators
void OnS tart none scripts and S tart event handler.
services
int OnCalculate const int rates _total, indicators Calculate event
const int handler for all prices.
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 &S pread[]
int OnCalculate const int rates _total, indicators Calculate event
const int handler on the single
prev _calculated, data array.
const int begin, Indicator cannot have
const double &price[] two event handlers
simultaneously.
In this case the only
one event handler will
work on the data
array.
void OnTick none Expert Advisors NewTick event
handler. W hile the
event of a new tick
receipt is being
processed, no other
events of this type
are received.
void OnTimer none Expert Advisors Timer event handler.
and indicators
void OnTrade none Expert Advisors Trade event handler.
double OnTester none Expert Advisors Tester event handler.
void OnChartEvent const int id, Expert Advisors ChartEvent event
const long &lparam, and indicators handler.
const double &dparam,
const string &sparam
void OnBookEvent const string Expert Advisors BookEvent event
&symbol_name and indicators handler.

© 2000-2025, MetaQuotes Ltd.


1027 MQL5 programs

A client terminal sends new events to the corresponding open charts. Events can also be generated by
charts (chart events) or mql5-programs (custom events). Generation of events of creation or deletion
of graphical objects on a chart can be enabled or disabled by setting CHART_EVENT_OBJECT_CREATE
and CHART_EVENT_OBJECT_DELETE chart properties. Each MQL5 program and each chart has its own
queue of events, where all new incoming events are added.

A program receives only events from the chart it runs on. All events are processed one after another in
the order they are received. If a queue already has a NewTick event, or this event is currently being
processed, then the new NewTick event is not placed in the queue of the MQL5 program. S imilarly, if
ChartEvent is already enqueued, or this event is being processed, no new event of this kind is
enqueued. The timer events are handled the same way – if the Timer event is in the queue or being
handled, the new timer event is not enqueued.
Event queues have a limited but sufficient size, so that the queue overflow for well written programs
is unlikely. In case of queue overflow, new events are discarded without queuing.
It is strongly recommended not to use infinite loops to handle events. Possible exceptions are scripts
and services handling a single S tart event.
Libraries do not handle any events.

Functions prohibited in Indicators and Expert Advisors

Indicators, scripts and Expert Advisors are executable programs written in MQL5. They are designed
for different types of tas ks. Therefore there are some restrictions on the use of certain functions,
depending on the type of program. The following functions are prohibited in indicators :
· OrderCalcMargin();
· OrderCalcProfit();
· OrderCheck();
· OrderS end();
· S endFTP();
· S leep();
· ExpertR emove();
· MessageBox().

All functions designed for indicators are prohibited in Expert Advisors and scripts :
· S etIndex Buffer();

· IndicatorS etDouble();
· IndicatorS etInteger();
· IndicatorS etS tring();
· PlotIndexS etDouble();
· PlotIndexS etInteger();
· PlotIndexS etS tring();

© 2000-2025, MetaQuotes Ltd.


1028 MQL5 programs

· PlotIndexGetInteger.
The library is not an independent program and is executed in the context of the MQL5 program that
has called it: script, indicator or Expert Advisor. Accordingly, the above restrictions apply to the called
library.

Functions prohibited in services

S ervicesdo not accept any events, as they are not bound to a chart. The following functions are
prohibited in services :
ExpertR emove();
EventS etMillisecondTimer();
EventS etTimer();
EventKillTimer();
S etIndex Buffer();
IndicatorS etDouble();
IndicatorS etInteger();
IndicatorS etS tring();
PlotIndexS etDouble();
PlotIndexS etInteger();
PlotIndexS etS tring();
PlotIndexGetInteger();

Loading and Unloading of Indicators

Indicators are loaded in the following cases :


· an indicator is attached to a chart;
· terminal start (if the indicator was attached to the chart prior to the shutdown of the terminal);
· loading of a template (if the indicator attached to a chart is specified in the template);
· change of a profile (if the indicator is attached to one of the profile charts);
· change of a symbol and/or timeframe of a chart, to which the indicator is attached;
· change of the account to which the terminal is connected;
· after the successful recompilation of an indicator (if the indicator was attached to a chart);
· change of input parameters of the indicator.

Indicators are unloaded in the following cases :


· when detaching an indicator from a chart;
· terminal shutdown (if the indicator was attached to a chart);
· loading of a template (if an indicator is attached to a chart);

© 2000-2025, MetaQuotes Ltd.


1029 MQL5 programs

· closing of a chart, to which the indicator was attached;


· change of a profile (if the indicator is attached to one of charts of the changed profile);
· change of a symbol and/or timeframe of a chart, to which the indicator is attached;
· change of the account to which the terminal is connected;
· change of input parameters of the indicator.

Loading and Unloading of Expert Advisors

Expert Advisors are loaded in the following cases :


· when attaching an Expert Advisor to a chart;
· terminal start (if the Expert Advisor was attached to the chart prior to the shutdown of the
terminal);
· loading of a template (if the Expert Advisor attached to the chart is specified in the template);
· change of a profile (if the Expert Advisor is attached to the one of the profile charts);
· connection to an account, even if the account number is the same (if the Expert Advisor was
attached to the chart before the authorization of the terminal on the server).

Expert Advisors are unloaded in the following cases :


· when detaching an Expert Advisor from a chart;
· if a new Expert Advisor is attached to a chart, if another Expert Advisor has been attached already,
this Expert Advisor is unloaded.
· terminal shutdown (if the Expert Advisor was attached to a chart);
· loading of a template (if an Expert Advisor is attached to the chart);
· close of a chart, to which the Expert Advisor is attached.
· change of a profile (if the Expert Advisor is attached to one of charts of the changed profile);
· change of the account to which the terminal is connected (if the Expert Advisor was attached to the
chart before the authorization of the terminal on the server);
· calling the ExpertRemove() function.
In case the symbol or timeframe of a chart, to which the Expert Advisor is attached, changes,
Expert Advisors are not loaded or unloaded. In this case client terminal subsequently calls OnDeinit()
handlers on the old symbol/timeframe and OnInit() on the new symbol/timeframe (if they are such),
values of global variables and static variables are not reset. All events, which have been received for
the Expert Advisor before the initialization is completed (OnInit() function) are s kipped.

Loading and Unloading of Scripts

S cripts
are loaded immediately after they are attached to a chart and unloaded immediately after they
complete their operation. OnInit() and OnDeinit() are not called for scripts.
W hen a program is unloaded (deleted from a chart) the client terminal performs deinitialization of
global variables and deletes the events queue. In this case deinitialization means reset of all the

© 2000-2025, MetaQuotes Ltd.


1030 MQL5 programs

string-type variables, deallocation of dynamical array objects and call of their destructors if they are
available.

Loading and Unloading services

S ervicesare loaded right after starting the terminal if they were launched at the moment of the
terminal shutdown. S ervices are unloaded immediately after completing their work.
S erviceshave a single OnS tart() handler, in which you can implement an endless data receiving and
handling loop, for example creating and updating custom symbols using the network functions.
Unlik e Expert Advisors, indicators and scripts, services are not bound to a specific chart, therefore a
separate mechanism is provided to launch them. A new service instance is created in the Navigator
using the "Add S ervice" command. A service instance can be launched, stopped and removed using the
appropriate instance menu. To manage all instances, use the service menu.

For a better understanding of the Expert Advisor operation we recommend to compile the code of the
following Expert Advisor and perform actions of load/unload, template change, symbol change,
timeframe change etc:
Example:

//+------------------------------------------------------------------+
//| TestExpert.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://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("Initialization");
//---
return(INIT_SUCCEEDED);

© 2000-2025, MetaQuotes Ltd.


1031 MQL5 programs

}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print("Deinitialization with reason",reason);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---

}
//+------------------------------------------------------------------+

See also
Client terminal events, Event handlers

© 2000-2025, MetaQuotes Ltd.


1032 MQL5 programs

Trade Permission
Trade Automation
MQL5 language provides a special group of trade functions designed for developing automated trading
systems. Programs developed for automated trading with no human intervention are called Expert
Advisors or trading robots. In order to create an Expert Advisor in MetaEditor, launch MQL5 W izard
and select one of the two options :
· Expert Advisor (template) – allows you to create a template with ready-made event handling
functions that should be supplemented with all necessary functionality by means of programming.
· Expert Advisor (generate) – allows you to develop a full-fledged trading robot simply by selecting the
necessary modules : trading signals module, money management module and trailing stop module.

Trading functions can work only in Expert Advisors and scripts. Trading is not allowed for indicators.

Checking for Permission to Perform Automated Trading


In order to develop a reliable Expert Advisor capable of working without human intervention, it is
necessary to arrange a set of important checks. First, we should programmatically check if trading is
allowed at all. This is a basic check that is indispensable when developing any automated system.

Checking for permission to perform automated trading in the terminal

The terminal settings provide you with an ability to allow or forbid automated trading for all programs.

© 2000-2025, MetaQuotes Ltd.


1033 MQL5 programs

You can switch automated trading option right on the terminal's S tandard panel:

· – automated trading enabled, trading functions in launched applications are allowed


for use.
· – automated trading disabled, running applications are unable to execute trading
functions.
S ample check:

if (!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
Alert("Check if automated trading is allowed in the terminal settings!");

Checking if trading is allowed for a certain running Expert Advisor/script

You can allow or forbid automated trading for a certain program when launching it. To do this, use the
special check box in the program properties.

© 2000-2025, MetaQuotes Ltd.


1034 MQL5 programs

S ample check:

if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
Alert("Check if automated trading is allowed in the terminal settings!");
else
{
if(!MQLInfoInteger(MQL_TRADE_ALLOWED))
Alert("Automated trading is forbidden in the program settings for ",__FILE__);
}

Checking if trading is allowed for any Expert Advisors/scripts for the current
account

Automated trading can be disabled at the trade server side. S ample check:
if(!AccountInfoInteger(ACCOUNT_TRADE_EXPERT))
Alert("Automated trading is forbidden for the account ",AccountInfoInteger(ACCOUNT_LOGIN),
" at the trade server side");

If automated trading is disabled for a trading account, trading operations of Expert Advisors /scripts
are not executed.

Checking if trading is allowed for the current account

In some cases, any trading operations are disabled for a certain trading account – neither manual nor
automated trading can be performed. S ample check when an investor password has been used to
connect to a trading account:
if(!AccountInfoInteger(ACCOUNT_TRADE_ALLOWED))
Comment("Trading is forbidden for the account ",AccountInfoInteger(ACCOUNT_LOGIN),
".\n Perhaps an investor password has been used to connect to the trading account.",
"\n Check the terminal journal for the following entry:",

© 2000-2025, MetaQuotes Ltd.


1035 MQL5 programs

"\n\'",AccountInfoInteger(ACCOUNT_LOGIN),"\': trading has been disabled - investor mode

AccountInfoInteger(ACCOUNT _T RADE_ALLOWED) may return false in the following cases :


· no connection to the trade server. That can be checked using
TerminalInfoInteger(TERMINAL_CONNECTED);
· trading account switched to read-only mode (sent to the archive);
· trading on the account is disabled at the trade server side;
· connection to a trading account has been performed in Investor mode.

See also
Client Terminal Properties, Account Properties, Properties of a Running MQL5 Program

© 2000-2025, MetaQuotes Ltd.


1036 MQL5 programs

Client Terminal Events


Init
Immediately after the client terminal loads a program (an Expert Advisor or custom indicator) and
starts the process of initialization of global variables, the Init event will be sent, which will be
processed by OnInit() event handler, if there is such. This event is also generated after a financial
instrument and/or chart timeframe is changed, after a program is recompiled in MetaEditor, after
input parameters are changed from the setup window of an Expert Advisor or a custom indicator. An
Expert Advisor is also initialized after the account is changed. The Init event is not generated for
scripts.

Deinit
Before global variables are deinitialized and the program (Expert Advisor or custom indicator) is
unloaded, the client terminal sends the Deinit event to the program. Deinit is also generated when the
client terminal is closed, when a chart is closed, right before the security and/or timeframe is
changed, at a successful program re-compilation, when input parameters are changed, and when
account is changed.
The deinitialization reason can be obtained from the parameter, passed to the OnDeinit() function.
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 is not generated for scripts.

Start
S tart is
a special event for launching a script or a service after loading it. It is handled by the OnS tart
function. The S tart event is not passed to EAs and custom indicators.

NewTick
The NewTick event is generated if there are new quotes, it is processed by OnTick() of Expert
Advisors attached. In case when OnTick function for the previous quote is being processed when a new
quote is received, the new quote will be ignored by an Expert Advisor, because the corresponding
event will not enqueued.
Allnew quotes that are received while the program is running are ignored until the OnTick() is
completed. After that the function will run only after a new quote is received. The NewTick event is
generated irrespective of whether automated trade is allowed or not ("Allow/prohibit Auto trading"
button). The prohibition of automated trading denotes only that sending of trade requests from an
Expert Advisor is not allowed, while the Expert Advisor k eeps work ing.

The prohibition of automated trading by pressing the appropriate button will not stop the current
execution of the OnTick() function.

Calculate
The Calculate event is generated only for indicators right after the Init event is sent and at any change
of price data. It is processed by the OnCalculate function.

© 2000-2025, MetaQuotes Ltd.


1037 MQL5 programs

Timer
The Timer event is periodically generated by the client terminal for the Expert Advisor that has
activated the timer by the EventS etTimer function. Usually, this function is called by OnInit. Timer
event processing is performed by the OnTimer function. After the operation of the Expert Advisor is
completed, it is necessary to destroy the timer using the EventKillTimer function, which is usually
called in the OnDeinit function.

Trade
The Trade event is generated when a trade operation is completed on a trade server. The Trade event
is handled by the OnTrade() function for the following trade operations :
· sending, modifying or removing of a pending order;
· cancellation of a pending order with not enough of money or expiration;
· activation of a pending order;
· opening, adding or closing a position (or part of the position);
· modifying of the open position (change stops – S top Loss and/or Take Profit).

TradeTransaction
W hen performing some definite actions on a trade account, its state changes. S uch actions include:
· S ending a trade request from any MQL5 application in the client terminal using OrderS end and
OrderS endAsync functions and its further execution;
· S ending a trade request via the terminal graphical interface and its further execution;
· Pending orders and stop orders activation on the server;
· Performing operations on a trade server side.
The following trade transactions are performed as a result of these actions :
· handling a trade request;
· changing open orders ;
· changing orders history;
· changing deals history;
· changing positions.
For example, when sending a market buy order, it is handled, an appropriate buy order is created for
the account, the order is then executed and removed from the list of the open ones, then it is added
to the orders history, an appropriate deal is added to the history and a new position is created. All
these actions are trade transactions. Arrival of such a transaction at the terminal is a
TradeTransaction event. This event is handled by OnTradeTransaction function.

Tester
The Tester event is generated after testing of an Expert Advisor on history data is over. The event is
handled by the OnTester() function.

© 2000-2025, MetaQuotes Ltd.


1038 MQL5 programs

TesterInit
The TesterInit event is generated with the start of optimization in the strategy tester before the first
optimization pass. The TesterInit event is handled by the OnTesterInit() function.

TesterPass
The TesterPass event is generated when a new data frame is received. The TesterPass event is
handled by the OnTesterPass() function.

TesterDeinit
The TesterDeinit event is generated after the end of optimization of an Expert Advisor in the strategy
tester. The TesterDeinit event is handled by the OnTesterDeinit() function.

ChartEvent
The ChartEvent event is generated by the client terminal when a user is working with a chart:
· k eystrok e, when the chart window is in focus ;
· graphical object created
· graphical object deleted
· mouse press on the graphical object of the chart
· move of the graphical object using the mouse
· end of text editing in LabelEdit.
Also there is a custom event ChartEvent, which can be sent to an Expert Advisor by any mql5 program
by using the EventChartCustom function. The event is processed by the OnChartEvent function.

BookEvent
The BookEvent event is generated by the client terminal after the Depth Of Market is changed; it is
processed by the OnBookEvent function. To start generation of BookEvent for the specified symbol, it
is necessary to subscribe the symbol to this event by using the MarketBookAdd function.
To unsubscribe from BookEvent for a specified symbol, it is necessary to call the MarketBookRelease
function. The BookEvent event is a broadcasting-type event - it means that it is sufficient to subscribe
just one Expert Advisor for this event, and all other Expert Advisors that have the OnBookEvent event
handler, will receive it. That's why it is necessary to analyze the symbol name, which is passed to a
handler as a parameter.
See also
Event handlers, Program running

© 2000-2025, MetaQuotes Ltd.


1039 MQL5 programs

Resources
Using graphics and sound in MQL5 programs
Programs in MQL5 allow working with sound and graphic files :
· PlayS ound() plays a sound file;
· ObjectCreate() allows creating user interfaces using graphical objects OBJ_BITM AP and
OBJ_BITM AP_LABEL.

PlaySound()

Example of call of the PlayS ound() function:


//+------------------------------------------------------------------+
//| Calls standard OrderSend() and plays a sound |
//+------------------------------------------------------------------+
void OrderSendWithAudio(MqlTradeRequest &request, MqlTradeResult &result)
{
//--- send a request to a server
OrderSend(request,result);
//--- if a request is accepted, play sound Ok.wav
if(result.retcode==TRADE_RETCODE_PLACED) PlaySound("Ok.wav");
//--- if fails, play alarm from file timeout.wav
else PlaySound("timeout.wav");
}

The example shows how to play sounds from files 'Ok.wav ' and 'timeout.wav ', which are included into
the standard terminal package. These files are located in the folder terminal_directory\Sounds. Here
terminal_directory is a folder, from which the MetaTrader 5 Client Terminal is started. The location
of the terminal directory can be found out from an mql5 program in the following way:
//--- Folder, in which terminal data are stored
string terminal_path=TerminalInfoString(TERMINAL_PATH);

You can use sound files not only from the folder terminal_directory\Sounds, but also from any
subfolder located in terminal_data_directory\MQL5. You can find out the location of the terminal
data directory from the terminal menu "File" -> " Open Data Folder" or using program method:
//--- Folder, in which terminal data are stored
string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH);

For example, if the Demo.wav sound file is located in terminal_data_directory\MQL5\Files, then call of
PlayS ound() should be written the following way:
//--- play Demo.wav from the folder terminal_directory_data\MQL5\Files\
PlaySound("\\Files\\Demo.wav");

Please note that in the comment the path to the file is written using backslash "\" , and in the function
"\\" is used.

© 2000-2025, MetaQuotes Ltd.


1040 MQL5 programs

W hen specifying the path, always use only the double backslash as a separator, because a single
backslash is a control symbol for the compiler when dealing with constant strings and character
constants in the program source code.
Call PlayS ound() function with NULL parameter to stop playback:
//--- call of PlaySound() with NULL parameter stops playback
PlaySound(NULL);

ObjectCreate()

Example of an Expert Advisor, which creates a graphical label (OBJ_BITM AP_LABEL) using the
ObjectCreate() function.
string label_name="currency_label"; // name of the OBJ_BITMAP_LABEL object
string euro ="\\Images\\euro.bmp"; // path to the file terminal_data_directory\MQL5\Images\
string dollar ="\\Images\\dollar.bmp"; // path to the file terminal_data_directory\MQL5\Images\
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create a button OBJ_BITMAP_LABEL, if it hasn't been created yet
if(ObjectFind(0,label_name)<0)
{
//--- trying to create object OBJ_BITMAP_LABEL
bool created=ObjectCreate(0,label_name,OBJ_BITMAP_LABEL,0,0,0);
if(created)
{
//--- link the button to the left upper corner of the chart
ObjectSetInteger(0,label_name,OBJPROP_CORNER,CORNER_RIGHT_UPPER);
//--- now set up the object properties
ObjectSetInteger(0,label_name,OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,label_name,OBJPROP_YDISTANCE,50);
//--- reset the code of the last error to 0
ResetLastError();
//--- download a picture to indicate the "Pressed" state of the button
bool set=ObjectSetString(0,label_name,OBJPROP_BMPFILE,0,euro);
//--- test the result
if(!set)
{
PrintFormat("Failed to download image from file %s. Error code %d",euro,GetLastError())
}
ResetLastError();
//--- download a picture to indicate the "Unpressed" state of the button
set=ObjectSetString(0,label_name,OBJPROP_BMPFILE,1,dollar);

if(!set)

© 2000-2025, MetaQuotes Ltd.


1041 MQL5 programs

{
PrintFormat("Failed to download image from file %s. Error code %d",dollar,GetLastError(
}
//--- send a command for a chart to refresh so that the button appears immediately without
ChartRedraw(0);
}
else
{
//--- failed to create an object, notify
PrintFormat("Failed to create object OBJ_BITMAP_LABEL. Error code %d",GetLastError());
}
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- delete an object from a chart
ObjectDelete(0,label_name);
}

Creation and setup of the graphical object named currency_label are carried out in the OnInit()
function. The paths to the graphical files are set in global variables euro and dollar, a double backlash
is used for a separator:
string euro ="\\Images\\euro.bmp"; // path to the file terminal_dara_directory\MQL5\Images\
string dollar ="\\Images\\dollar.bmp"; // path to the file terminal_dara_directory\MQL5\Images\

The files are located in the folder terminal_data_directory\MQL5\Images.


Object OBJ_BITM AP_LABEL is actually a button, which displays one of the two images, depending on
the button state (pressed or unpressed): euro.bmp or dollar.bmp.

© 2000-2025, MetaQuotes Ltd.


1042 MQL5 programs

The size of the button with a graphical interface is automatically adjusted to the size of the picture.
The image is changed by a left mouse button click on the OBJ_BITM AP_LABEL object (" Disable
selection" option must be checked in the properties). The OBJ_BITM AP object is created the same
way - it is used for creating the background with a necessary image.
The value of the OBJPROP_BMPFILE property, which is responsible for the appearance of the objects
OBJ_BITM AP and OBJ_BITM AP_LABEL, can be changed dynamically. This allows creating various
interactive user interfaces for mql5 programs.

Including resources to executable files during compilation of mql5


programs
An mql5 program may need a lot of different downloadable resources in the form of image and sound
files. In order to eliminate the need to transfer all these files when moving an executable file in MQL5,
the compiler's directive #resource should be used:
#resource path_to_resource_file

The #resource command tells the compiler that the resource at the specified path
path_to_resource_file should be included into the executable EX5 file. Thus all the necessary images
and sounds can be located directly in an EX5 file, so that there is no need to transfer separately the
files used in it, if you want to run the program on a different terminal. Any EX5 file can contain
resources, and any EX5 program can use resources from another EX5 program.
The files in format BMP and WAV are automatically compressed before including them to an EX5 file.
This denotes that in addition to the creation of complete programs in MQL5, using resources also
allows to reduce the total size of necessary files when using graphics and sounds, as compared to the
usual way of MQL5 program writing.
The resource file size must not exceed 128 Mb.

© 2000-2025, MetaQuotes Ltd.


1043 MQL5 programs

Search for specified resources by a compiler


A resource is inserted using the command #resource "<path to the resource file>"
#resource "<path_to_resource_file>"

The length of the constant string <path_to_resource_file> must not exceed 63 characters.
The compiler searches for a resource at the specified path in the following order:
· if the backslash "\" separator (written as "\\" ) is placed at the beginning of the path, it searches for
the resource relative to the directory terminal_data_directory\MQL5\,
· if there is no backslash, it searches for the resource relative to the location of the source file, in
which the resource is written.
The resource path cannot contain the substrings " ..\\" and ":\\" .
Examples of resource inclusion:
//--- correct specification of resources
#resource "\\Images\\euro.bmp" // euro.bmp is located in terminal_data_directory\MQL5\Images\
#resource "picture.bmp" // picture.bmp is located in the same directory as the source file
#resource "Resource\\map.bmp" // the resource is located in source_file_directory\Resource\map.bmp

//--- incorrect specification of resources


#resource ":picture_2.bmp" // must not contain ":"
#resource "..\\picture_3.bmp" // must not contain ".."
#resource "\\Files\\Images\\Folder_First\\My_panel\\Labels\\too_long_path.bmp" //more than 63 symbo

Use of Resources
Resource name

After a resource is declared using the #resource directive, it can be used in any part of a program. The
name of the resource is its path without a backslash at the beginning of the line, which sets the path
to the resource. To use your own resource in the code, the special sign "::" should be added before the
resource name.
Examples :

//--- examples of resource specification and their names in comments


#resource "\\Images\\euro.bmp" // resource name - Images\euro.bmp
#resource "picture.bmp" // resource name - picture.bmp
#resource "Resource\\map.bmp" // resource name - Resource\map.bmp
#resource "\\Files\\Pictures\\good.bmp" // resource name - Files\Pictures\good.bmp
#resource "\\Files\\Demo.wav"; // resource name - Files\Demo.wav"
#resource "\\Sounds\\thrill.wav"; // resource name - Sounds\thrill.wav"
...

//--- utilization of resources

© 2000-2025, MetaQuotes Ltd.


1044 MQL5 programs

ObjectSetString(0,bitmap_name,OBJPROP_BMPFILE,0,"::Images\\euro.bmp");
...
ObjectSetString(0,my_bitmap,OBJPROP_BMPFILE,0,"::picture.bmp");
...
set=ObjectSetString(0,bitmap_label,OBJPROP_BMPFILE,1,"::Files\\Pictures\\good.bmp");
...
PlaySound("::Files\\Demo.wav");
...
PlaySound("::Sounds\\thrill.wav");

It should be noted that when setting images from a resource to the OBJ_BITM AP and
OBJ_BITM AP_LABEL objects, the value of the OBJPROP_BMPFILE property cannot be modified
manually. For example, for creating OBJ_BITM AP_LABEL we use resources euro.bmp and dollar.bmp.
#resource "\\Images\\euro.bmp"; // euro.bmp is located in terminal_data_directory\MQL5\Images\
#resource "\\Images\\dollar.bmp"; // dollar.bmp is located in terminal_data_directory\MQL5\Images\

W hen viewing the properties of this object, we'll see that the properties BitMap File (On) and BitMap
File (Off) are dimmed and cannot be change manually:

Using the resources of other mql5 programs

There is another advantage of using resources – in any MQL5 program, resources of another EX5 file
can be used. Thus the resources from one EX5 file can be used in many other mql5 programs.
In order to use a resource name from another file, it should be specified as
<path_EX5_file_name>::<resource_name>. For example, suppose the Draw_Triangles _S cript.mq5
script contains a resource to an image in the file triangle.bmp:
#resource "\\Files\\triangle.bmp"

Then its name, for using in the script itself, will look like "Files \triangle.bmp" , and in order to use it,
"::" should be added to the resource name.

© 2000-2025, MetaQuotes Ltd.


1045 MQL5 programs

//--- using the resource in the script


ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"::Files\\triangle.bmp");

In order to use the same resource from another program, e.g. from an Expert Advisor, we need to add
to the resource name the path to the EX5 file relative to terminal_data_directory\MQL5\ and the
name of the script's EX5 file - Draw_Triangles_Script.ex5. S uppose the script is located in the
standard folder terminal_data_directory\MQL5\S cripts \, then the call should be written the following
way:
//--- using a resource from a script in an EA
ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"\\Scripts\\Draw_Triangles_Script.ex5::Files\\tr

If the path to the executable file is not specified when calling the resource from another EX5, the
executable file is searched for in the same folder that contains the program that calls the resource.
This means that if an Expert Advisor calls a resource from Draw_Triangles _S cript.ex5 without
specification of the path, like this :
//--- call script resource in an EA without specifying the path
ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"Draw_Triangles_Script.ex5::Files\\triangle.bmp"

then the file will be searched for in the folder terminal_data_directory\MQL5\Experts \, if the Expert
Advisor is located in terminal_data_directory\MQL5\Experts \.

Working with custom indicators included as resources

One or several custom indicators may be necessary for the operation of MQL5 applications. All of them
can be included into the code of an executable MQL5 program. Inclusion of indicators as resources
simplifies the distribution of applications.
Below is an example of including and using S ampleIndicator.ex5 custom indicator located in
terminal_data_folder \MQL5\Indicators \ directory:

//+------------------------------------------------------------------+
//| SampleEA.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#resource "\\Indicators\\SampleIndicator.ex5"
int handle_ind;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
handle_ind=iCustom(_Symbol,_Period,"::Indicators\\SampleIndicator.ex5");
if(handle_ind==INVALID_HANDLE)
{
Print("Expert: iCustom call: Error code=",GetLastError());
return(INIT_FAILED);

© 2000-2025, MetaQuotes Ltd.


1046 MQL5 programs

}
//--- ...
return(INIT_SUCCEEDED);
}

The case when a custom indicator in OnInit() function creates one or more copies of itself requires
special consideration. Please keep in mind that the resource should be specified in the following way:
<path_EX 5_file_name>::<resource_name>.

For example, if S ampleIndicator.ex5 indicator is included to S ampleEA.ex5 Expert Advisor as a


resource, the path to itself specified when calling iCustom() in the custom indicator's initialization
function looks the following way: "\\Experts \\S ampleEA.ex5::Indicators \\S ampleIndicator.ex5" . W hen
this path is set explicitly, S ampleIndicator.ex5 custom indicator is rigidly connected to S ampleEA.ex5
Expert Advisor losing ability to work independently.

The path to itself can be received using GetRelativeProgramPath() function. The example of its usage
is provided below:
//+------------------------------------------------------------------+
//| SampleIndicator.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_plots 0
int handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- the wrong way to provide a link to itself
//--- string path="\\Experts\\SampleEA.ex5::Indicators\\SampleIndicator.ex5";
//--- the right way to receive a link to itself
string path=GetRelativeProgramPath();
//--- indicator buffers mapping
handle=iCustom(_Symbol,_Period,path,0,0);
if(handle==INVALID_HANDLE)
{
Print("Indicator: iCustom call: Error code=",GetLastError());
return(INIT_FAILED);
}
else Print("Indicator handle=",handle);
//---
return(INIT_SUCCEEDED);
}
///....
//+------------------------------------------------------------------+
//| GetRelativeProgramPath |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1047 MQL5 programs

string GetRelativeProgramPath()
{
int pos2;
//--- get the absolute path to the application
string path=MQLInfoString(MQL_PROGRAM_PATH);
//--- find the position of "\MQL5\" substring
int pos =StringFind(path,"\\MQL5\\");
//--- substring not found - error
if(pos<0)
return(NULL);
//--- skip "\MQL5" directory
pos+=5;
//--- skip extra '\' symbols
while(StringGetCharacter(path,pos+1)=='\\')
pos++;
//--- if this is a resource, return the path relative to MQL5 directory
if(StringFind(path,"::",pos)>=0)
return(StringSubstr(path,pos));
//--- find a separator for the first MQL5 subdirectory (for example, MQL5\Indicators)
//--- if not found, return the path relative to MQL5 directory
if((pos2=StringFind(path,"\\",pos+1))<0)
return(StringSubstr(path,pos));
//--- return the path relative to the subdirectory (for example, MQL5\Indicators)
return(StringSubstr(path,pos2+1));
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double& price[])
{
//--- return value of prev_calculated for next call
return(rates_total);
}

Resource variables
R esources can be declared using the resource variables and treated as if they are variables of the
appropriate type. Declaration format:
#resource path_to_the_resource_file as resource_variable_type resource_variable_name

S ample declarations :

#resource "data.bin" as int ExtData[] // declare the numeric array containing data from

© 2000-2025, MetaQuotes Ltd.


1048 MQL5 programs

#resource "data.bin" as MqlRates ExtData[] // declare the simple structures array containing
//--- strings
#resource "data.txt" as string ExtCode // declare the string containing the data.txt fil
//--- graphical resources
#resource "image.bmp" as bitmap ExtBitmap[] // declare the one-dimensional array containing a
#resource "image.bmp" as bitmap ExtBitmap2[][] // declare the two-dimensional array containing a

In case of such declaration, the resource data can be addressed only via the variable, auto addressing
via "::<rsource name>" does not work.
#resource "\\Images\\euro.bmp" as bitmap euro[][]
#resource "\\Images\\dollar.bmp"
//+------------------------------------------------------------------+
//| OBJ_BITMAP_LABEL object creation function using the resource |
//+------------------------------------------------------------------+
void Image(string name,string rc,int x,int y)
{
ObjectCreate(0,name,OBJ_BITMAP_LABEL,0,0,0);
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
ObjectSetString(0,name,OBJPROP_BMPFILE,rc);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- output the size of the image [width, height] stored in euro resource variable
Print(ArrayRange(euro,1),", ",ArrayRange(euro,0));
//--- change the image in euro - draw the red horizontal stripe in the middle
for(int x=0;x<ArrayRange(euro,1);x++)
euro[ArrayRange(euro,1)/2][x]=0xFFFF0000;
//--- create the graphical resource using the resource variable
ResourceCreate("euro_icon",euro,ArrayRange(euro,1),ArrayRange(euro,0),0,0,ArrayRange(euro,1),COL
//--- create the Euro graphical label object, to which the image from the euro_icon resource will b
Image("Euro","::euro_icon",10,40);
//--- another method of applying the resource, we cannot draw do it
Image("USD","::Images\\dollar.bmp",15+ArrayRange(euro,1),40);
//--- direct method of addressing the euro.bmp resource is unavailable since it has already been de
Image("E2","::Images\\euro.bmp",20+ArrayRange(euro,1)*2,40); // execution time error is to occur
}

S cript
execution result – only two OBJ_BITM AP_LABEL objects out of three ones are created. The
image of the first object has the red stripe in the middle.

© 2000-2025, MetaQuotes Ltd.


1049 MQL5 programs

An important advantage of applying the resources is that the resource files are automatically
compressed before they are included into an executable EX5 file prior to compilation. Thus, using the
resource variables allows you to put all necessary data directly into the executable EX5 file as well as
reduce the number and total size of the files compared to the conventional way of writing MQL5
programs.
Using the resource variables is particularly convenient for publishing products in the Market.

Features
· The special bitmap resource variable type informs the compiler that the resource is an image. S uch
variables receive the uint type.
· The bitmap type array resource variable may have two dimensions. In this case, the array size is
defined as [image_height ][ image_width ]. If an array of one dimension is specified, the number of
elements is equal to image_height*image_width.
· W hen downloading a 24-bit image, the alpha channel component is set to 255 for all the image
pixels.
· W hen downloading a 32-bit image without the alpha channel, the alpha channel component is also
set to 255 for all the image pixels.
· W hen downloading a 32-bit image with the alpha channel, the pixels are not processed in any way.
· The resource file size cannot exceed 128 Mb.
· The automatic encoding detection by BOM (header) presence is performed for string files. If BOM is
absent, the encoding is defined by the file contents. The files in the ANS I, UTF-8 and UTF-16
encodings are supported. All strings are converted to Unicode when reading data from the files.
OpenCL programs

Using the resource string variables may greatly facilitate the development of some programs. For
example, you are able to write a code of an OpenCL program in a separate CL file and then include it
as a string into your MQL5 program resources.

© 2000-2025, MetaQuotes Ltd.


1050 MQL5 programs

#resource "seascape.cl" as string cl_program


...
int context;
if((cl_program=CLProgramCreate(context,cl_program)!=INVALID_HANDLE)
{
//--- perform further actions with an OpenCL program
}

In this example, you would have had to write the entire code as a single big string if no cl_program

resource variable had been used.


See also
R esourceCreate(), R esourceS ave(), PlayS ound(), ObjectS etInteger(), ChartApplyTemplate(), File
Functions

© 2000-2025, MetaQuotes Ltd.


1051 MQL5 programs

Call of Imported Functions


To import functions during the execution of a mql5-program, the client terminal uses early binding.
This means that if a program has call of an imported function, the corresponding module (ex5 or dll) is
loaded during the program load. MQL5 and DLL libraries are executed in the thread of a calling
module.
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 Advisor, 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, from which the module importing dll was started. The module here is an Expert Advisor,
a script, an indicator or EX5 library;
2. Directory terminal_data_directory\MQL5\Libraries (T ER MINAL _DAT A_PAT H\MQL5\Libraries);
3. Directory, from which the MetaTrader 5 client terminal was started;
4. S ystem directory;
5. W indows directory;
6. Current directory;
7. Directories listed in the PAT H system variable.

If the DLL library uses another DLL in its work, the first one cannot be loaded in case when there is no
second DLL.
Before an Expert Advisor (script, indicator) is loaded, a common list of all EX5 library modules is
formed. It's going to be used both from a loaded Expert Advisor (script, indicator) and from libraries
of this list. Thus the one-time loading of many times used EX5 library modules is needed. Libraries use
predefined variables of the Expert Advisor (script, indicator) they were called by.
The imported library EX5 is searched for in the following sequence:
1. Directory, path to which is set relative to the directory of the Expert Advisor (script, indicator) that
imports EX5;
2. Directory terminal_directory\MQL5\Libraries ;
3. Directory MQL5\Libraries in the common directory of all MetaTrader 5 client terminals
(Common\MQL5\Libraries).
Functions imported DLL into a mql5-program must ensure the W indows 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 Microsoft(r) compilers. This agreement is characterized by the following:
· caller (in our case it is a mq5-program) should " see" a prototype of a function called (imported from
the DLL), in order to properly combine parameters to a stack;
· caller (in our case it is a mql5-program) puts parameters to the stack in a reverse order, from right
to left - in this order an imported function reads parameters passed to it;
· parameters are passed by value, except those explicitly passed by reference (in our case strings)

© 2000-2025, MetaQuotes Ltd.


1052 MQL5 programs

· an imported function cleans the stack independently by reading parameters passed to it.
W hen describing the prototype of an imported function, default parameters can be used.
If the corresponding library is unable to load, or there is a prohibition on the DLL use, or the imported
function is not found - the Expert Advisor stops its operation with the appropriate message "Expert
Advisor stopped" in the Journal (log file). In this case the Expert Advisor will not run until it is
reinitialized. An Expert Advisor can be reinitialized as a result of recompilation or after the table of its
properties is opened and OK is pressed.

Passing Parameters
All parameters of simple types are passed by values unless it is explicitly indicated that they are
passed by reference. W hen a string is passed, the address of the buffer of the copied string is passed;
if a string is passed by reference, the address of the buffer of this string without copying it is passed
to the function imported from DLL.
S tructures
that contain dynamic arrays, strings, classes, other complex structures, as well as static or
dynamic arrays of the enumerated objects, can't be passed as a parameter to an imported function.
W hen passing an array to DLL, the address of the beginning of the data buffer is always passed
(irrespective of the AS_SERIES flag). A function inside a DLL knows nothing about the AS_SERIES flag,
the passed array is a static array of an undefined length; an additional parameter should be used for
specifying the array size.

© 2000-2025, MetaQuotes Ltd.


1053 MQL5 programs

Runtime Errors
The executing subsystem of the client terminal has an opportunity to save the error code in case it
occurs during a MQL5 program run. There is a predefined variable _LastError for each executable
MQL5 program.
Before starting the OnInit function, the _LastError variable is reset. In case an erroneous situation
occurs during calculations or in the process of internal function calls, the _LastError variable accepts a
corresponding error code. The value stored in this variable can be obtained using the GetLastError()
function.
There are several critical errors in case of which a program is terminated immediately:
· division by zero
· going beyond array boundary
· using an incorrect object pointer

© 2000-2025, MetaQuotes Ltd.


1054 MQL5 programs

Testing Trading Strategies


The idea of automated trading is appealing by the fact that the trading robot can work non-stop for 24
hours a day, seven days a week. The robot does not get tired, doubtful or scared, it's is totally free
from any psychological problems. It is sufficient enough to clearly formalize the trading rules and
implement them in the algorithms, and the robot is ready to work tirelessly. But first, you must make
sure that the following two important conditions are met:
· The Expert Advisor performs trading operations in accordance with the rules of the trading system;
· The trading strategy, implemented in the EA, demonstrates a profit on the history.
To get answers to these questions, we turn to the S trategy Tester, included in the MetaTrader 5 client
terminal.
This section covers the features of program testing and optimization in the strategy tester:
· Function Limitations in the S trategy Tester
· Tick Generation Modes
· S imulation of spread
· Using real tick s during a test
· The Global Variables of the Client Terminal
· The Calculation of Indicators During Testing
· Loading History during Testing
· Multi-Currency Testing
· S imulation of Time in the S trategy Tester
· Graphical Objects in Testing
· The OnTimer() Function in the S trategy Tester
· The S leep() Function in the S trategy Tester
· Using the S trategy Tester for Optimization Problems in Mathematical Calculations
· The S ynchronization of Bars in the " Open prices only" mode
· The IndicatorRelease() function in the Tester
· Event H andling in the Tester
· Testing Agents
· The Data Exchange between the Terminal and the Agent
· Using the S hared Folder of All of the Client Terminals
· Using DLLs

Memory and disk space limits in MQL5 Cloud Network


The following limitation applies to optimizations run in the MQL5 Cloud Network: the Expert Advisor
must not write to dis k more than 4GB of information or use more than 4GB of RAM. If the limit is
exceeded, the network agent will not be able to complete the calculation correctly, and you will not
receive the result. However, you will be charged for all the time spent on the calculations.

© 2000-2025, MetaQuotes Ltd.


1055 MQL5 programs

If you need to get information from each optimization pass, send frames without writing to dis k. To
avoid using file operations in Expert Advisors during calculations in the MQL5 Cloud Network, you can
use the following check:
int handle=INVALID_HANDLE;
bool file_operations_allowed=true;
if(MQLInfoInteger(MQL_OPTIMIZATION) || MQLInfoInteger(MQL_FORWARD))
file_operations_allowed=false;

if(file_operations_allowed)
{
...
handle=FileOpen(...);
...
}

Function Limitations in the Strategy Tester


There are operation limitations for some functions in the client terminal's S trategy Tester.

The Comment(), Print() and PrintFormat() Functions

To increase performance Comment(), Print() and PrintFormat() functions are not executed when
optimizing the trading robot's parameters. The exception is the use of these functions inside the
OnInit() handler. This allows you to easily find the cause of errors when they occur.

The Alert(), MessageBox(), PlaySound(), SendFTP, SendMail(),


SendNotification(), WebRequest() Functions

The Alert(), MessageBox(), PlayS ound(), S endFTP(), S endMail(), S endNotification() and W ebRequest()
functions designed for interaction with the " outside world" are not executed in the S trategy Tester.

Tick Generation Modes


An Expert Advisor is a program, written in MQL5, that is run each time in response to some external
event. The EA has a corresponding function (event handler) for each pre-defined event.
The NewTick event (price change) is the main event for the EA and, therefore, we need to generate a
tick sequence to test the EA. There are 3 modes of tick generation implemented in the S trategy Tester
of MetaTrader 5 client terminal:
· Every tick
· 1 Minute OH LC (OH LC prices with minute bars)
· Open prices only

© 2000-2025, MetaQuotes Ltd.


1056 MQL5 programs

The basic and the most detailed is the "Every tick" mode, the other two modes are the simplifications
of the basic one, and will be described in comparison to the "Every tick" mode. Consider all three
modes in order to understand the differences between them.

"Every Tick"
The historical quotes data for financial instruments is transferred from the trading server to the
MetaTrader 5 client terminal in the form of packed minute bars. Detailed information on the
occurrence of requests and the construction of the required time-frames can be obtained from the
Organizing Data Access chapter of MQL5 Reference.
The minimal element of the price history is the minute bar, from which you can obtain information on
the four values of the price:
· Open - the price at which the minute bar was opened;
· H igh - the maximum that was achieved during this minute bar;
· Low - the minimum that was achieved during this minute bar;
· Close - the closing price of the bar.
The new minute bar is not opened at the moment when the new minute begins (number of seconds
becomes equal to 0), but when a tick occurs - a price change by at least one point. The figure shows
the first minute bar of the new trading week, which has the opening time of 2011.01.10 00:00. The
price gap between Friday and Monday, which we see on the chart, is common, since currency rates
fluctuates even on weekends in response to incoming news.

For this bar, we only know that the minute bar was opened on January 10th 2011 at 00 hours 00
minutes, but we know nothing about the seconds. It could have been opened at 00:00:12 or 00:00:36
(12 or 36 seconds after the start of a new day) or any other time within that minute. But we do know
that the Open price of EURUSD was at 1.28940 at the opening time of the new minute bar.
W e also don't know (accurate within a second) when we received the tick corresponding to the closing
price of the considered minute bar. W e known only one thing - the last Close price of the minute bar.

© 2000-2025, MetaQuotes Ltd.


1057 MQL5 programs

For this minute, the price was 1.28958. The time of the appearance of H igh and Low prices is also
unknown, but we know that the maximum and minimum prices were on the levels of 1.28958 and
1.28940, respectively.

To test the trading strategy, we need a sequence of ticks, on which the work of the Expert Advisor will
be simulated. Thus, for every minute bar, we know the 4 control points, where the price has
definitely been. If a bar has only 4 ticks, then this is enough information to perform a testing, but
usually the tick volume is greater than 4.
H ence, there is a need to generate additional control points for ticks, which occurred between the
Open, High, Low, and Close prices. The principle of the "Every tick" ticks generation mode is
described in the The Algorithm of Ticks ’ Generation within the S trategy Tester of the MetaTrader 5
Terminal a figure from which is presented below.

W hen testing in the "Every tick" mode, the OnTick () function of the EA will be called at every control
point. Each control point is a tick from a generated sequence. The EA will receive the time and price
of the simulated tick, just as it would when working online.

Important: the "Every tick" testing mode is the most accurate, but at the same time, the most
time consuming. For an initial testing of the majority of trading strategies, it is usually sufficient
to use one of the other two testing modes.

"1 Minute OHLC"


The "Every tick" mode is the most accurate of the three modes, but at the same time, is the slowest.
The running of the OnTick() handler occurs at every tick, while tick volume can be quite large. For a
strategy, in which the tick sequence of price movement throughout the bar, does not matter, there is
a faster and rougher simulation mode - "1 minute OHLC" .
In the "1 minute OHLC" mode, the tick sequence is constructed only by the OHLC prices of the minute
bars, the number of the generated control points is significantly reduced - hence, so is the testing
time. The launch of the OnTick () function is performed on all control points, which are constructed by
the prices of OHLC minute bars.
The refusal to generate additional intermediate ticks between the Open, High, Low, and Close prices,
leads to an appearance of rigid determinism in the development of prices, from the moment that the

© 2000-2025, MetaQuotes Ltd.


1058 MQL5 programs

Open price is determined. This makes it possible to create a " Testing Grail" , which shows a nice
upward graph of the testing balance.
An example of such Grail is presented in the CodeBase - Grr-al.

The figure shows a very attractive graph of this EA testing. How was it obtained? W e know 4 prices for
a minute bar, and we also know that the first is the Open price, and the last is the Close price. W e
have the High and Low prices between them, and the sequence of their occurrence is unknown, but it
is known, that the High price is greater than or equal to the Open price (and the Low price is less than
or equal to the Open price).
It is sufficient enough to determine the moment of receiving the Open price, and then analyze the
next tick in order to determine what price we have at the moment - either the High or the Low. If the
price is below the Open price, then we have a Low price and buy at this tick, the next tick will
correspond to the High price, at which we will close the buy and open for sell. The next tick is the last
one, this is the Close price, and we close the sale on it.
If after the price, we receive a tick with a price greater than the opening price, then the sequence of
deals is reversed. Process a minute bar in this " cheat" mode, and wait for the next one.
W hen testing such EA on the history, everything goes smoothly, but once we launch it online, the truth
begins to get revealed - the balance line remains steady, but heads downwards. To expose this trick,
we simply need to run the EA in the "Every tick" mode.

Note: If the test results of the EA in the rough testing modes ("1 minute OHLC" and " Open Prices
only" ) seem too good, make sure to test it in the "Every tick" mode.

"Open Prices Only"


In this mode ticks are generated based on the OHLC prices of the timeframe selected for testing. The
OnTick() function of the Expert Advisor runs only at the beginning of the bar at the Open price. Due to
this feature, stop levels and pending may trigger at a price that differs from the specified one
(especially when testing on higher timeframes). Instead, we have an opportunity to quickly run an
evaluation test of the Expert Advisor.
W1 and M N1 periods are the exceptions in the " Open Price Only" ticks generation mode: for these
timeframes ticks are generated for the OHLC prices of each day, not OHLC prices of the week or
month.

© 2000-2025, MetaQuotes Ltd.


1059 MQL5 programs

S uppose we test an Expert Advisor on EURUSD H1 in the " Open Prices Only" mode. In this case the
total number of ticks (control points) will be no more than 4*number of one-hour bars within the tested
interval. But the OnTick() handler is called only at the opening of the one-hour bar. The checks
required for a correct testing occur on the rest of the ticks (that are " hidden" from the EA).
· The calculation of margin requirements ;
· The triggering of S top Loss and Take Profit levels ;
· The triggering of pending orders ;
· The removal of expired pending orders.
If there are no open positions or pending orders, we don't need to perform these checks on hidden
ticks, and the increase of speed may be quite substantial. This " Open prices only" mode is well suited
for testing strategies, which process deals only at the opening of the bar and do not use pending
orders, as well as S topLoss and TakeProfit orders. For the class of such strategies, the necessary
accuracy of testing is preserved.
Let's use the Moving Average Expert Advisor from the standard package as an example of an EA,
which can be tested in any mode. The logic of this EA is built in such a way that all of the decisions are
made at the opening of the bar, and deals are carried out immediately, without the use of pending
orders.
R un atesting of the EA on EURUSD H1 on an interval from 2010.09.01 to 2010.12.31, and compare the
graphs. The figure shows the balance graph from the test report for all of the three modes.

As you can see, the graphs on different testing modes are exactly the same for the Moving Average EA
from the standard package.
There are some limitations on the " Open Prices Only" mode:
· You cannot use the Random Delay execution mode.
· In the tested Expert Advisor, you cannot access data of the timeframe lower than that used for
testing/optimization. For example, if you run testing/optimization on the H1 period, you can access

© 2000-2025, MetaQuotes Ltd.


1060 MQL5 programs

data of H2, H3, H4 etc., but not M 30, M 20, M 10 etc. In addition, the higher timeframes that are
accessed must be multiple of the testing timeframe. For example, if you run testing in M 20, you
cannot access data of M 30, but it is possible to access H1. These limitations are connected with the
impossibility to obtain data of lower or non-multiple timeframes out of the bars generated during
testing/optimization.
· Limitations on accessing data of other timeframes also apply to other symbols whose data are used
by the Expert Advisor. In this case the limitation for each symbol depends on the first timeframe
accessed during testing/optimization. S uppose, during testing on EURUSD H1, an Expert Advisor
accesses data of GBPUSD M 20. In this case the Expert Advisor will be able to further use data of
EURUSD H1, H2, etc., as well as GBPUSD M 20, H1, H2 etc.

Note: The " Open prices only" mode has the fastest testing time, but it is not suitable for all of the
trading strategies. S elect the desired test mode based on the characteristics of the trading
system.

To conclude the section on the tick generation modes, let's consider a visual comparison of the
different tick generation modes for EURUSD, for two M 15 bars on an interval from 2011.01.11
21:00:00 - 2011.01.11 21:30:00.

The ticks were saved into different files using the W riteTicks FromTester.mq5 EA and the ending of
these files names are specified in filenameEveryTick, filenameOHLC and filenameOpenPrice input-
parameters.

To obtain three files with three tick sequences (for each of the following modes "Every tick" , "1 minute
OHLC" and " Open prices only), the EA was launched three times in the corresponding modes, in single
runs. Then, the data from these three files were displayed on the chart using the
Ticks FromTester.mq5 indicator. The indicator code is attached to this article.

© 2000-2025, MetaQuotes Ltd.


1061 MQL5 programs

By default, all of the file operations in the MQL5 language are made within the " file sandbox" , and
during testing the EA has access only to its own " file sandbox" . In order for the indicator and the EA to
work with files from one folder during testing, we used the flag FILE_COMMON. An example of code
from the EA:
//--- open the file
file=FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON,";");
//--- check file handle
if(file==INVALID_HANDLE)
{
PrintFormat("Error in opening of file %s for writing. Error code=%d",filename,GetLastError())
return;
}
else
{
PrintFormat("The file will be created in %s folder",TerminalInfoString(TERMINAL_COMMONDATA_PA
}

Forreading the data in the indicator, we also used the flag FILE_COMMON. This allowed us to avoid
manually transferring the necessary files from one folder to another.
//--- open the file
int file=FileOpen(fname,FILE_READ|FILE_CSV|FILE_COMMON,";");
//--- check file handle
if(file==INVALID_HANDLE)
{
PrintFormat("Error in open of file %s for reading. Error code=%d",fname,GetLastError());
return;
}
else
{

© 2000-2025, MetaQuotes Ltd.


1062 MQL5 programs

PrintFormat("File will be opened from %s",TerminalInfoString(TERMINAL_COMMONDATA_PATH));


}

Simulation of spread
The price difference between the Bid and the As k prices is called the spread. During testing, the
spread is not modeled but is taken from historical data. If the spread is less than or equal to zero in
the historical data, then the last known (at the moment of generation) spread is used by testing
agent.
In the S trategy Tester, the spread is always considered floating. That is, S ymbolInfoInteger(symbol,
SYM BOL _S PREAD_FLOAT) always returns true.

In addition, the historical data contains tick values and trading volumes. For the storage and retrieval
of data we use a special M qlRates structure:
struct MqlRates
{
datetime time; // Period 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 real_volume; // Trade volume
};

Using real ticks during a test


Testing and optimization on real ticks are as close to real conditions as possible. Instead of generated
ticks based on minute data, it is possible to use real ticks accumulated by a broker. These are ticks
from exchanges and liquidity providers.
To ensure the greatest test accuracy, minute bars are also used in the real ticks mode. The bars are
applied to check and correct tick data. This also allows you to avoid the divergence of charts in the
tester and the client terminal.
The tester compares the tick data to the minute bar parameters : a tick should not exceed the bar's
H igh/Low levels, also initial and final tick s should coincide with the bar's Open/Close prices. The
volume is compared as well. If a mismatch is detected, all ticks corresponding to this minute bar are
discarded. Generated ticks are used instead (like in the "Every tick" mode).
If a symbol history has a minute bar with no tick data for it, the tester generates ticks in the "Every
tick" mode. This allows plotting a correct chart in the tester in case a broker's tick data is insufficient.
If a symbol history has no minute bar but the appropriate tick data for the minute is present, the data
can be used in the tester. For example, exchange symbol pairs are formed using Last prices. If only
ticks with Bid/As k prices without the Last price arrive from the server, the bar is not generated. The
tester uses these tick data since they do not contradict the minute ones.

© 2000-2025, MetaQuotes Ltd.


1063 MQL5 programs

Tick data may not coincide with minute bars for various reasons, for example because of connection
losses or other failures when transmitting data from a source to the client terminal. The minute data
is considered more reliable during tests.
Keep in mind the following features when testing on real ticks :
· W hen launching a test, the minute data on a symbol is synchronized along with the tick one.
· Ticks are stored in the symbol cache of the strategy tester. The cache size does not exceed 128 000
ticks. W hen new ticks arrive, the oldest data is removed from the cache. However, the CopyTicks
function allows receiving ticks outside the cache (only when testing on real ticks). In that case, the
data is requested from the tester tick database that is completely similar to the corresponding client
terminal database. No minute bar corrections are implemented to this base. Therefore, the ticks
there may differ from the ones stored in the cache.

The Global Variables of the Client Terminal


During testing, the global variables of the client terminal are also emulated, but they are not related to
the current global variables of the terminal, which can be seen in the terminal using the F3 button. It
means that all operations with the global variables of the terminal, during testing, take place outside
of the client terminal (in the testing agent).

The Calculation of Indicators During Testing


In the real-time mode, the indicator values are calculated at every tick.
In the S trategy Tester, indicators are calculated only when they are accessed for data, i.e. when
indicator buffer values are requested. The only exceptions are custom indicators with the specified
#property tester_everytick_calculate. In this case, recalculation is done on each tick .

In the visual testing mode, all indicators are unconditionally recalculated when a new tick arrives in
order to be correctly displayed on the visual testing chart.
The indicator is calculated once per tick. All subsequent requests for indicator data do not lead to
recalculation until a new tick arrives. Therefore, if the timer is enabled in an EA via the
EventS etTimer() function, the indicator data is requested from the last tick before each call of the
OnTimer() handler. If the indicator has not been calculated on the last tick yet, the calculations of the
indicator values are launched. If the data has already been prepared, it is provided without a new
recalculation.
Thus, all indicator calculations are performed in the most resource-saving manner — if the indicator
has already been calculated at a given tick, its data is provided 'as is '. No recalculation is launched.

Loading History during Testing


The history of a symbol to be tested is synchronized and loaded by the terminal from the trade server
before starting the testing process. During the first time, the terminal loads all available history of a
symbol in order not to request it later. Further only the new data are loaded.
A testing agent receives the history of a symbol to be tested from the client terminal right after the
start of testing. If data of other instruments are used in the process of testing (for example, it is a
multicurrency Expert Advisor), the testing agent requests the required history from the client terminal

© 2000-2025, MetaQuotes Ltd.


1064 MQL5 programs

during the first call to such data. If historical data are available in the terminal, they are immediately
passed to the testing agent. If data are not available, the terminal requests and downloads them from
the server, and then passes to the testing agent.
Data of additional instruments is also required for calculating cross-rates for trade operations. For
example, when testing a strategy on EURCHF with the deposit currency in USD, prior to processing the
first trading operation, the testing agent requests the history data of EURUSD and USDCHF from the
client terminal, though the strategy does not contain direct use call of these symbols.
Before testing a multi-currency strategy, it is recommended to download all the necessary historical
data to the client terminal. This will help to avoid delays in testing/optimization associated with
download of the required data. You can download history, for example, by opening the appropriate
charts and scrolling them to the history beginning. An example of forced loading of history into the
terminal is available in the Organizing Access to Data section of the MQL5 Reference.
Testing agents, in turn, receive history from the terminal in the packed form. During the next testing,
the tester does not load history from the terminal, because the required data is available since the
previous run of the tester.

· The terminal loads history from a trade server only once, the first time the agent requests the
history of a symbol to be tested from the terminal. The history is loaded in a packed form to
reduce the traffic.
· Ticks are not sent over the network, they are generated on testing agents.

Multi-Currency Testing
The S trategy Tester allows us to perform a testing of strategies, trading on multiple symbols. S uch EAs
are conventionally referred to as multi-currency Expert Advisors, since originally, in the previous
platforms, testing was performed only for a single symbol. In the S trategy Tester of the MetaTrader 5
terminal, we can model trading for all of the available symbols.
The tester loads the history of the used symbols from the client terminal (not from the trade server!)
automatically during the first call of the symbol data.
The testing agent downloads only the missing history, with a small margin to provide the necessary
data on the history, for the calculation of the indicators at the starting time of testing. For the time-
frames D1 and less, the minimum volume of the downloaded history is one year.
Thus, if we run a testing on an interval 2010.11.01-2010.12.01 (testing for an interval of one month)
with a period of M 15 (each bar is equal to 15 minutes), then the terminal will be requested the history
for the instrument for the entire year of 2010. For the weekly time-frame, we will request a history of
100 bars, which is about two years (a year has 52 week s). For testing on a monthly time-frame the
agent will request the history of 8 years (12 months x 8 years = 96 months).
If there isn't necessary bars, the starting date of testing will be automatically shifted from past to
present to provide the necessary reserve of bars before the testing.
During testing, the " Market W atch" is emulated as well, from which one can obtain information on
symbols.

© 2000-2025, MetaQuotes Ltd.


1065 MQL5 programs

By default, at the beginning of testing, there is only one symbol in the " Market W atch" of the S trategy
Tester - the symbol that the testing is running on. All of the necessary symbols are connected to the
" Mark et W atch" of the S trategy Tester (not terminal!) automatically when referred to.

Prior to starting testing of a multi-currency Expert Advisor, it is necessary to select symbols


required for testing in the " Market W atch" of the terminal and load the required data. During the
first call of a " foreign" symbol, its history will be automatically synchronized between the testing
agent and the client terminal. A " foreign" symbol is the symbol other than that on which testing is
running.

R eferral to the data of an " other" symbol occurs in the following cases :
· W hen using the technical indicators function and IndicatorCreate() on the symbol/timeframe;
· The request to the " Market W atch" data for the other symbol:
1. S eriesInfoInteger
2. Bars
3. S ymbolS elect
4. S ymbolIs S ynchronized
5. S ymbolInfoDouble
6. S ymbolInfoInteger
7. S ymbolInfoS tring
8. S ymbolInfoTick
9. S ymbolInfoS essionQuote
10. S ymbolInfoS essionTrade
11.Mark etBookAdd
12.Mark etBookGet
· R equest of the time-series for a symbol/timeframe by using the following functions :
1. CopyBuffer
2. CopyR ates
3. CopyTime
4. CopyOpen
5. CopyHigh
6. CopyLow
7. CopyClose
8. CopyTickVolume
9. CopyR ealVolume
10.CopyS pread

At the moment of the first call to an " other" symbol, the testing process is stopped and the history is
downloaded for the symbol/timeframe, from the terminal to the testing agent. At the same time, the
generation of tick sequence for this symbol is made.

© 2000-2025, MetaQuotes Ltd.


1066 MQL5 programs

An individual tick sequence is generated for each symbol, according to the selected tick generation
mode. You can also request the history explicitly for the desired symbols by calling the S ymbolS elect()
in the OnInit() handler - the downloading of the history will be made immediately prior to the testing
of the Expert Advisor.
Thus, it does not require any extra effort to perform multi-currency testing in the MetaTrader 5 client
terminal. Just open the charts of the appropriate symbols in the client terminal. The history will be
automatically uploaded from the trading server for all the required symbols, provided that it contains
this data.

Simulation of Time in the Strategy Tester


During testing, the local time TimeLocal() is always equal to the server time TimeTradeS erver(). In
turn, the server time is always equal to the time corresponding to the GMT time - TimeGMT(). This
way, all of these functions display the same time during testing.
The lack of a difference between the GMT, the Local, and the server time in the S trategy Tester is
done deliberately in case there is no connection to the server. The test results should always be the
same, regardless of whether or not there is a connection. Information about the server time is not
stored locally, and is taken from the server.

Graphical Objects in Testing


During testing/optimization graphical objects are not plotted. Thus, when referring to the properties
of a created object during testing/optimization, an Expert Advisor will receive zero values.

This limitation does not apply to testing in visual mode.

The OnTimer() Function in the Strategy Tester


MQL5 provides the opportunity for handling timer events. The call of the OnTimer() handler is done
regardless of the test mode. This means that if a test is running in the " Opening prices only" mode for
the period H4, and the EA has a timer set to a call per second, then at the opening of each H4 bar, the
OnTick() handler will be called one time, and the OnTimer() handler will be called 14400 times (3600
seconds * 4 hours ). The amount by which the testing time of the EA will be increased depends on the
logic of the EA.
To check the dependence of the testing time from the given frequency of the timer, we have created a
simple EA without any trading operations.
//--- input parameters
input int timer=1; // timer value, sec
input bool timer_switch_on=true; // timer on
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- run the timer if timer_switch_on==true
if(timer_switch_on)

© 2000-2025, MetaQuotes Ltd.


1067 MQL5 programs

{
EventSetTimer(timer);
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- stop the timer
EventKillTimer();
}
//+------------------------------------------------------------------+
//| Timer function |
//+------------------------------------------------------------------+
void OnTimer()
{
//---
// take no actions, the body of the handler is empty
}
//+------------------------------------------------------------------+

Testing time measurements were taken at different values of the timer parameter (periodicity of the
Timer event). On the obtained data, we plot a testing time as function of Timer period.

It can be clearly seen that the smaller is the parameter timer, during the initialization of the
EventS etTimer(Timer) function, the smaller is the period (Period) between the calls of the OnTimer()
handler, and the larger is the testing time T, under the same other conditions.

The Sleep() Function in the Strategy Tester

© 2000-2025, MetaQuotes Ltd.


1068 MQL5 programs

The S leep() function allows the EA or script to suspend the execution of the mql5-program for a while,
when working on the graph. This can be useful when requesting data, which is not ready at the time of
the request and you need to wait until it is ready. A detailed example of using the S leep() function can
be found in the section Organizing Data Access.
The testing process is not lingered by the S leep() calls.W hen you call the S leep(), the generated ticks
are " played" within a specified delay, which may result in the triggering of pending orders, stops, etc.
After a S leep() call, the simulated time in the S trategy Tester increases by an interval, specified in the
parameter of the S leep function.
If as a result of the execution of the S leep() function, the current time in the S trategy Tester went
over the testing period, then you will receive an error " Infinite S leep loop detected while testing" . If
you receive this error, the test results are not rejected, all of the computations are performed in their
full volume (the number of deals, subsidence, etc.), and the results of this testing are passed on to
the terminal.
The S leep() function will not work in OnDeinit(), since after it is called, the testing time will be
guaranteed to surpass the range of the testing interval.

Using the Strategy Tester for Optimization Problems in


Mathematical Calculations
The tester in the MetaTrader 5 terminal can be used, not only to testing trading strategies, but also
for mathematical calculations. To use it, it's necessary to select the " Math calculations " mode:

© 2000-2025, MetaQuotes Ltd.


1069 MQL5 programs

In this case, only three functions will be called: OnInit(), OnTester(), OnDeinit(). In " Math calculations "
mode the S trategy Tester doesn't generate any ticks and download the history.
The S trategy Tester works in " Math calculations " mode also if you specify the starting date greater
than ending date.
W hen using the tester to solve mathematical problems, the uploading of the history and the
generation of ticks does not occur.
A typical mathematical problem for solving in the MetaTrader 5 S trategy Tester - searching for an
extremum of a function with many variables.
To solve it we need to:
· The calculation of function value should be located in OnTester() function;
· The function parameters must be defined as input-variables of the Expert Advisor;
Compile the EA, open the "S trategy Tester" window. In the " Input parameters " tab, select the required
input variables, and define the set of parameter values by specifying the start, stop and step values
for each of the function variables.
S electthe optimization type - "S low complete algorithm" (full search of parameters space) or "Fast
genetic based algorithm" . For a simple search of the extremum of the function, it is better to choose a
fast optimization, but if you want to calculate the values for the entire set of variables, then it is best
to use the slow optimization.
S elect " Math calculation"
mode and using the "S tart" button, run the optimization procedure. Note that
during the optimization the S trategy Tester will search for the maximum values of the OnTester
function. To find a local minimum, return the inverse of the computed function value from the
OnTester function:
return(1/function_value);

It is necessary to check that the function_value is not equal to zero, since otherwise we can obtain a
critical error of dividing by zero.
There is another way, it is more convenient and does not distort the results of optimization, it was
suggested by the readers of this article:
return(-function_value);

© 2000-2025, MetaQuotes Ltd.


1070 MQL5 programs

This option does not require the checking of the function_value for being equal to zero, and the
surface of the optimization results in a 3D-representation has the same shape. The only difference is
that it is mirrored comparing to the original.
As an example, we provide the sink() function:

The code of the EA for finding the extremum of this function is placed into the OnTester():
//+------------------------------------------------------------------+
//| Sink.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
//--- input parameters
input double x=-3.0; // start=-3, step=0.05, stop=3
input double y=-3.0; // start=-3, step=0.05, stop=3
//+------------------------------------------------------------------+
//| Tester function |
//+------------------------------------------------------------------+
double OnTester()
{
//---
double sink=MathSin(x*x+y*y);
//---
return(sink);
}
//+------------------------------------------------------------------+

Perform an optimization and see the optimization results in the form of a 2D graph.

© 2000-2025, MetaQuotes Ltd.


1071 MQL5 programs

The better the value is for a given pair of parameters (x, y), the more saturated the color is. As was
expected from the view of the form of the sink() formula, its values forms concentric circles with a
center at (0,0). One can see in the 3D-graph, that the sink() function has no single global extremum:

The Synchronization of Bars in the "Open prices only" mode


The tester in the MetaTrader 5 client terminal allows us to check the so-called " multi-currency" EAs. A
multi-currency EA - is an EA that trades on two or more symbols.
The testing of strategies, that are trading on multiple symbols, imposes a few additional technical
requirements on the tester:

© 2000-2025, MetaQuotes Ltd.


1072 MQL5 programs

· The generation of ticks for these symbols ;


· The calculation of indicator values for these symbols ;
· The calculation of margin requirements for these symbols ;
· S ynchronization of generated tick sequences for all trading symbols.

The S trategy Tester generates and plays a tick sequence for each instrument in accordance with the
selected trading mode. At the same time, a new bar for each symbol is opened, regardless of how the
bar opened on another symbol. This means that when testing a multi-currency EA, a situation may
occur (and often does), when for one instrument a new bar has already opened, and for the other it
has not. Thus, in testing, everything happens just like in reality.
This authentic simulation of the history in the tester does not cause any problems as long as the
"Every tick" and "1 minute OH LC" testing modes are used. For these modes, enough tick s are
generated for one candlestick, to be able to wait until the synchronization of bars from different
symbols takes place. But how do we test multi-currency strategies in the " Open prices only" mode, if
the synchronization of bars on trading instruments is mandatory? In this mode, the EA is called only on
one tick, which corresponds to the time of the opening of the bars.
W e'llillustrate it on an example: we are testing an EA on the EURUSD, and a new H1 candlestick has
been opened on EURUSD. W e can easily recognize this fact - while testing in the " Open prices only"
mode, the NewTick event corresponds to the moment of a bar opening on the tested period. But there
is no guarantee that the new candlestick was opened on the USDJPY symbol, which is used in the EA.
Under normal circumstances, it is sufficient enough to complete the work of the OnTick() function and
to check for the emergence of a new bar on USDJPY at the next tick. But when testing in the " Open
prices only" mode, there will be no other tick, and so it may seem that this mode is not fit for testing
multi-currency EAs. But this is not so - do not forget that the tester in MetaTrader 5 behaves just as it
would in real life. You can wait until a new bar is opened on another symbols using the function
S leep()!

The code of the EA S ynchronize_Bars _Use_S leep.mq5, which shows an example of the synchronization
of bars in the " Open prices only" mode:
//+------------------------------------------------------------------+
//| Synchronize_Bars_Use_Sleep.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
//--- input parameters
input string other_symbol="USDJPY";
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- check symbol
if(_Symbol==other_symbol)
{

© 2000-2025, MetaQuotes Ltd.


1073 MQL5 programs

PrintFormat("You have to specify the other symbol in input parameters or select other symbol
//--- forced stop testing
return(INIT_PARAMETERS_INCORRECT);
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- static variable, used for storage of last bar time
static datetime last_bar_time=0;
//--- sync flag
static bool synchonized=false;
//--- if static variable isn't initialized
if(last_bar_time==0)
{
//--- it's first call, save bar time and exit
last_bar_time=(datetime)SeriesInfoInteger(_Symbol,Period(),SERIES_LASTBAR_DATE);
PrintFormat("The last_bar_time variable is initialized with value %s",TimeToString(last_bar_t
}
//--- get open time of the last bar of chart symbol
datetime curr_time=(datetime)SeriesInfoInteger(Symbol(),Period(),SERIES_LASTBAR_DATE);
//--- if times aren't equal
if(curr_time!=last_bar_time)
{
//--- save open bar time to the static variable
last_bar_time=curr_time;
//--- not synchronized
synchonized=false;
//--- print message
PrintFormat("A new bar has appeared on symbol %s at %s",_Symbol,TimeToString(TimeCurrent()));
}
//--- open time of the other symbol's bar
datetime other_time;
//--- loop until the open time of other symbol become equal to curr_time
while(!(curr_time==(other_time=(datetime)SeriesInfoInteger(other_symbol,Period(),SERIES_LASTBAR_
{
PrintFormat("Waiting 5 seconds..");
//--- wait 5 seconds and call SeriesInfoInteger(other_symbol,Period(),SERIES_LASTBAR_DATE)
Sleep(5000);
}
//--- bars are synchronized
synchonized=true;
PrintFormat("Open bar time of the chart symbol %s: is %s",_Symbol,TimeToString(last_bar_time));
PrintFormat("Open bar time of the symbol %s: is %s",other_symbol,TimeToString(other_time));
//--- TimeCurrent() is not useful, use TimeTradeServer()

© 2000-2025, MetaQuotes Ltd.


1074 MQL5 programs

Print("The bars are synchronized at ",TimeToString(TimeTradeServer(),TIME_SECONDS));


}
//+------------------------------------------------------------------+

Notice the last line in the EA, which displays the current time when the fact of synchronization was
established:
Print("The bars synchronized at ",TimeToString(TimeTradeServer(),TIME_SECONDS));

To display the current time we used the TimeTradeS erver() function rather than TimeCurrent(). The
TimeCurrent() function returns the time of the last tick, which does not change after using S leep().
R un the EA in the " Open prices only" mode, and you will see a message about the synchronization of
the bars.

Use the TimeTradeS erver() function instead of the TimeCurrent(), if you need to obtain the current
server time, and not the time of the last tick arrival.
There is another way to synchronize bars - using a timer. An example of such an EA is
S ynchronize_Bars _Use_OnTimer.mq5, which is attached to this article.

The IndicatorRelease() function in the Tester


After completing a single testing, a chart of the instrument is automatically opened, which displays the
completed deals and the indicators used in the EA. This helps to visually check the entry and exit
points, and compare them with the values of the indicators.

Note: indicators, displayed on the chart, which automatically opens after the completion of the
testing, are calculated anew after the completion of testing. Even if these indicators were used in
the tested EA.

But in some cases, the programmer may want to hide the information on which indicators were
involved in the trading algorithms. For example, the code of the EA is rented or sold as an executable
file, without the provision of the source code. For this purpose, the IndicatorRelease() function is
suitable.
If the terminal sets a template with the name tester.tpl in the directory/profiles /templates of the
client terminal, then it will be applied to the opened chart. In its absence, the default template is
applied. (default.tpl).
The IndicatorRelease() function is originally intended for releasing the calculating portion of the
indicator, if it is no longer needed. This allows you to save both the memory and the CPU resources,
because each tick calls for an indicator calculation. Its second purpose is to prohibit the showing of an
indicator on the testing chart, after a single test run.

© 2000-2025, MetaQuotes Ltd.


1075 MQL5 programs

To prohibit the showing of the indicator on the chart after testing, call the IndicatorRelease() with the
handle of the indicator in the handler OnDeinit(). The OnDeinit() function is always called after the
completion and before the showing of the testing chart.
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
bool hidden=IndicatorRelease(handle_ind);
if(hidden) Print("IndicatorRelease() successfully completed");
else Print("IndicatorRelease() returned false. Error code ",GetLastError());
}

In order to prohibit the showing of the indicator on the chart, after the completion of a single test, use
the function IndicatorRelease() in the handler OnDeinit().

Event Handling in the Tester


The presence of the OnTick() handler in the EA is not mandatory in order for it to be subjected to
testing on historical data in the MetaTrader 5 tester. It is sufficient enough for the EA ti contain at
least one of the following function-handlers :
· OnTick() - Event handler of a new tick arrival;
· OnTrade() - Trading event handler;
· OnTimer() - Event handler of a signal arrival from the timer;
· OnChartEvent() - a handler for client events.
W hen testing in an EA, we can handle custom events using the OnChartEvent() function, but in the
indicators, this function can not be called in the tester. Even if the indicator has the OnChartEvent()
event handler and this indicator is used in the tested EA, the indicator itself will not receive any
custom events.
During testing, an Indicator can generate custom events using the EventChartCustom() function, and
the EA can process this event in the OnChartEvent().
In addition to these events, special events associated with the process of testing and optimization are
generated in the strategy tester:
· Tester - this event is generated after completion of Expert Advisor testing on history data. The
Tester event is handled using the OnTester() function. This function can be used only when testing
Expert Advisor and is intended primarily for the calculation of a value that is used as a Custom max
criterion for genetic optimization of input parameters.
· TesterInit - this event is generated during the start of optimization in the strategy tester before the
very first pass. The TesterInit event is handled using the OnTesterInit() function. During the start of
optimization, an Expert Advisor with this handler is automatically loaded on a separate terminal
chart with the symbol and period specified in the tester, and receives the TesterInit event. The
function is used to initiate an Expert Advisor before start of optimization for further processing of
optimization results.

© 2000-2025, MetaQuotes Ltd.


1076 MQL5 programs

· TesterPass - this event is generated when a new data frame is received. The TesterPass event is
handled using the OnTesterPass() function. An Expert Advisor with this handler is automatically
loaded on a separate terminal chart with the symbol/period specified for testing, and receives the
TesterPass event when a frame is received during optimization. The function is used for dynamic
handling of optimization results " on the spot" without waiting for its completion. Frames are added
using the FrameAdd() function, which can be called after the end of a single pass in the OnTester()
handler.
· TesterDeinit - this event is generated after the end of Expert Advisor optimization in the strategy
tester. The TesterDeinit event is handles using the OnTesterDeinit() function. An Expert Advisor
with this handler is automatically loaded on a chart at the start of optimization, and receives
TesterDeinit after its completion. The function is used for final processing of all optimization
results.

Testing Agents
Testing in the MetaTrader 5 client terminal is carried out using test agents. Local agents are created
and enabled automatically. The default number of local agents corresponds to the number of cores in a
computer.
Each testing agent has its own copy of the global variables, which is not related to the client terminal.
The terminal itself is the dispatcher, which distributes the tas ks to the local and remote agents. After
executing a tas k on the testing of an EA, with the given parameters, the agent returns the results to
the terminal. W ith a single test, only one agent is used.
The agent stores the history, received from the terminal, in separate folders, by the name of the
instrument, so the history for EURUSD is stored in a folder named EURUSD. In addition, the history of
the instruments is separated by their sources. The structure for storing the history looks the following
way:
tester_catalog\Agent-IPaddress-Port\bases\name_source\history\symbol_name

For example, the history for EURUSD from the server MetaQuotes-Demo can be stored in the folder
tester_catalog\Agent-127.0.0.1-3000\bases \MetaQuotes-Demo\EURUSD.
A local agent, after the completion of testing, goes into a standby mode, awaiting for the next tas k
for another 5 minutes, so as not to waste time on launching for the next call. Only after the waiting
period is over, the local agent shuts down and unloads from the CPU memory.
In case of an early completion of the testing, from the user's side (the " Cancel" button), as well as with
the closing of the client terminal, all local agents immediately stop their work and are unloaded from
the memory.

The Data Exchange between the Terminal and the Agent


W hen you run a test, the client terminal prepares to send an agent a number of parameter blocks :
· Input parameters for testing (simulation mode, the interval of testing, instruments, optimization
criterion, etc.)
· The list of the selected symbols in the " Market W atch"
· The specification of the testing symbol (the contract size, the allowable margins from the market
for setting a S topLoss and Takeprofit, etc)

© 2000-2025, MetaQuotes Ltd.


1077 MQL5 programs

· The Expert Advisor to be tested and the values of its input parameters
· Information about additional files (libraries, indicators, data files - # property tester_ ...)

tester_indicator string Name of a custom indicator in the format of " indicator_name.ex5" .


Indicators that require testing are defined automatically from the
call of the iCustom() function, if the corresponding parameter is
set through a constant string. For all other cases (use of the
IndicatorCreate() function or use of a non-constant string in the
parameter that sets the indicator name) this property is required
tester_file string File name for a tester with the indication of extension, in double
quotes (as a constant string). The specified file will be passed to
tester. Input files to be tested, if there are necessary ones, must
always be specified.
tester_library string Library name with the extension, in double quotes. A library can
have extension dll or ex5. Libraries that require testing are
defined automatically. However, if any of libraries is used by a
custom indicator, this property is required

For each block of parameters, a digital fingerprint in the form of M D5-hash is created, which is sent to
the agent. M D5-hash is unique for each set, its volume is many more times smaller than the amount of
information on which it is calculated.
The agent receives a hash of blocks and compares them with those that it already has. If the
fingerprint of the given parameter block is not present in the agent, or the received hash is different
from the existing one, the agent requests this block of parameters. This reduces the traffic between
the terminal and the agent.
After the testing, the agent returns to the terminal all of the results of the run, which are shown in the
tabs " Test Results " and " Optimization Results ": the received profit, the number of deals, the S harpe
coefficient, the result of the OnTester() function, etc.
During optimizing, the terminal hands out testing tas ks to the agents in small packages, each package
contains several tas ks (each tas k means single testing with a set of input parameters). This reduces
the exchange time between the terminal and the agent.
The agents never record to the hard dis k the EX5-files, obtained from the terminal (EA, indicators,
libraries, etc.) for security reasons, so that a computer with a running agent could not use the sent
data. All other files, including DLL, are recorded in the sandbox. In remote agents you can not test EAs
using DLL.
The testing results are added up by the terminal into a special cache of results (the result cache), for a
quick access to them when they are needed. For each set of parameters, the terminal searches the
result cache for already available results from the previous runs, in order to avoid re-runs. If the result
with such a set of parameters is not found, the agent is given the tas k to conduct the testing.
All traffic between the terminal and the agent is encrypted.

Ticks are not sent over the network, they are generated on testing agents.

© 2000-2025, MetaQuotes Ltd.


1078 MQL5 programs

Using the Shared Folder of All of the Client Terminals


All testing agents are isolated from each other and from the client terminal: each agent has its own
folder in which its logs are recorded. In addition, all file operations during the testing of the agent
occur in the folder agent_name/MQL5/Files. However, we can implement the interaction between the
local agents and the client terminal through a shared folder for all of the client terminals, if during the
file opening you specify the flag FILE_COMMON:
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- the shared folder for all of the client terminals
common_folder=TerminalInfoString(TERMINAL_COMMONDATA_PATH);
//--- draw out the name of this folder
PrintFormat("Open the file in the shared folder of the client terminals %s", common_folder);
//--- open a file in the shared folder (indicated by FILE_COMMON flag)
handle=FileOpen(filename,FILE_WRITE|FILE_READ|FILE_COMMON);
... further actions
//---
return(INIT_SUCCEEDED);
}

Using DLLs
To speed up the optimization we can use not only local, but also remote agents. In this case, there are
some limitations for remote agents. First of all, remote agents do not display in their logs the results
of the execution of the Print() function, messages about the opening and closing of positions. A
minimum of information is displayed in the log to prevent incorrectly written EAs from trashing up the
computer, on which the remote agent is working, with messages.
A second limitation - the prohibition on the use of DLL when testing EAs. DLL calls are absolutely
forbidden on remote agents for security reasons. On local agent, DLL calls in tested EAs are allowed
only with the appropriate permission "Allow import DLL" .

© 2000-2025, MetaQuotes Ltd.


1079 MQL5 programs

Note: W hen using 3rd party EAs (scripts, indicators) that require allowed DLL calls, you should be
aware of the ris ks which you assume when allowing this option in the settings of the terminal.
R egardless of how the EA will be used - for testing or for running on a chart.

© 2000-2025, MetaQuotes Ltd.


1080 Predefined Variables

The predefined Variables


For each executable mql5-program a set of predefined variables is supported, which reflect the state
of the current price chart by the moment a mql5-program (Expert Advisor, script or custom indicator)
is started.
Values of predefined variables are set by the client terminal before a mql5-program is started.
Predefined variables are constant and cannot be changed from a mql5-program. As exception, there is
a special variable _LastError, which can be reset to 0 by the ResetLastError function.

Variable Value

_AppliedTo The _AppliedTo variable allows finding out the type of data, used for
indicator calculation
_Digits Number of decimal places
_Point S ize of the current symbol point in the quote currency
_LastError The last error code
_Period Timeframe of the current chart
_R andomS eed Current status of the generator of pseudo-random integers
_S topFlag Program stop flag
_S ymbol S ymbol name of the current chart
_UninitR eason Uninitialization reason code

_Is X64 The _Is X64 variable allows finding out the bit version of the terminal, in
which an MQL5 application is running

Predefined variables cannot be defined in a library. A library uses such variables that are defined in
program from which this library is called.

© 2000-2025, MetaQuotes Ltd.


1081 Predefined Variables

int _AppliedTo
The _AppliedTo variable allows finding out the type of data, used for indicator calculation:

Data type Meani Description of data used for indicator calculation.


ng

— 0 The indicator uses the second OnCalculate() call form - the data for
calculation are not specified by a certain buffer or data array
Close 1 Close prices
Open 2 Open prices
H igh 3 H igh prices

Low 4 Low prices


Median Price 5 Median price = (High+Low)/2
(HL/2)
Typical Price 6 Typical price = (High+Low+Close)/3
(HLC/3)
W eighted Price 7 W eighted price = (Open+High+Low+Close)/4
(HLCC/4)
Previous 8 Data of the indicator, which was launched on the chart before this
Indicator's Data indicator
First Indicator's 9 Data of the indicator, which was launched first on the chart
Data

Indicator handle 10+ Data of the indicator, which was passed to the iCustom() function
using the indicator handle. The _AppliedTo value contains the
indicator handle

Example:

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
// Getting the type of data used for indicator calculation
Print("_AppliedTo=",_AppliedTo);
Print(getIndicatorDataDescription(_AppliedTo));
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1082 Predefined Variables

//| Description of data used for indicator calculation |


//+------------------------------------------------------------------+
string getIndicatorDataDescription(int data_id)
{
string descr="";
switch(data_id)
{
case(0):descr="It's first type of OnCalculate() - no data buffer";
break;
case(1):descr="Indicator calculates on Close price";
break;
case(2):descr="Indicator calculates on Open price";
break;
case(3):descr="Indicator calculates on High price";
break;
case(4):descr="Indicator calculates on Low price";
break;
case(5):descr="Indicator calculates on Median Price (HL/2)";
break;
case(6):descr="Indicator calculates on Typical Price (HLC/3)";
break;
case(7):descr="Indicator calculates on Weighted Price (HLCC/4)";
break;
case(8):descr="Indicator calculates Previous Indicator's data";
break;
case(9):descr="Indicator calculates on First Indicator's data";
break;
default: descr="Indicator calculates on data of indicator with handle="+string(data_id);
break;
}
//---
return descr;
}

See also
ENUM _APPLIED_PR ICE

© 2000-2025, MetaQuotes Ltd.


1083 Predefined Variables

int _Digits
The _Digits variable stores number of digits after a decimal point, which defines the price accuracy of
the symbol of the current chart.
You may also use the Digits() function.

© 2000-2025, MetaQuotes Ltd.


1084 Predefined Variables

double _Point
The _Point variable contains the point size of the current symbol in the quote currency.
You may also use the Point() function.

© 2000-2025, MetaQuotes Ltd.


1085 Predefined Variables

int _LastError
The _LastError variable contains code of the last error, that occurred during the mql5-program run. Its
value can be reset to zero by ResetLastError().
To obtain the code of the last error, you may also use the GetLastError() function.

© 2000-2025, MetaQuotes Ltd.


1086 Predefined Variables

ENUM_TIMEFRAMES _Period
The _Period variable contains the value of the timeframe of the current chart.
Also you may use the Period() function.
See also

PeriodS econds, Chart timeframes, Date and Time, Visibility of objects

© 2000-2025, MetaQuotes Ltd.


1087 Predefined Variables

_RandomSeed
Variable forstoring the current state when generating pseudo-random integers. _RandomS eed changes
its value when calling MathRand(). Use MathS rand() to set the required initial condition.
x random number received by MathRand() function is calculated in the following way at each call:
x=_RandomSeed*214013+2531011;
_RandomSeed=x;
x=(x>>16)&0x7FFF;

See also
MathRand(), MathS rand(), Integer types

© 2000-2025, MetaQuotes Ltd.


1088 Predefined Variables

int _StopFlag
The _S topFlag variable contains the mql5 program stop flag equal to 0 during normal operation. W hen
the client terminal tries to stop the program, the variable is set to a value other than zero.
To check the state of the _S topFlag you may also use the Is S topped() function.

© 2000-2025, MetaQuotes Ltd.


1089 Predefined Variables

string _Symbol
The _S ymbol variable contains the symbol name of the current chart.
You may also use the S ymbol() function.

© 2000-2025, MetaQuotes Ltd.


1090 Predefined Variables

int _UninitReason
The _UninitReason variable contains the code of the program uninitialization reason.
Usually, this code is obtained by UninitializeReason()the function.

© 2000-2025, MetaQuotes Ltd.


1091 Predefined Variables

int _IsX64
The _Is X64 variable allows finding out the bit version of the terminal, in which an MQL5 application is
running: _Is X64=0 for the 32-bit terminal and _Is X64!=0 for the 64-bit terminal.
Also, function TerminalInfoInteger(TERMINAL_X64) can be used.
Example:

// Checking the terminal, in which the program is running


Print("_IsX64=",_IsX64);
if(_IsX64)
Print("Program ",__FILE__," is running in the 64-bit terminal");
else
Print("Program ",__FILE__," is running in the 32-bit terminal");
Print("TerminalInfoInteger(TERMINAL_X64)=",TerminalInfoInteger(TERMINAL_X64));

See also
MQLInfoInteger, Importing functions (#import)

© 2000-2025, MetaQuotes Ltd.


1092 Common Functions

Common Functions
General-purpose functions not included into any specialized group are listed here.

Function Action

Alert Displays a message in a separate window


CheckPointer R eturns the type of the object pointer
Comment Outputs a comment in the left top corner of the chart
CryptEncode Transforms the data from array with the specified method
CryptDecode Performs the inverse transformation of the data from array
Debug Break Program breakpoint in debugging
ExpertR emove S tops Expert Advisor and unloads it from the chart
GetPointer R eturns the object pointer
GetTick Count R eturnsthe number of milliseconds that have elapsed since the system
was started
GetTick Count64 R eturnsthe number of milliseconds that have elapsed since the system
was started
GetMicrosecondCount R eturns
the number of microseconds that have elapsed since the start
of MQL5 program
MessageBox Creates, displays a message box and manages it
PeriodS econds R eturns the number of seconds in the period
PlayS ound 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
R esetLastError S ets the value of a predetermined variable _LastError to zero
R esourceCreate Creates an image resource based on a data set
R esourceFree Deletes dynamically created resource (freeing the memory allocated for
it)
R esourceR eadImage R eads data from the graphical resource created by ResourceCreate()
function or saved in EX5 file during compilation
R esourceS ave S aves a resource into the specified file
S etUserError S ets the predefined variable _LastError into the value equal to
ERR_USER_ERR OR_FIRS T + user_error

S etR eturnError S etsthe code that returns the terminal process when completing the
operation.

© 2000-2025, MetaQuotes Ltd.


1093 Common Functions

Function Action

S leep S uspends execution of the current Expert Advisor or script within a


specified interval
TerminalClose Commands the terminal to complete operation
TesterHideIndicators S ets the mode of displaying/hiding indicators used in an EA
TesterS tatistics It returns the value of a specified statistic calculated based on testing
results
TesterS top Gives program operation completion command when testing
TesterDeposit Emulates
depositing funds during a test. It can be used in some money
management systems
TesterW ithdrawal Emulates the operation of money withdrawal in the process of testing
TranslateKey R eturns a Unicode character by a virtual key code
ZeroMemory R esetsa variable passed to it by reference. The variable can be of any
type, except for classes and structures that have constructors.

© 2000-2025, MetaQuotes Ltd.


1094 Common Functions

Alert
Displays a message in a separate window.
void Alert(
argument, // first value
... // other values
);

Parameters
argument
[in] Any values separated by commas. To split the information output in several lines you can use
the line feed character "\n" or "\r\n" . The number of parameters can not exceed 64.

Return Value

No return value.
Note

Arrays can't be passed to the Alert() function. Arrays should be output elementwise. Data of the
double type are output with 8 digits after the decimal point, data of the float type are displayed with
5 digits after the decimal point. To output the real numbers with a different precision or in a
scientific format, use the DoubleToS tring() function.
Data of the bool type is output as " true" or " false" strings. Dates are output as YYYY.MM.DD
HH:MI:SS . To display a date in another format use the TimeToS tring() function. Data of the color
type are output either as an R,G,B string or as a color name, if the color is present in a color set.
Alert() function does not work in the S trategy Tester.

Example:

//--- enums
enum ENUM_INTERSECT_DIRECTION
{
INTERSECT_DIRECTION_NONE= 0, // no crossing
INTERSECT_DIRECTION_UP = 1, // upward crossing
INTERSECT_DIRECTION_DOWN=-1, // downward crossing
};

//--- input parameters


input uint InpPeriod = 10; // MA Period
input int InpShift = 0; // MA Shift
input ENUM_MA_METHOD InpMethod = MODE_SMA; // MA Method
input ENUM_APPLIED_PRICE InpPrice = PRICE_CLOSE; // MA Applied price

//--- global variables


int ExtMaHandle;
int ExtMaPeriod;

© 2000-2025, MetaQuotes Ltd.


1095 Common Functions

double ExtData[2];
MqlRates ExtRates[2];

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- the period for calculating the moving average will be equal to the default value (10) if zero
ExtMaPeriod=int(InpPeriod<1 ? 10 : InpPeriod);
//--- create a handle for the Moving Average indicator with the specified parameters
ExtMaHandle=iMA(Symbol(),PERIOD_CURRENT,ExtMaPeriod,InpShift,InpMethod,InpPrice);
ResetLastError();
if(ExtMaHandle==INVALID_HANDLE)
{
PrintFormat("Failed to create iMA() handle. Error code: %d",GetLastError());
return(INIT_FAILED);
}

//--- get the time of the last price update


datetime tick_time=TickTime();
//--- get moving average data and price data from the last two bars
if(GetData(ExtMaHandle,ExtData,ExtRates) && tick_time!=0)
{
//--- if the price is above the MA
if(ExtRates[1].close>ExtData[1])
{
//--- create a message text and display Alert
string message=StringFormat("Bar time: %s. The price is above the moving average",TimeToSt
Alert(message+" at "+TimeToString(tick_time,TIME_DATE|TIME_MINUTES|TIME_SECONDS));
/*
Result:
Alert: Bar time: 2024.02.16 18:00. The price is above the moving average at 2024.02.16 18:
*/
}
else
{
//--- if the price is below the MA
if(ExtRates[1].close<ExtData[1])
{
//--- create a message text and display Alert
string message=StringFormat("Bar time: %s. The price is below the moving average.",Time
Alert(message+" at "+TimeToString(tick_time,TIME_DATE|TIME_MINUTES|TIME_SECONDS));
/*
Result:
Alert: Bar time: 2024.02.16 19:00. The price is below the moving average at 2024.02.16
*/
}
else

© 2000-2025, MetaQuotes Ltd.


1096 Common Functions

{
//--- create a message text and display Alert
string message=StringFormat("Bar time: %s. The price and moving average are equal.",Tim
Alert(message+" at "+TimeToString(tick_time,TIME_DATE|TIME_MINUTES|TIME_SECONDS));
/*
Result:
Alert: Bar time: 2024.02.16 20:00. The price and moving average are equal at 2024.02.16
*/
}
}
}

//--- successful
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
ResetLastError();
//--- get moving average data and price data from the last two bars
if(!GetData(ExtMaHandle,ExtData,ExtRates))
return;
//--- get the direction of the price crossing the moving average on the current bar
ENUM_INTERSECT_DIRECTION intersect=GetIntersectDirection(ExtData,ExtRates);

//--- variable for saving the previous message


static string message_prev="";

//--- if the price has crossed the moving average on the current bar upwards
if(intersect==INTERSECT_DIRECTION_UP)
{
//--- get the tick time, at which the crossing occurred
datetime tick_time=TickTime();
if(tick_time==0)
return;
//--- create a message text
string message=StringFormat("Bar time: %s. The price crossed the MA from bottom to top",TimeT
//--- if the previous message is not equal to the current one, display Alert with the message
if(message!=message_prev)
{
Alert(message+" at "+TimeToString(tick_time,TIME_DATE|TIME_MINUTES|TIME_SECONDS));
message_prev=message;
/*
Result:\
Alert: Bar time: 2024.02.16 09:00. The price crossed the MA from bottom to top at 2024.02.
*/
}

© 2000-2025, MetaQuotes Ltd.


1097 Common Functions

//--- if the price has crossed the moving average on the current bar downwards
if(intersect==INTERSECT_DIRECTION_DOWN)
{
//--- get the tick time, at which the crossing occurred
datetime tick_time=TickTime();
if(tick_time==0)
return;
//--- create a message text
string message=StringFormat("Bar time: %s. The price crossed the MA from top to bottom",TimeT
//--- if the previous message is not equal to the current one, display Alert with the message
if(message!=message_prev)
{
Alert(message+" at "+TimeToString(tick_time,TIME_DATE|TIME_MINUTES|TIME_SECONDS));
message_prev=message;
/*
Result:\
Alert: Bar time: 2024.02.16 10:00. The price crossed the MA from top to bottom at 2024.02.
*/
}
}
}
//+------------------------------------------------------------------+
//| Get price and moving average data into arrays |
//+------------------------------------------------------------------+
bool GetData(int handle,double &ma_data[],MqlRates &price_data[])
{
ResetLastError();
//--- get moving average data from the last two bars
if(CopyBuffer(handle,0,0,2,ma_data)!=2)
{
PrintFormat("CopyBuffer() failed. Error code: %d",GetLastError());
return(false);
}
//--- get price data for the last two bars
if(CopyRates(Symbol(),PERIOD_CURRENT,0,2,price_data)!=2)
{
PrintFormat("CopyRates() failed. Error code: %d",GetLastError());
return(false);
}

return(true);
}
//+------------------------------------------------------------------+
//| Return the direction of the price crossing the moving average |
//+------------------------------------------------------------------+
ENUM_INTERSECT_DIRECTION GetIntersectDirection(double &ma_data[],MqlRates &price_data[])
{

© 2000-2025, MetaQuotes Ltd.


1098 Common Functions

double ma0=ma_data[1];
double ma1=ma_data[0];
double close0=price_data[1].close;
double close1=price_data[0].close;

if(close1<=ma1 && close0>ma0)


return(INTERSECT_DIRECTION_UP);
else
{
if(close1>=ma1 && close0<ma0)
return(INTERSECT_DIRECTION_DOWN);
else
return(INTERSECT_DIRECTION_NONE);
}
}
//+------------------------------------------------------------------+
//| Return the tick time in seconds |
//+------------------------------------------------------------------+
datetime TickTime()
{
MqlTick tick={};

ResetLastError();
if(!SymbolInfoTick(Symbol(),tick))
{
PrintFormat("SymbolInfoTick() failed. Error code: %d",GetLastError());
return(0);
}

return(tick.time);
}

© 2000-2025, MetaQuotes Ltd.


1099 Common Functions

CheckPointer
The function returns the type of the object pointer.
ENUM_POINTER_TYPE CheckPointer(
object* anyobject // object pointer
);

Parameters
anyobject
[in] Object pointer.

Return value

R eturns a value from the ENUM _POINTER_TYPE enumeration.


Note

An attempt to call an incorrect pointer results in the critical termination of a program. That's why
it's necessary to call the CheckPointer function before using a pointer. A pointer can be incorrect in
the following cases :
· the pointer is equal to NULL;
· the object has been deleted using the delete operator.
This function can be used for checking pointer validity. A non-zero value warranties that the pointer
can be used for accessing.
To quickly validate the pointer, you can also use operator "!" (example) which checks it via an
implicit call of the CheckPointer function.
Example:

//+------------------------------------------------------------------+
//| Deletes list by deleting its elements |
//+------------------------------------------------------------------+
void CMyList::Destroy()
{
//--- service pointer for working in the loop
CItem* item;
//--- go through loop and try to delete dynamic pointers
while(CheckPointer(m_items)!=POINTER_INVALID)
{
item=m_items;
m_items=m_items.Next();
if(CheckPointer(item)==POINTER_DYNAMIC)
{
Print("Dynamic object ",item.Identifier()," to be deleted");
delete (item);
}
else Print("Non-dynamic object ",item.Identifier()," cannot be deleted");
}

© 2000-2025, MetaQuotes Ltd.


1100 Common Functions

//---
}

See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete

© 2000-2025, MetaQuotes Ltd.


1101 Common Functions

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] Anyvalues, 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 2045 characters (excess symbols will be
cut out during output).

Return Value

No return value
Note

Arrays can't be passed to the Comment() function. Arrays must be entered element-by-element.
Data of double type are output 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 notation 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 DoubleToS tring() function.
Data of bool type are output as " true" or " false" strings. Dates are shown as YYYY.MM.DD HH:MI:SS .
To show dates in another format, use the TimeToS tring() function. Data of color type are output
either as R,G,B string or as a color name, if this color is present in the color set.
Comment() function does not work during optimization in the S trategy Tester.
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
ChartS etS tring, ChartGetS tring

© 2000-2025, MetaQuotes Ltd.


1102 Common Functions

CryptEncode
Transforms the data from array with the specified method.
int CryptEncode(
ENUM_CRYPT_METHOD method, // method
const uchar& data[], // source array
const uchar& key[], // key
uchar& result[] // destination array
);

Parameters
method
[in] Data transformation method. Can be one of the values of ENUM _CRYPT _M ET H OD
enumeration.
data[]
[in] S ource array.

key[]
[in] Key array.

result[]
[out] Destination array.

Return Value

Amount of bytes in the destination array or 0 in case of error. To obtain information about the error
call the GetLastError() function.
Example:

//+------------------------------------------------------------------+
//| ArrayToHex |
//+------------------------------------------------------------------+
string ArrayToHex(uchar &arr[],int count=-1)
{
string res="";
//--- check
if(count<0 || count>ArraySize(arr))
count=ArraySize(arr);
//--- transform to HEX string
for(int i=0; i<count; i++)
res+=StringFormat("%.2X",arr[i]);
//---
return(res);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()

© 2000-2025, MetaQuotes Ltd.


1103 Common Functions

{
string text="The quick brown fox jumps over the lazy dog";
string keystr="ABCDEFG";
uchar src[],dst[],key[];
//--- prepare key
StringToCharArray(keystr,key);
//--- copy text to source array src[]
StringToCharArray(text,src);
//--- print initial data
PrintFormat("Initial data: size=%d, string='%s'",ArraySize(src),CharArrayToString(src));
//--- encrypt src[] with DES 56-bit key in key[]
int res=CryptEncode(CRYPT_DES,src,key,dst);
//--- check error
if(res>0)
{
//--- print encrypted data
PrintFormat("Encoded data: size=%d %s",res,ArrayToHex(dst));
//--- decode dst[] to src[]
res=CryptDecode(CRYPT_DES,dst,key,src);
//--- check error
if(res>0)
{
//--- print decoded data
PrintFormat("Decoded data: size=%d, string='%s'",ArraySize(src),CharArrayToString(src));
}
else
Print("Error in CryptDecode. Error code=",GetLastError());
}
else
Print("Error in CryptEncode. Error code=",GetLastError());
}

See also
Array Functions, CryptDecode()

© 2000-2025, MetaQuotes Ltd.


1104 Common Functions

CryptDecode
Performs the inverse transformation of the data from array, tranformed by CryptEncode().
int CryptEncode(
ENUM_CRYPT_METHOD method, // method
const uchar& data[], // source array
const uchar& key[], // key
uchar& result[] // destination array
);

Parameters
method
[in] Data transformation method. Can be one of the values of ENUM _CRYPT _M ET H OD
enumeration.
data[]
[in] S ource array.

key[]
[in] Key array.

result[]
[out] Destination array.

Return Value

Amount of bytes in the destination array or 0 in case of error. To obtain information about the error
call the GetLastError() function.

Example:

input string InpKey = "ABCDEFG"; // Encryption key

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string text="The quick brown fox jumps over the lazy dog";
uchar src[],dst[],key[];

//--- prepare the encryption key


StringToCharArray(InpKey,key);
//--- prepare the src[] source array
StringToCharArray(text,src);
//--- display source data
PrintFormat("Initial data: size=%d, string='%s'",ArraySize(src),CharArrayToString(src));

© 2000-2025, MetaQuotes Ltd.


1105 Common Functions

//--- encrypt the src[] array using the DES method with the key[] 56-bit key
int res=CryptEncode(CRYPT_DES,src,key,dst);

//--- check the encryption result


if(res>0)
{
//--- display encrypted data
PrintFormat("Encoded data: size=%d %s",res,ArrayToHex(dst));
//--- decrypt the dst[] array data using the DES method with the key[] 56-bit key
res=CryptDecode(CRYPT_DES,dst,key,src);
//--- check the result
if(res>0)
{
//--- display decrypted data
PrintFormat("Decoded data: size=%d, string='%s'",ArraySize(src),CharArrayToString(src));
}
else
Print("CryptDecode failed. Error: ",GetLastError());
}
else
Print("CryptEncode failed. Error: ",GetLastError());
}
//+------------------------------------------------------------------+
//| ArrayToHex |
//+------------------------------------------------------------------+
string ArrayToHex(uchar &arr[],int count=-1)
{
string res="";

//--- check the size


if(count<0 || count>ArraySize(arr))
count=ArraySize(arr);

//--- convert to hexadecimal string


for(int i=0; i<count; i++)
res+=StringFormat("%.2X",arr[i]);

return(res);
}

See also
Array Functions, CryptEncode()

© 2000-2025, MetaQuotes Ltd.


1106 Common Functions

DebugBreak
It is a program breakpoint in debugging.
void DebugBreak();

Return Value

No return value.
Note

Execution of an MQL5 program is interrupted only if a program is started in a debugging mode. The
function can be used for viewing values of variables and/or for further step-by-step execution.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- compile the file using F5
//--- in debugging mode, if i == j, stop at the DebugBreak() string
for(int i=0,j=20; i<20; i++,j--)
{
if(i==j)
DebugBreak();
}
}

© 2000-2025, MetaQuotes Ltd.


1107 Common Functions

ExpertRemove
The function stops an Expert Advisor and unloads it from a chart.
void ExpertRemove();

Return Value

No return value.
Note

The Expert Advisor is not stopped immediately as you call ExpertRemove(); just a flag to stop the
EA operation is set. That is, any next event won't be processed, OnDeinit() will be called and the
Expert Advisor will be unloaded and removed from the chart.

Calling ExpertRemove() in the strategy tester inside the OnInit() handler cancels testing on the
current set of parameters. S uch completion is considered an initialization error.
W hen calling ExpertR emove() in the strategy tester after successful initialization of an EA, a test is
completed normally with the call of OnDeinit() and OnTester(). In this case, the entire trading
statistics and an optimization criterion value are obtained.
Example:

//+------------------------------------------------------------------+
//| Test_ExpertRemove.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
input int ticks_to_close=20;// number of ticks before EA unload
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print(TimeCurrent(),": " ,__FUNCTION__," reason code = ",reason);
//--- "clear" comment
Comment("");
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
static int tick_counter=0;
//---

© 2000-2025, MetaQuotes Ltd.


1108 Common Functions

tick_counter++;
Comment("\nBefore unloading expert advisor ",__FILE__," left",
(ticks_to_close-tick_counter)," ticks");
//--- before
if(tick_counter>=ticks_to_close)
{
ExpertRemove();
Print(TimeCurrent(),": ",__FUNCTION__," expert advisor will be unloaded");
}
Print("tick_counter =",tick_counter);
//---
}
//+------------------------------------------------------------------+

See also
Program running, Client terminal events

© 2000-2025, MetaQuotes Ltd.


1109 Common Functions

GetPointer
The function returns the object pointer.
void* GetPointer(
any_class anyobject // object of any class
);

Parameters
anyobject
[in] Object of any class.

Return Value

The function returns the object pointer.


Note

Only class objects have pointers. Instances of structures and simple-type variables can't have
pointers. The class object not created using the new() operator, but, e.g., automatically created in
the array of objects, still has a pointer. But this pointer will be of the automatic type
POINTER_AUTOM ATIC, therefore the delete() operator can't be applied to it. Aside from that, the
type pointer doesn't differ from dynamic pointers of the POINTER_DYNAMIC type.
S ince variables of structure types and simple types do not have pointers, it's prohibited to apply the
GetPointer() function to them. It's also prohibited to pass the pointer as a function argument. In all
these cases the compiler will notify an error.
An attempt to call an incorrect pointer causes the critical termination of a program. That's why the
CheckPointer() function should be called prior to using a pointer. A pointer can be incorrect in the
following cases :
· the pointer is equal to NULL;
· the object has been deleted using the delete operator.
This function can be used to check the validity of a pointer. A non-zero value guarantees, that the
pointer can be used for accessing.
Example:

//+------------------------------------------------------------------+
//| Check_GetPointer.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"

//+------------------------------------------------------------------+
//| Class implementing the list element |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1110 Common Functions

class CItem
{
int m_id;
string m_comment;
CItem* m_next;
public:
CItem() { m_id=0; m_comment=NULL; m_next=NULL; }
~CItem() { Print("Destructor of ",m_id,
(CheckPointer(GetPointer(this))==POINTER_DYNAMIC)?
"dynamic":"non-dynamic"); }
void Initialize(int id,string comm) { m_id=id; m_comment=comm; }
void PrintMe() { Print(__FUNCTION__,":",m_id,m_comment); }
int Identifier() { return(m_id); }
CItem* Next() {return(m_next); }
void Next(CItem *item) { m_next=item; }
};
//+------------------------------------------------------------------+
//| Simplest class of the list |
//+------------------------------------------------------------------+
class CMyList
{
CItem* m_items;
public:
CMyList() { m_items=NULL; }
~CMyList() { Destroy(); }
bool InsertToBegin(CItem* item);
void Destroy();
};
//+------------------------------------------------------------------+
//| Inserts list element at the beginning |
//+------------------------------------------------------------------+
bool CMyList::InsertToBegin(CItem* item)
{
if(CheckPointer(item)==POINTER_INVALID) return(false);
//---
item.Next(m_items);
m_items=item;
//---
return(true);
}
//+------------------------------------------------------------------+
//| Deleting the list by deleting elements |
//+------------------------------------------------------------------+
void CMyList::Destroy()
{
//--- service pointer to work in a loop
CItem* item;
//--- go through the loop and try to delete dynamic pointers
while(CheckPointer(m_items)!=POINTER_INVALID)

© 2000-2025, MetaQuotes Ltd.


1111 Common Functions

{
item=m_items;
m_items=m_items.Next();
if(CheckPointer(item)==POINTER_DYNAMIC)
{
Print("Dynamyc object ",item.Identifier()," to be deleted");
delete (item);
}
else Print("Non-dynamic object ",item.Identifier()," cannot be deleted");
}
//---
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
CMyList list;
CItem items[10];
CItem* item;
//--- create and add into the list a dynamic object pointer
item=new CItem;
if(item!=NULL)
{
item.Initialize(100,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- add automatic pointers into the list
for(int i=0; i<10; i++)
{
items[i].Initialize(i,"automatic");
items[i].PrintMe();
item=GetPointer(items[i]);
if(CheckPointer(item)!=POINTER_INVALID)
list.InsertToBegin(item);
}
//--- add one more dynamic object pointer at the list beginning
item=new CItem;
if(item!=NULL)
{
item.Initialize(200,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- delete all the list elements
list.Destroy();
//--- all the list elements will be deleted after the script is over
//--- see the Experts tab in the terminal

© 2000-2025, MetaQuotes Ltd.


1112 Common Functions

See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete

© 2000-2025, MetaQuotes Ltd.


1113 Common Functions

GetTickCount
The GetTickCount() function returns the number of milliseconds that elapsed since the system start.
uint GetTickCount();

Return Value

Value of uint 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 days if a computer works uninterruptedly.
Example:

#define MAX_SIZE 40
//+------------------------------------------------------------------+
//| Script for measuring computation time of 40 Fibonacci numbers |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Remember the initial value
uint start=GetTickCount();
//--- A variable for getting the next number in the Fibonacci series
long fib=0;
//--- In loop calculate the specified amount of numbers from Fibonacci series
for(int i=0;i<MAX_SIZE;i++) fib=TestFibo(i);
//--- Get the spent time in milliseconds
uint time=GetTickCount()-start;
//--- Output a message to the Experts journal
PrintFormat("Calculating %d first Fibonacci numbers took %d ms",MAX_SIZE,time);
//--- Script completed
return;
}
//+------------------------------------------------------------------+
//| Function for getting Fibonacci number by its serial number |
//+------------------------------------------------------------------+
long TestFibo(long n)
{
//--- The first member of the Fibonacci series
if(n<2) return(1);
//--- All other members are calculated by the following formula
return(TestFibo(n-2)+TestFibo(n-1));
}

See also

Date and Time, EventS etMillisecondTimer, GetTick Count64, GetMicrosecondCount

© 2000-2025, MetaQuotes Ltd.


1114 Common Functions

GetTickCount64
The GetTickCount64() function returns the number of milliseconds that have elapsed since the system
was launched.
ulong GetTickCount64();

Return Value

A ulong type value.


Note

The counter is limited to the accuracy of the system timer, which usually returns a result with the
10-16 millisecond precision. Unlik e GetTick Count, which is of uint type and the contents of which
overflow every 49.7 days in the case of continued computer operation, GetTickCount64() can be
used for the unlimited computer operation time and is not subject to overflow.

Example:

#define MAX_SIZE 40

//+------------------------------------------------------------------+
//| Script for measuring the time of calculating 40 Fibo numbers |
//+------------------------------------------------------------------+
void OnStart()
{
long fib_array[MAX_SIZE];

//--- store the initial value


ulong start=GetTickCount64();
//--- a loop, in which we calculate a given number of numbers from the Fibo series
for(int i=0;i<MAX_SIZE;i++)
fib_array[i]=TestFibo(i);
//--- get the spent time in milliseconds
ulong time=GetTickCount64()-start;

//--- display the error message in the Experts journal


ArrayPrint(fib_array);
PrintFormat("Calculating the first %d Fibonacci numbers took %I64u ms",MAX_SIZE,time);
}
//+------------------------------------------------------------------+
//| Function for obtaining a Fibo number by its serial number |
//+------------------------------------------------------------------+
long TestFibo(long n)
{
//--- first member of the Fibo series
if(n<2)
return(1);
//--- all subsequent members are calculated using this equation

© 2000-2025, MetaQuotes Ltd.


1115 Common Functions

return(TestFibo(n-2)+TestFibo(n-1));
}

See also

Date and Time, EventS etMillisecondTimer, GetTick Count, GetMicrosecondCount

© 2000-2025, MetaQuotes Ltd.


1116 Common Functions

GetMicrosecondCount
The GetMicrosecondCount() function returns the number of microseconds that have elapsed since the
start of MQL5-program.
ulong GetMicrosecondCount();

Return Value

Value of ulong type.


Example:

//+------------------------------------------------------------------+
//| Test function |
//+------------------------------------------------------------------+
void Test()
{
int res_int=0;
double res_double=0;
//---
for(int i=0;i<10000;i++)
{
res_int+=i*i;
res_int++;
res_double+=i*i;
res_double++;
}
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
uint ui=0,ui_max=0,ui_min=INT_MAX;
ulong ul=0,ul_max=0,ul_min=INT_MAX;
//--- number of measurements
for(int count=0;count<1000;count++)
{
uint ui_res=0;
ulong ul_res=0;
//---
for(int n=0;n<2;n++)
{
//--- select measurement type
if(n==0) ui=GetTickCount();
else ul=GetMicrosecondCount();
//--- execute code
Test();
//--- add measurement result (depending on type)

© 2000-2025, MetaQuotes Ltd.


1117 Common Functions

if(n==0) ui_res+=GetTickCount()-ui;
else ul_res+=GetMicrosecondCount()-ul;
}
//--- calculate minimum and maximum time for both measurements
if(ui_min>ui_res) ui_min=ui_res;
if(ui_max<ui_res) ui_max=ui_res;
if(ul_min>ul_res) ul_min=ul_res;
if(ul_max<ul_res) ul_max=ul_res;
}
//---
Print("GetTickCount error(msec): ",ui_max-ui_min);
Print("GetMicrosecondCount error(msec): ",DoubleToString((ul_max-ul_min)/1000.0,2));
}

See also

Date and Time, GetTick Count, GetTick Count64

© 2000-2025, MetaQuotes Ltd.


1118 Common Functions

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 flags defining appearance and behavior of a message box. Flags can be a
combination of a special group of flags.

Return Value

If the function is successfully performed, the returned value is one of values of MessageBox() return
codes.
Note

The function cannot be used in custom indicators since calling MessageBox() suspends the thread of
execution for the whole time while waiting for the user's response. S ince all indicators for each
symbol are executed in a single thread, such suspension makes the operation of all charts on all
timeframes for this symbol impossible.
MessageBox() function does not work in the S trategy Tester.

Example:

//+------------------------------------------------------------------+
//| The EA displays MessageBox window with a request for further work|
//| upon reaching specified number of series of unprofitable trades |
//| Wait for the specified number of bars and display MessageBox |
//| with a request to continue work. |
//| To check, we need to manually open and close several positions |
//| with a loss, since the EA does not control |
//| its own "positions" by magic number for simplicity. |
//+------------------------------------------------------------------+

//--- input parameters

© 2000-2025, MetaQuotes Ltd.


1119 Common Functions

input uint InpMaxLossDeals = 3; // Max Loss deals


input uint InpInactivityNumBars = 5; // Number of bars of advisor inactivity

//--- global variables


bool ExtFirstStart=true; // First launch flag
bool ExtFlag=true; // Flag for allowing the EA to work
uint ExtNumLoss; // Number of consecutive unprofitable trades
datetime ExtTimeLastLoss; // Time of the last trade to close a losing position

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- get the number of losing trades in a row and the time of the last trade to close the position
ExtNumLoss=GetNumLosingTradesInRow(ExtTimeLastLoss);

return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Comment("");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- determine how many bars have passed since the last closed losing position in the series
int bars_remaining=iBarShift(Symbol(),PERIOD_CURRENT,ExtTimeLastLoss);

//--- if this is the first launch


if(ExtFirstStart)
{
//--- If a specified number of bars have already passed after a series of unprofitable positi
if(bars_remaining>(int)InpInactivityNumBars)
ExtFlag=true;
ExtFirstStart=false;
}

//--- if the EA operation flag is disabled


if(!ExtFlag)
{
Comment(StringFormat("The advisor is stopped for %d bars. Num Loss positions: %u, Time last l
(InpInactivityNumBars-bars_remaining),ExtNumLoss,TimeToString(ExtTimeLast
//--- if a specified number of bars have passed after a series of unprofitable positions

© 2000-2025, MetaQuotes Ltd.


1120 Common Functions

if(bars_remaining>(int)InpInactivityNumBars)
{
//--- display MessageBox window with the specified text and window title
//--- the request window has two Yes/No buttons and an icon with a question mark.
//--- the Yes button is selected by default.
string mb_text="The specified number of bars of EA inactivity have passed.\n Continue its
string mb_caption="Please note";
int mb_id=MessageBox(mb_text,mb_caption,MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON1);
//--- if the return code from MessageBox is the Yes button pressed, set the EA operation f
if(mb_id==IDYES)
{
ExtFlag=true;
return;
}
}
//--- the EA operation flag is disabled, exit OnTick()
return;
}

//--- the EA operation flag is set - the EA works as provided by the code below
Comment(StringFormat("The advisor is working. Num Loss positions: %u, Time last loss: %s, Elapse
ExtNumLoss,TimeToString(ExtTimeLastLoss,TIME_DATE|TIME_MINUTES|TIME_SECONDS),bars_remain
}
//+------------------------------------------------------------------+
//| TradeTransaction function |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
const MqlTradeRequest& request,
const MqlTradeResult& result)
{
//--- if the transaction type is adding a transaction to history
if(trans.type==TRADE_TRANSACTION_DEAL_ADD)
{
//--- get a deal ticket and select a deal from the list by ticket
ulong deal_ticket=trans.deal;
if(HistoryDealSelect(deal_ticket))
{
//--- if this is a market exit trade, get the number of losing trades in a row and the tim
ENUM_DEAL_ENTRY entry=(ENUM_DEAL_ENTRY)HistoryDealGetInteger(deal_ticket,DEAL_ENTRY);
if(entry==DEAL_ENTRY_OUT || entry==DEAL_ENTRY_INOUT || entry==DEAL_ENTRY_OUT_BY)
ExtNumLoss=GetNumLosingTradesInRow(ExtTimeLastLoss);
}
}

//--- if the number of losing trades in a row is greater than the specified value and the EA operat
if(ExtNumLoss>=InpMaxLossDeals && ExtFlag)
{
//--- display MessageBox window with the specified text and window title
//--- the request window has two Yes/No buttons and an icon with an exclamation mark.

© 2000-2025, MetaQuotes Ltd.


1121 Common Functions

//--- the No button is selected by default.


string mb_text="The number of losing trades has reached the specified maximum. The advisor is
string mb_caption="Attention!";
int mb_id=MessageBox(mb_text,mb_caption,MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2);
//--- if the return code from MessageBox is the No button pressed, disable the EA operation f
if(mb_id==IDNO)
ExtFlag=false;
}
}
//+------------------------------------------------------------------+
//| Return the number of consecutive unprofitable trades |
//| and the time of the last trade to close a losing position |
//+------------------------------------------------------------------+
uint GetNumLosingTradesInRow(datetime &time_last_deal)
{
//--- select the entire history
if(!HistorySelect(0,TimeCurrent()))
return(0);

//--- get the next trade ticket by the list of historical deals in a loop
uint res=0;
uint total=HistoryDealsTotal();
for(int i=(int)total-1; i>=0; i--)
{
ulong deal_ticket=HistoryDealGetTicket(i);
if(deal_ticket>0)
{
//--- if the deal is not for exiting the position, move on to the next one
ENUM_DEAL_ENTRY entry=(ENUM_DEAL_ENTRY)HistoryDealGetInteger(deal_ticket,DEAL_ENTRY);
if(entry!=DEAL_ENTRY_OUT && entry!=DEAL_ENTRY_OUT_BY && entry!=DEAL_ENTRY_INOUT)
continue;
//--- if the result of closing a position has a profit, interrupt the loop
if(!IsClosePositionWithLoss(deal_ticket))
break;
//--- increase the counter of consecutive loss-making trades
res++;
//--- write the maximum trade time into a variable (looking for the last one)
datetime deal_time=(datetime)HistoryDealGetInteger(deal_ticket,DEAL_TIME);
if(deal_time>time_last_deal)
time_last_deal=deal_time;
}
}

//--- return the number of consecutive losses


return(res);
}
//+------------------------------------------------------------------+
//| Return the flag of closing a position with a loss |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1122 Common Functions

bool IsClosePositionWithLoss(const ulong deal_ticket)


{
//--- get the values of the properties affecting profit from the trade
double profit=HistoryDealGetDouble(deal_ticket,DEAL_PROFIT);
double comission=HistoryDealGetDouble(deal_ticket,DEAL_COMMISSION);
double swap=HistoryDealGetDouble(deal_ticket,DEAL_SWAP);
double fee=HistoryDealGetDouble(deal_ticket,DEAL_FEE);

//--- return the flag indicating that the total value of the received properties is negative
return(profit+comission+swap+fee<0);
}

© 2000-2025, MetaQuotes Ltd.


1123 Common Functions

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 _TIM EFRAM ES . If the parameter isn't
specified, it returns the number of seconds of the current chart period, at which the program runs.

Return Value

Number of seconds in a selected period.

Example:

//--- input parameters


input ENUM_TIMEFRAMES InpPeriod1 = PERIOD_CURRENT; // First Period
input ENUM_TIMEFRAMES InpPeriod2 = PERIOD_M1; // Second Period

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the number of seconds in the InpPeriod1 and InpPeriod2 chart periods
int sec1=PeriodSeconds(InpPeriod1);
int sec2=PeriodSeconds(InpPeriod2);
//--- display the received values in the log
PrintFormat("Seconds in period %s: %lu, in period %s: %lu",TimeframeDescription(InpPeriod1),sec1
//--- calculate how many bars of the InpPeriod2 chart period are contained in a bar with the chart
int res=sec1/sec2;
if(res==0)
res=1;
//--- display the obtained value in the log
PrintFormat("One bar %s contains %d bars %s",TimeframeDescription(InpPeriod1),res,TimeframeDescr
/*
Result:
Seconds in period M5: 300, in period M1: 60
One bar M5 contains 5 bars M1
*/
}
//+------------------------------------------------------------------+
//| Return the timeframe name |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1124 Common Functions

string TimeframeDescription(const ENUM_TIMEFRAMES period)


{
return(StringSubstr(EnumToString(period==PERIOD_CURRENT ? Period() : period), 7));
}

See also

_Period, Chart timeframes, Date and Time, Visibility of objects

© 2000-2025, MetaQuotes Ltd.


1125 Common Functions

PlaySound
It plays a sound file.
bool PlaySound(
string filename // file name
);

Parameters
filename
[in] Path to a sound file. If filename=NULL, the playback is stopped.

Return Value

true – if the file is found, otherwise - false.


Note

The file must be located in terminal_directory\S ounds or its sub-directory. Only WAV files are
played.
Call of PlayS ound() with NULL parameter stops playback.
PlayS ound() function does not work in the S trategy Tester.

Example:

#include <Trade\Trade.mqh>
#define MAGIC (123)

//--- input parameters


input string InpFileNameOK = "ok.wav"; // success audio file
input string InpFileNameErr = "timeout.wav"; // error audio file
input ENUM_ORDER_TYPE InpOrderType = ORDER_TYPE_BUY_LIMIT; // order type
input double InpLots = 0.1; // lots

//--- global variables


CTrade ExtTrade;

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set the magic and order type by execution according to the symbol settings
ExtTrade.SetExpertMagicNumber(MAGIC);
ExtTrade.SetTypeFillingBySymbol(Symbol());
//--- call the function of placing an order or opening a position with sound playback
OrderSendWithAudio();
}

© 2000-2025, MetaQuotes Ltd.


1126 Common Functions

//+------------------------------------------------------------------+
//| The function places an order or opens a position |
//| and plays the sound of success or error |
//+------------------------------------------------------------------+
void OrderSendWithAudio(void)
{
bool res=true;
MqlTick tick= {};

ResetLastError();
if(!SymbolInfoTick(Symbol(),tick))
{
Print("SymbolInfoTick() failed. Error code: ",GetLastError());
PlaySound(InpFileNameErr);
return;
}
//--- send a request to the server
switch(InpOrderType)
{
case ORDER_TYPE_BUY :
res=ExtTrade.Buy(InpLots);
break;
case ORDER_TYPE_BUY_LIMIT :
res=ExtTrade.BuyLimit(InpLots,NormalizeDouble(tick.ask-100*Point(),Digits()));
break;
case ORDER_TYPE_BUY_STOP :
res=ExtTrade.BuyStop(InpLots,NormalizeDouble(tick.ask+100*Point(),Digits()));
break;
case ORDER_TYPE_SELL :
res=ExtTrade.Sell(InpLots);
break;
case ORDER_TYPE_SELL_LIMIT :
res=ExtTrade.SellLimit(InpLots,NormalizeDouble(tick.bid+100*Point(),Digits()));
break;
case ORDER_TYPE_SELL_STOP :
res=ExtTrade.SellStop(InpLots,NormalizeDouble(tick.bid-100*Point(),Digits()));
break;
default :
res=false;
}
if(!res)
Print("Error ",GetLastError());
Print(ExtTrade.ResultRetcodeDescription());

//--- if the request is accepted, play the ok.wav sound


if(ExtTrade.ResultRetcode()==TRADE_RETCODE_DONE)
PlaySound(InpFileNameOK);
else
PlaySound(InpFileNameErr);

© 2000-2025, MetaQuotes Ltd.


1127 Common Functions

See also

R esources

© 2000-2025, MetaQuotes Ltd.


1128 Common Functions

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. The number of parameters cannot 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 PrintFormat() 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 TimeToS tring(). 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.
Print() function does not work during optimization in the S trategy Tester.
Example:

void OnStart()
{
//--- Output DBL_MAX using Print(), this is equivalent to PrintFormat(%%.16G,DBL_MAX)
Print("---- how DBL_MAX looks like -----");
Print("Print(DBL_MAX)=",DBL_MAX);
//--- Now output a DBL_MAX number using PrintFormat()
PrintFormat("PrintFormat(%%.16G,DBL_MAX)=%.16G",DBL_MAX);
//--- Output to the Experts journal
// Print(DBL_MAX)=1.797693134862316e+308
// PrintFormat(%.16G,DBL_MAX)=1.797693134862316E+308

//--- See how float is output


float c=(float)M_PI; // We should explicitly cast to the target type
Print("c=",c, " Pi=",M_PI, " (float)M_PI=",(float)M_PI);
// c=3.14159 Pi=3.141592653589793 (float)M_PI=3.14159

//--- Show what can happen with arithmetic operations with real types
double a=7,b=200;
Print("---- Before arithmetic operations");
Print("a=",a," b=",b);
Print("Print(DoubleToString(b,16))=",DoubleToString(b,16));
//--- Divide a by b (7/200)

© 2000-2025, MetaQuotes Ltd.


1129 Common Functions

a=a/b;
//--- Now emulate restoring a value in the b variable
b=7.0/a; // It is expected that b=7.0/(7.0/200.0)=>7.0/7.0*200.0=200 - but it differs
//--- Output the newly calculated value of b
Print("----- After arithmetic operations");
Print("Print(b)=",b);
Print("Print(DoubleToString(b,16))=",DoubleToString(b,16));
//--- Output to the Experts journal
// Print(b)=200.0
// Print(DoubleToString(b,16))=199.9999999999999716 (see that b is no more equal to 200.0)

//--- Create a very small value epsilon=1E-013


double epsilon=1e-13;
Print("---- Create a very small value");
Print("epsilon=",epsilon); // Get epsilon=1E-013
//--- Now subtract epsilon from b and again output the value to the Experts journal
b=b-epsilon;
//--- Use two ways
Print("---- After subtracting epsilon from the b variable");
Print("Print(b)=",b);
Print("Print(DoubleToString(b,16))=",DoubleToString(b,16));
//--- Output to the Experts journal
// Print(b)=199.9999999999999 (now the value of b after subtracting epsilon cannot be rounded to 2
// Print(DoubleToString(b,16))=199.9999999999998578
// (now the value of b after subtracting epsilon cannot be rounded to 200)
}

See also
DoubleToS tring, S tring Format

© 2000-2025, MetaQuotes Ltd.


1130 Common Functions

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 string
... // values of simple types
);

Parameters
format_string
[in] A format string consists of simple symbols, and if the format string 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 string.

Return Value

S tring.

Note

PrintFormat() function does not work during optimization in the S trategy Tester.
The number, order and type of parameters must exactly match the set of qualifiers, otherwise the
print result is undefined. Instead of PrintFormat() you can use printf().
If the format string is followed by parameters, this string must contain format specifications that
denote output format of these parameters. S pecification of format always starts with the percent
sign (%).
A format string is read from left to right. W hen the first format specification is met (if there is
any), the value of the first parameter after the format string 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 string end.
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 string, use the format specification %%.

flags

© 2000-2025, MetaQuotes Ltd.


1131 Common Functions

Flag Description Default Behavior

– Left justification within the set width R ight justification


(minus
)
+ Output of the + or - sign for values of sign types The sign is shown only if the
(plus) value is negative
0 Zeroes are added before an output value within the Nothing is added
(zero) 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.
space A space is shown before an output value, if it is a S paces aren't inserted
sign and positive value
# If used together with the format o, x or X , then Nothing is added
before the output value 0, 0x or 0X is added
respectively.
If used together with the format e, E, a or A, value Decimal point is shown only if
is always shown with a decimal point. there is a non-zero fractional
part.
If used together with the format g or G, flag defines Decimal point is shown only if
presence of a decimal point in the output value and there is a non-zero fractional
prevents the cutting off of leading zeroes. part. Leading zeroes are cut
Flag # is ignored when used together with formats c, off.
d , i, u , s .

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 specified 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
symbols is greater than the specified width, the output value is never cut off.
If an asteris k (*) 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 precision - number of digits after a decimal
point. As distinct from width specification, precision specification can cut off the part of fractional
type with or without rounding.
The use of precision specification is different for different format types.

© 2000-2025, MetaQuotes Ltd.


1132 Common Functions

Types Description Default Behavior

a, A Precision specification sets the number of digits Default precision – 6.


after a decimal point.
c, C Not used

d, i, S ets minimal number of output digits. If number of Default precision – 1.


u, o, digits in a corresponding parameter is less than this
x, X precision, 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 the specified
precision.
e, E, f S etsnumber of output digits after a decimal point. Default precision – 6. If set
The last digit is rounded off. precision is 0 or decimal part is
absent, the decimal point is not
shown.
g, G S ets maximal number of meaningful numbers. 6 meaningful numbers are
output.
s S ets number of output symbols of a string. If the The whole string is output.
string length exceeds the precision, the string is cut
off.

PrintFormat("1. %s", _Symbol);


PrintFormat("2. %.3s", _Symbol);
int length=4;
PrintFormat("3. %.*s", length, _Symbol);
/*
1. EURUSD
2. EUR
3. EURU
/

h | l | ll | I32 | I64

S pecification of data sizes, passed as a parameter.

Paramet Used Prefix Joint Specifier of Type


er 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 d, i, o, x, or X
case L)

© 2000-2025, MetaQuotes Ltd.


1133 Common Functions

Paramet Used Prefix Joint Specifier of Type


er Type

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 S ymbol of short type (Unicode)


C int S ymbol of char type (ANS I)
d int S igned decimal integer

i int S igned 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 doubl A real value in the format [-] d.dddde[sign] ddd, where d - one decimal digit,
e dddd - one or more decimal digits, ddd - a three-digit number that
determines the size of the exponent, sign - plus or minus
E doubl S imilarto the format of e, except that the sign of exponent is output by
e upper case letter (E instead of e)
f doubl A real value in the format [-] dddd.dddd, where dddd - one or more decimal
e 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 doubl A real value output in f or e format depending on what output is more
e compact.
G doubl A real value output in F or E format depending on what output is more
e compact.

© 2000-2025, MetaQuotes Ltd.


1134 Common Functions

Symbol Type Output Format

a doubl A real number in format [−]0xh.hhhh p±dd, where h.hhhh – mantissa in the
e form of hexadecimal digits, using " abcdef" , dd - One or more digits of
exponent. Number of decimal places is determined by the accuracy
specification
A doubl A real number in format [−]0xh.hhhh P±dd, where h.hhhh – mantissa in the
e form of hexadecimal digits, using "ABCDEF" , dd - One or more digits of
exponent. Number of decimal places is determined by the accuracy
specification
s string S tring output

Instead of PrintFormat() you can use printf().


Example:

© 2000-2025, MetaQuotes Ltd.


1135 Common Functions

void OnStart()
{
//--- trade server name
string server=AccountInfoString(ACCOUNT_SERVER);
//--- account number
int login=(int)AccountInfoInteger(ACCOUNT_LOGIN);
//--- long value output
long leverage=AccountInfoInteger(ACCOUNT_LEVERAGE);
PrintFormat("%s %d: leverage = 1:%I64d",
server,login,leverage);
//--- account currency
string currency=AccountInfoString(ACCOUNT_CURRENCY);
//--- double value output with 2 digits after the decimal point
double equity=AccountInfoDouble(ACCOUNT_EQUITY);
PrintFormat("%s %d: account equity = %.2f %s",
server,login,equity,currency);
//--- double value output with mandatory output of the +/- sign
double profit=AccountInfoDouble(ACCOUNT_PROFIT);
PrintFormat("%s %d: current result for open positions = %+.2f %s",
server,login,profit,currency);
//--- double value output with variable number of digits after the decimal point
double point_value=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
string format_string=StringFormat("%%s: point value = %%.%df",_Digits);
PrintFormat(format_string,_Symbol,point_value);
//--- int value output
int spread=(int)SymbolInfoInteger(_Symbol,SYMBOL_SPREAD);
PrintFormat("%s: current spread in points = %d ",
_Symbol,spread);
//--- double value output in the scientific (floating point) format with 17 meaningful digits after
PrintFormat("DBL_MAX = %.17e",DBL_MAX);
//--- double value output in the scientific (floating point) format with 17 meaningful digits after
PrintFormat("EMPTY_VALUE = %.17e",EMPTY_VALUE);
//--- output using PrintFormat() with default accuracy
PrintFormat("PrintFormat(EMPTY_VALUE) = %e",EMPTY_VALUE);
//--- simple output using Print()
Print("Print(EMPTY_VALUE) = ",EMPTY_VALUE);
/* execution result
MetaQuotes-Demo 1889998: leverage = 1:100
MetaQuotes-Demo 1889998: account equity = 22139.86 USD
MetaQuotes-Demo 1889998: current result for open positions = +174.00 USD
EURUSD: point value = 0.00001
EURUSD: current spread in points = 12
DBL_MAX = 1.79769313486231570e+308
EMPTY_VALUE = 1.79769313486231570e+308
PrintFormat(EMPTY_VALUE) = 1.797693e+308
Print(EMPTY_VALUE) = 1.797693134862316e+308
*/
}

See also
StringFormat, DoubleToS tring, R eal types (double, float)

© 2000-2025, MetaQuotes Ltd.


1136 Common Functions

ResetLastError
S ets the value of the predefined variable _LastError into zero.
void ResetLastError();

Return Value

No return value.
Note

It should be noted that the GetLastError() function doesn't zero the _LastError variable. Usually the
R esetLastError() function is called before calling a function, after which an error appearance is
checked.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- reset the last error code before calling the function,
//--- otherwise, GetLastError() may return the previous error code
long lres=SymbolInfoInteger("123456",SYMBOL_DIGITS);
PrintFormat("lres=%d error=%d",lres,GetLastError());
lres=SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
PrintFormat("lres=%d error=%d",lres,GetLastError());
ResetLastError();
lres=SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
PrintFormat("lres=%d error=%d",lres,GetLastError());
}

© 2000-2025, MetaQuotes Ltd.


1137 Common Functions

ResourceCreate
Creates an image resource based on a data set. There are two variants of the function:
Creating a resource based on a file
bool ResourceCreate(
const string resource_name, // Resource name
const string path // A relative path to the file
);

Creating a resource based on the array of pixels

bool ResourceCreate(
const string resource_name, // Resource name
const uint& data[], // Data set as an array
uint img_width, // The width of the image resource
uint img_height, // The height of the image resource
uint data_xoffset, // The horizontal rightward offset of the upper left corn
uint data_yoffset, // The vertical downward offset of the upper left corner
uint data_width, // The total width of the image based on the data set
ENUM_COLOR_FORMAT color_format // Color processing method
);

Parameters
resource_name
[in] R esource name.

data[][]
[in] A one-dimensional or two-dimensional array for creating a complete image.
img_width
[in] The width of the rectangular image area in pixels to be placed in the resource in the form of
an image. It cannot be greater than the data_width value.
img_height
[in] The height of the rectangular image area in pixels to be placed in the resource in the form of
an image.
data_xoffset
[in] The horizontal rightward offset of the rectangular area of the image.
data_yoffset
[in] The vertical downward offset of the rectangular area of the image.
data_width
[in] R equired only for
one-dimensional arrays. It denotes the full width of the image from the data
set. If data_width=0, it is assumed to be equal to img_width. For two-dimensional arrays the
parameter is ignored and is assumed to be equal to the second dimension of the data[] array.
color_format
[in] Color processing method, from a value from the ENUM _COLOR_FORM AT enumeration.

© 2000-2025, MetaQuotes Ltd.


1138 Common Functions

Return Value

R eturns true if successful, otherwise false. To get information about the error call the
GetLastError() function. The following errors may occur:
· 4015 – ERR_RES OUR CE_NAM E_DUPLICAT ED (identical names of the dynamic and the static
resource)
· 4016 – ERR_RES OUR CE_NOT _FOUND (the resource is not found)
· 4017 – ERR_RES OUR CE_UNSUPPOR T ED_T YPE (this type of resource is not supported)
· 4018 – ERR_RES OUR CE_NAM E_IS_TOO_LONG (the name of the resource is too long)

Note

If the second version of the function is called for creating the same resource with different width,
height and shift parameters, it does not create a new resource, but simply updates the existing one.
The first version of the function is used for uploading images and sounds from files, and the second
version is used only for the dynamic creation of images.
Images must be in the BMP format with a color depth of 24 or 32 bits. S ounds can only be in the
WAV format. The size of the resource should not exceed 16 Mb.

ENUM_COLOR_FORMAT

Identifier Description

COLOR_FORM AT_XRGB_NOALPHA The component of the alpha channel is ignored


COLOR_FORM AT_ARGB_RAW Color components are not handled by the
terminal (must be correctly set by the user)
COLOR_FORM AT_ARGB_NORM ALIZE Color components are handled by the terminal

Example:

//+------------------------------------------------------------------+
//| Update graphical resource data |
//+------------------------------------------------------------------+
void Update(const string res_name,const uint &pixel_data[],const uint width,const uint height,const
{
//--- leave if zero dimensions are passed
if(width==0 || height==0)
return;
//--- Update resource data and redraw the chart
if(ResourceCreate(res_name,pixel_data,width,height,0,0,0,COLOR_FORMAT_ARGB_NORMALIZE) && redraw)
ChartRedraw();
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()

© 2000-2025, MetaQuotes Ltd.


1139 Common Functions

{
//--- declare the parameters of the graphical resource
string rc_name="Resource";
uint rc_width=100;
uint rc_height=100;
uint rc_data[];
uint rc_size=rc_width*rc_height;

ResetLastError();
//--- set the size of the pixel array
if(ArrayResize(rc_data,rc_size)!=rc_size)
{
Print("ArrayResize() failed. Error code: ",GetLastError());
return;
}
//--- fill the pixel array with a transparent color and create a graphical resource based on it
ArrayInitialize(rc_data,0x00FFFFFF);
if(!ResourceCreate(rc_name,rc_data,rc_width,rc_height,0,0,0,COLOR_FORMAT_ARGB_NORMALIZE))
{
Print("ResourceCreate() failed. Error code: ",GetLastError());
return;
}
Print("Size of created recource array: ",rc_data.Size());

//--- check the created graphical resource.


//--- get the time and price data of the current bar
MqlTick tick={};
if(!SymbolInfoTick(Symbol(),tick))
{
Print("SymbolInfoTick() failed. Error code: ",GetLastError());
return;
}
//--- create the Bitmap object using the coordinates of the last tick price and time
string obj_name="Bitmap";
if(!ObjectCreate(0,obj_name,OBJ_BITMAP,0,tick.time,tick.bid))
{
Print("ObjectCreate() failed. Error code: ",GetLastError());
return;
}
//--- set the width and height of the created bitmap object equal to the width and height of the gr
//--- set the object anchor point to its center.
ObjectSetInteger(0,obj_name,OBJPROP_XSIZE,rc_width);
ObjectSetInteger(0,obj_name,OBJPROP_YSIZE,rc_height);
ObjectSetInteger(0,obj_name,OBJPROP_ANCHOR,ANCHOR_CENTER);
//--- specify the previously created graphical resource for the bitmap object as an image file
//--- in this case, in order to indicate the name of the graphical resource used, we need to add ":
ObjectSetString(0,obj_name,OBJPROP_BMPFILE,"::"+rc_name);

//--- set the DodgerBlue color with the transparency of 200

© 2000-2025, MetaQuotes Ltd.


1140 Common Functions

uint clr=ColorToARGB(clrDodgerBlue,200);
//--- fill the entire array of pixels of the graphical resource with the set color
ArrayInitialize(rc_data,clr);
//--- update the graphical resource data
Update(rc_name,rc_data,rc_width,rc_height,true);
}

See also

R esources, ObjectCreate(), ObjectS etS tring(), OBJPROP_BMPFILE

© 2000-2025, MetaQuotes Ltd.


1141 Common Functions

ResourceFree
The function deletes dynamically created resource (freeing the memory allocated for it).
bool ResourceFree(
const string resource_name // resource name
);

Parameters
resource_name
[in] R esource name should start with "::" .

Return Value

True if successful, otherwise false. To get information about the error, call the GetLastError()
function.
Note

R esourceFree() allows mql5 application developers to manage memory consumption when actively
working with resources. Graphical objects bound to the resource being deleted from the memory will
be displayed correctly after its deletion. However, newly created graphical objects (OBJ_BITM AP and
OBJ_BITM AP_LABEL) will not be able to use the deleted resource.
The function deletes only dynamic resources created by the program.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare the parameters of the graphical resource
string rc_name="Resource";
uint rc_width=100;
uint rc_height=100;
uint rc_data[];
uint rc_size=rc_width*rc_height;

ResetLastError();
//--- set the size of the pixel array
if(ArrayResize(rc_data,rc_size)!=rc_size)
{
Print("ArrayResize() failed. Error code: ",GetLastError());
return;
}
//--- fill the pixel array with a transparent color and create a graphical resource based on it
ArrayInitialize(rc_data,0x00FFFFFF);
if(!ResourceCreate(rc_name,rc_data,rc_width,rc_height,0,0,0,COLOR_FORMAT_ARGB_NORMALIZE))

© 2000-2025, MetaQuotes Ltd.


1142 Common Functions

{
Print("ResourceCreate() failed. Error code: ",GetLastError());
return;
}
Print("Size of created recource array: ",rc_data.Size());

//--- check the created graphical resource.


//--- get the time and price data of the current bar
MqlTick tick={};
if(!SymbolInfoTick(Symbol(),tick))
{
Print("SymbolInfoTick() failed. Error code: ",GetLastError());
return;
}
//--- create the Bitmap object using the coordinates of the last tick price and time
string obj_name="Bitmap";
if(!ObjectCreate(0,obj_name,OBJ_BITMAP,0,tick.time,tick.bid))
{
Print("ObjectCreate() failed. Error code: ",GetLastError());
return;
}
//--- set the width and height of the created bitmap object equal to the width and height of the gr
//--- set the object anchor point to its center.
ObjectSetInteger(0,obj_name,OBJPROP_XSIZE,rc_width);
ObjectSetInteger(0,obj_name,OBJPROP_YSIZE,rc_height);
ObjectSetInteger(0,obj_name,OBJPROP_ANCHOR,ANCHOR_CENTER);
//--- specify the previously created graphical resource for the bitmap object as an image file
//--- in this case, in order to indicate the name of the graphical resource used, we need to add ":
ObjectSetString(0,obj_name,OBJPROP_BMPFILE,"::"+rc_name);

//--- set the DodgerBlue color with the transparency of 200


uint clr=ColorToARGB(clrDodgerBlue,200);
//--- fill the entire array of pixels of the graphical resource with the set color
ArrayInitialize(rc_data,clr);
//--- update the graphical resource data
Update(rc_name,rc_data,rc_width,rc_height,true);

//--- wait three seconds and change the image color


Print("Wait 3 seconds before changing color");
Sleep(3000);
//--- set the OrangeRed color with the transparency of 200
Print("Change color");
clr=ColorToARGB(clrOrangeRed,200);
//--- fill the entire array of pixels of the graphical resource with the set color
ArrayInitialize(rc_data,clr);
//--- update the graphical resource data
Update(rc_name,rc_data,rc_width,rc_height,true);

//--- wait three seconds and release the graphical resource

© 2000-2025, MetaQuotes Ltd.


1143 Common Functions

Print("Wait 3 seconds before ResourceFree()");


Sleep(3000);
bool res=ResourceFree("::"+rc_name);
Print("ResourceFree: ",res);

//--- try changing the color after releasing the resource


Print("Trying to change color to GreenYellow after ResourceFree()");
//--- set the GreenYellow color with the transparency of 200
clr=ColorToARGB(clrGreenYellow,200);
//--- fill the entire array of pixels of the graphical resource with the set color
ArrayInitialize(rc_data,clr);
//--- update the graphical resource data (the image remains, but the color cannot be changed)
Update(rc_name,rc_data,rc_width,rc_height,true);
Print("The color has not changed because the resource has been released");

//--- wait three seconds and delete the bitmap object


Print("Wait 3 seconds before deleting the Bitmap object");
Sleep(3000);
Print("Delete Bitmap object");
ObjectDelete(0,obj_name);
}
//+------------------------------------------------------------------+
//| Update graphical resource data |
//+------------------------------------------------------------------+
void Update(const string res_name,const uint &pixel_data[],const uint width,const uint height,const
{
//--- leave if zero dimensions are passed
if(width==0 || height==0)
return;
//--- update resource data and redraw the chart
if(ResourceCreate(res_name,pixel_data,width,height,0,0,0,COLOR_FORMAT_ARGB_NORMALIZE) && redraw)
ChartRedraw();
}

See also

R esources, ObjectCreate(), PlayS ound(), ObjectS etS tring(), OBJPROP_BMPFILE

© 2000-2025, MetaQuotes Ltd.


1144 Common Functions

ResourceReadImage
The function reads data from the graphical resource created by ResourceCreate() function or saved in
EX5 file during compilation.

bool ResourceReadImage(
const string resource_name, // graphical resource name for reading
uint& data[], // array for receiving data from the resource
uint& width, // for receiving the image width in the resource
uint& height, // for receiving the image height in the resource
);

Parameters
resource_name
[in] Name of the graphical resource containing an image. To gain access to its own resources, the
name is used in brief form "::resourcename" . If we download a resource from a compiled EX5 file,
the full name should be used with the path relative to MQL5 directory, file and resource names –
" path\\filename.ex5::resourcename" .

data[][]
[in] One- or two-dimensional array for receiving data from the graphical resource.
img_width
[out] Graphical resource image width in pixels .

img_height
[out] Graphical resource image height in pixels .

Return Value

true if successful, otherwise false. To get information about the error, call the GetLastError()
function.
Note

If data[] array is then to be used for creating a graphical resource,


COLOR_FORM AT_ARGB_NORM ALIZE or COLOR_FORM AT_XRGB_NOALPHA color formats should be
used.
If data[] array is two-dimensional and its second dimension is less than X(width) graphical resource
size, ResourceReadImage() function returns false and reading is not performed. But if the resource
exists, actual image size is returned to width and height parameters. This will allow making another
attempt to receive data from the resource.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{

© 2000-2025, MetaQuotes Ltd.


1145 Common Functions

//--- declare the parameters of the graphical resource


string rc_name="Resource";
uint rc_width=100;
uint rc_height=100;
uint rc_data[];
uint rc_size=rc_width*rc_height;

ResetLastError();
//--- set the size of the pixel array
if(ArrayResize(rc_data,rc_size)!=rc_size)
{
Print("ArrayResize() failed. Error code: ",GetLastError());
return;
}
//--- fill the pixel array with a transparent color and create a graphical resource based on it
ArrayInitialize(rc_data,0x00FFFFFF);
if(!ResourceCreate(rc_name,rc_data,rc_width,rc_height,0,0,0,COLOR_FORMAT_ARGB_NORMALIZE))
{
Print("ResourceCreate() failed. Error code: ",GetLastError());
return;
}
Print("Size of created recource array: ",rc_data.Size());

//--- check the created graphical resource.


//--- get the time and price data of the current bar
MqlTick tick={};
if(!SymbolInfoTick(Symbol(),tick))
{
Print("SymbolInfoTick() failed. Error code: ",GetLastError());
return;
}
//--- create the Bitmap object using the coordinates of the last tick price and time
string obj_name="Bitmap";
if(!ObjectCreate(0,obj_name,OBJ_BITMAP,0,tick.time,tick.bid))
{
Print("ObjectCreate() failed. Error code: ",GetLastError());
return;
}
//--- set the width and height of the created bitmap object equal to the width and height of the gr
//--- set the object anchor point to its center.
ObjectSetInteger(0,obj_name,OBJPROP_XSIZE,rc_width);
ObjectSetInteger(0,obj_name,OBJPROP_YSIZE,rc_height);
ObjectSetInteger(0,obj_name,OBJPROP_ANCHOR,ANCHOR_CENTER);
//--- specify the previously created graphical resource for the bitmap object as an image file
//--- In this case, in order to indicate the name of the graphical resource used, we need to add ":
ObjectSetString(0,obj_name,OBJPROP_BMPFILE,"::"+rc_name);

//--- set the DodgerBlue color with the transparency of 200


uint clr=ColorToARGB(clrDodgerBlue,200);

© 2000-2025, MetaQuotes Ltd.


1146 Common Functions

//--- fill the entire array of pixels of the graphical resource with the set color
ArrayInitialize(rc_data,clr);
//--- update the graphical resource data
Update(rc_name,rc_data,rc_width,rc_height,true);

//--- wait 3 seconds before reading the graphical resource data


Print("Wait 3 seconds before ResourceReadImage()");
Sleep(3000);
//--- read the image from the resource into a new array of pixels
uint rc_data_copy[];
uint w=0,h=0;
ResetLastError();
if(!ResourceReadImage("::"+rc_name,rc_data_copy,w,h))
{
Print("ResourceReadImage() failed. Error code: ",GetLastError());
return;
}

//--- set the OrangeRed color with the transparency of 200


clr=ColorToARGB(clrOrangeRed,200);
//--- fill the entire array of pixels of the graphical resource with the set color and create a new
ArrayInitialize(rc_data_copy,clr);
if(!ResourceCreate(rc_name+"Copy",rc_data_copy,rc_width,rc_height,0,0,0,COLOR_FORMAT_ARGB_NORMAL
{
Print("New ResourceCreate() failed. Error code: ",GetLastError());
return;
}
Print("Size of created new recource array: ",rc_data_copy.Size());

//--- create the "Graphical label" object using the coordinates of the last tick price and time
string obj_name2="BitmapLabel";
if(!ObjectCreate(0,obj_name2,OBJ_BITMAP_LABEL,0,0,0))
{
Print("ObjectCreate() failed. Error code: ",GetLastError());
return;
}
//--- get screen coordinates using the previously received price and time
int x=0,y=0;
if(!ChartTimePriceToXY(0,0,tick.time,tick.bid,x,y))
{
Print("New ChartTimePriceToXY() failed. Error code: ",GetLastError());
return;
}
//--- set the width and height of the created graphical label object equal to the width and height
//--- set the object anchor point to its center.
ObjectSetInteger(0,obj_name2,OBJPROP_XSIZE,rc_width);
ObjectSetInteger(0,obj_name2,OBJPROP_YSIZE,rc_height);
ObjectSetInteger(0,obj_name2,OBJPROP_ANCHOR,ANCHOR_LEFT_UPPER);
ObjectSetInteger(0,obj_name2,OBJPROP_XDISTANCE,x);

© 2000-2025, MetaQuotes Ltd.


1147 Common Functions

ObjectSetInteger(0,obj_name2,OBJPROP_YDISTANCE,y);
//--- set the copied graphical resource as an image file for the graphical label object
//--- in this case, in order to indicate the name of the graphical resource used, we need to add ":
ObjectSetString(0,obj_name2,OBJPROP_BMPFILE,"::"+rc_name+"Copy");

//--- change the color of the new graphical label object


Print("Wait 3 seconds before changing color to GreenYellow");
Sleep(3000);
//--- set the GreenYellow color with the transparency of 200
clr=ColorToARGB(clrGreenYellow,200);
//--- fill the entire array of pixels of the new graphical resource with the set color
ArrayInitialize(rc_data_copy,clr);
//--- update the graphical resource data
Update(rc_name+"Copy",rc_data_copy,rc_width,rc_height,true);

//--- wait three seconds and delete resources and both objects
Print("Wait 3 seconds before deleting both objects");
Sleep(3000);
Print("Deleting Resource and all Bitmap objects");
ResourceFree("::"+rc_name);
ResourceFree("::"+rc_name+"Copy");
ObjectDelete(0,obj_name);
ObjectDelete(0,obj_name2);
}
//+------------------------------------------------------------------+
//| Update graphical resource data |
//+------------------------------------------------------------------+
void Update(const string res_name,const uint &pixel_data[],const uint width,const uint height,const
{
//--- leave if zero dimensions are passed
if(width==0 || height==0)
return;
//--- update resource data and redraw the chart
if(ResourceCreate(res_name,pixel_data,width,height,0,0,0,COLOR_FORMAT_ARGB_NORMALIZE) && redraw)
ChartRedraw();
}

See also

R esource, ObjectCreate(), ObjectS etS tring(), OBJPROP_BMPFILE

© 2000-2025, MetaQuotes Ltd.


1148 Common Functions

ResourceSave
S aves a resource into the specified file.
bool ResourceSave(
const string resource_name // Resource name
const string file_name // File name
);

Parameters
resource_name
[in] The name of the resource, must start with "::" .
file_name
[in] The name of the file relative to MQL5\Files.

Return Value

true – in case of success, otherwise false. For the error information call GetLastError().
Note

The function always overwrites a file and creates all the required intermediate directories in the file
name if necessary.

Example:

//--- graphical resource parameters


string ExtResName="Resource";
int ExtResWidth=100;
int ExtResHeight=100;
uint ExtResData[];
int ExtResSize=ExtResWidth*ExtResHeight;

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
ResetLastError();
//--- set the size of the pixel array
if(ArrayResize(ExtResData,ExtResSize)!=ExtResSize)
{
Print("ArrayResize() failed. Error code: ",GetLastError());
return;
}
//--- fill the pixel array with a transparent color and create a graphical resource based on it
ArrayInitialize(ExtResData,0x00FFFFFF);
if(!ResourceCreate(ExtResName,ExtResData,ExtResWidth,ExtResHeight,0,0,0,COLOR_FORMAT_ARGB_NORMAL

© 2000-2025, MetaQuotes Ltd.


1149 Common Functions

{
Print("ResourceCreate() failed. Error code: ",GetLastError());
return;
}
Print("Size of created recource array: ",ExtResData.Size());

//--- check the created graphical resource.


//--- get the time and price data of the current bar
MqlTick tick={};
if(!SymbolInfoTick(Symbol(),tick))
{
Print("SymbolInfoTick() failed. Error code: ",GetLastError());
return;
}
//--- Create the Bitmap object using the coordinates of the last tick price and time
string obj_name="Bitmap";
if(!ObjectCreate(0,obj_name,OBJ_BITMAP,0,tick.time,tick.bid))
{
Print("ObjectCreate() failed. Error code: ",GetLastError());
return;
}
//--- set the width and height of the created bitmap object equal to the width and height of the gr
//--- set the object anchor point to its center.
ObjectSetInteger(0,obj_name,OBJPROP_XSIZE,ExtResWidth);
ObjectSetInteger(0,obj_name,OBJPROP_YSIZE,ExtResHeight);
ObjectSetInteger(0,obj_name,OBJPROP_ANCHOR,ANCHOR_CENTER);
//--- specify the previously created graphical resource for the bitmap object as an image file
//--- in this case, in order to indicate the name of the graphical resource used, we need to add ":
ObjectSetString(0,obj_name,OBJPROP_BMPFILE,"::"+ExtResName);

//--- set the GreenYellow color with the transparency of 200


uint clr=ColorToARGB(clrGreenYellow,200);
//--- fill the entire array of pixels of the graphical resource with the set color
ArrayInitialize(ExtResData,clr);
//--- draw the grid using DodgerBlue color
for(int x=0;x<ExtResWidth;x+=9)
LineVertical(x,0,ExtResHeight,ColorToARGB(clrDodgerBlue,200));
for(int y=0;y<ExtResHeight;y+=9)
LineHorizontal(0,ExtResWidth,y,ColorToARGB(clrDodgerBlue,200));
//--- update the graphical resource data
Update(ExtResName,ExtResData,ExtResWidth,ExtResHeight,true);

//--- wait 3 seconds before deleting the resource and graphical object
Print("Wait 3 seconds before deleting the resource and graphic object");
Sleep(3000);

//--- save the resource to the file


ResetLastError();
if(!ResourceSave("::"+ExtResName,"ResourceSave\\"+ExtResName+".bmp"))

© 2000-2025, MetaQuotes Ltd.


1150 Common Functions

{
Print("ResourceSave() failed. Error code: ",GetLastError());
return;
}
//--- delete the resource and graphic object image
if(!ResourceFree("::"+ExtResName))
{
Print("ResourceFree() failed. Error code: ",GetLastError());
return;
}
if(!ObjectDelete(0,obj_name))
{
Print("ObjectDelete() failed. Error code: ",GetLastError());
return;
}

//--- now create the "Graphical label" object using the coordinates of the price and time of the la
//--- get screen coordinates using the previously received last tick price and time
int x=0,y=0;
if(!ChartTimePriceToXY(0,0,tick.time,tick.bid,x,y))
{
Print("ChartTimePriceToXY() failed. Error code: ",GetLastError());
return;
}
obj_name="BitmapLabel";
if(!ObjectCreate(0,obj_name,OBJ_BITMAP_LABEL,0,0,0))
{
Print("ObjectCreate() failed. Error code: ",GetLastError());
return;
}
//--- set the object anchor point to its center.
ObjectSetInteger(0,obj_name,OBJPROP_ANCHOR,ANCHOR_CENTER);
//--- set the coordinates of the price and time of the last tick, shifted to the left by the image
ObjectSetInteger(0,obj_name,OBJPROP_XDISTANCE,x-ExtResWidth);
ObjectSetInteger(0,obj_name,OBJPROP_YDISTANCE,y);
//--- specify the resource, previously saved as a bmp image, for the graphical label object as an i
ObjectSetString(0,obj_name,OBJPROP_BMPFILE,"\\Files\\ResourceSave\\"+ExtResName+".bmp");
//--- update the chart
ChartRedraw();

//--- wait 3 seconds before deleting the graphical label object


Print("Wait 3 seconds before deleting the new graphic object");
Sleep(3000);
if(!ObjectDelete(0,obj_name))
Print("ObjectDelete() failed. Error code: ",GetLastError());
}
//+------------------------------------------------------------------+
//| Update graphical resource data |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1151 Common Functions

void Update(const string res_name,const uint &pixel_data[],const uint width,const uint height,const
{
//--- leave if zero dimensions are passed
if(width==0 || height==0)
return;
//--- update resource data and redraw the chart
if(ResourceCreate(res_name,pixel_data,width,height,0,0,0,COLOR_FORMAT_ARGB_NORMALIZE) && redraw)
ChartRedraw();
}
//+------------------------------------------------------------------+
//| Draw a vertical line |
//+------------------------------------------------------------------+
void LineVertical(int x,int y1,int y2,const uint clr)
{
int tmp;
//--- sort by Y
if(y1>y2)
{
tmp=y1;
y1 =y2;
y2 =tmp;
}
//--- line outside the image boundaries
if(y2<0 || y1>=ExtResHeight || x<0 || x>=ExtResWidth)
return;
//--- stay within the image boundaries
if(y1<0)
y1=0;
if(y2>=ExtResHeight)
y2=ExtResHeight-1;
//--- draw the line
int index=y1*ExtResWidth+x;
for(int i=y1; i<=y2; i++,index+=ExtResWidth)
ExtResData[index]=clr;
}
//+------------------------------------------------------------------+
//| Draw a horizontal line |
//+------------------------------------------------------------------+
void LineHorizontal(int x1,int x2,int y,const uint clr)
{
int tmp;
//--- sort by X
if(x1>x2)
{
tmp=x1;
x1 =x2;
x2 =tmp;
}
//--- line outside the image boundaries

© 2000-2025, MetaQuotes Ltd.


1152 Common Functions

if(x2<0 || x1>=ExtResWidth || y<0 || y>=ExtResHeight)


return;
//--- stay within the image boundaries
if(x1<0)
x1=0;
if(x2>=ExtResWidth)
x2=ExtResWidth-1;
//--- draw the line
ArrayFill(ExtResData,y*ExtResWidth+x1,(x2-x1)+1,clr);
}

See also

R esources, ObjectCreate(), PlayS ound(), ObjectS etS tring(), OBJPROP_BMPFILE

© 2000-2025, MetaQuotes Ltd.


1153 Common Functions

SetReturnError
S ets the code that returns the terminal process when completing the operation.
void SetReturnError(
int ret_code // client terminal completion code
);

Parameters
ret_code
[in] The code to be returned by the client terminal process when completing the operation.

Return Value

No return value.
Note

S etting
the specified ret_code return code using the S etReturnError() function is useful for analyzing
reasons of the programmatic operation completion when launching the terminal via the command
line.
Unlik e TerminalClose(), the S etR eturnError() function does not complete the terminal operation.
Instead, it only sets the code that returns the terminal process upon its completion.
If the S etReturnError() function is called multiple times and/or from different MQL5 programs, the
terminal returns the last set return code.
The set code is returned upon the terminal process completion except for the following cases :
· a critical error has occurred during execution;
· the TerminalClose(int ret_code) function issuing the terminal operation completion command with
a specified code has been called.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
matrix matrix_a =
{
{-3.474589, 1.106384, -9.091977,-3.925227 },
{-5.522139, 2.366887,-15.162351,-6.357512 },
{ 8.394926,-2.960067, 22.292115, 9.524129 },
{ 7.803242,-2.080287, 19.217706, 8.186645 }
};
matrix matrix_l(4,4);
matrix matrix_u(4,4);

//--- LU decomposition

© 2000-2025, MetaQuotes Ltd.


1154 Common Functions

matrix_a.LU(matrix_l,matrix_u);

//--- check if A = L * U
matrix matrix_lu=matrix_l.MatMul(matrix_u);
int compare_errors=(int)matrix_a.Compare(matrix_lu,1e-29);
Print("MatrixCompare errors=",compare_errors);

//--- upon completion, the client terminal will return the number of errors in comparing two matric
SetReturnError(compare_errors);
}

See also
Program Running, Runtime Errors, Uninitialization Reason Codes, TerminalClose

© 2000-2025, MetaQuotes Ltd.


1155 Common Functions

SetUserError
S ets the predefined variable _LastError into the value equal to ERR_USER_ERROR_FIRS T + user_error
void SetUserError(
ushort user_error, // error number
);

Parameters
user_error
[in] Error number set by a user.

Return Value

No return value.
Note

After an error has been set using the S etUserError(user_error) function, GetLastError() returns value
equal to ERR_USER_ERROR_FIRS T + 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
*/
}

© 2000-2025, MetaQuotes Ltd.


1156 Common Functions

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.

Return Value

No return value.
Note

The S leep() 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.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- display a countdown from 10 to 1 in the comments on the chart
for(int i=10; i>0 && !IsStopped(); i--)
{
Comment(StringFormat("Wait %u seconds",i));
Sleep(1000);
}
//--- write a text in the "arriving" comment that describes the purpose of the script
string text="This was a test showing how the Sleep() function works";
string mess="";
for(int i=0; i<(int)text.Length(); i++)
{
mess+=ShortToString(text.GetChar(i));
Sleep(100);
Comment(mess);
}
//--- say goodbye...
Sleep(1000);
for(int i=0; i<6; i++)
{
mess=(i % 2 == 0 ? "" : " Bye!");

© 2000-2025, MetaQuotes Ltd.


1157 Common Functions

Comment(mess);
Sleep(300);
}
//--- delete the text on the chart
Comment("");
}

© 2000-2025, MetaQuotes Ltd.


1158 Common Functions

TerminalClose
The function commands the terminal to complete operation.
bool TerminalClose(
int ret_code // closing code of the client terminal
);

Parameters
ret_code
[in] R eturn code, returned by the process of the client terminal at the operation completion.

Return Value

The function returns true on success, otherwise - false.


Note

The TerminalClose() function does not stop the terminal immediately, it just commands the terminal
to complete its operation.
The code of an Expert Advisor that called TerminalClose() must have all arrangements for the
immediate completion (e.g. all previously opened files must be closed in the normal mode). Call of
this function must be followed by the return operator.
The ret_code parameter allows indicating the necessary return code for analyzing reasons of the
program termination of the terminal operation when starting it from the command prompt.
Example:

//--- input parameters


input int tiks_before=500; // number of ticks till termination
input int pips_to_go=15; // distance in pips
input int seconds_st=50; // number of seconds given to the Expert Advisor
//--- globals
datetime launch_time;
int tick_counter=0;
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print(__FUNCTION__," reason code = ",reason);
Comment("");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
static double first_bid=0.0;

© 2000-2025, MetaQuotes Ltd.


1159 Common Functions

MqlTick tick;
double distance;
//---
SymbolInfoTick(_Symbol,tick);
tick_counter++;
if(first_bid==0.0)
{
launch_time=tick.time;
first_bid=tick.bid;
Print("first_bid =",first_bid);
return;
}
//--- price distance in pips
distance=(tick.bid-first_bid)/_Point;
//--- show a notification to track the EA operation
string comm="From the moment of start:\r\n\x25CF elapsed seconds: "+
IntegerToString(tick.time-launch_time)+" ;"+
"\r\n\x25CF ticks received: "+(string)tick_counter+" ;"+
"\r\n\x25CF price went in points: "+StringFormat("%G",distance);
Comment(comm);
//--- section for checking condition to close the terminal
if(tick_counter>=tiks_before)
TerminalClose(0); // exit by tick counter
if(distance>pips_to_go)
TerminalClose(1); // go up by the number of pips equal to pips_to_go
if(distance<-pips_to_go)
TerminalClose(-1); // go down by the number of pips equal to pips_to_go
if(tick.time-launch_time>seconds_st)
TerminalClose(100); // termination by timeout
//---
}

See also
Program running, Execution errors, Reasons for deinitialization

© 2000-2025, MetaQuotes Ltd.


1160 Common Functions

TesterHideIndicators
S etsthe mode of displaying/hiding indicators used in an EA. The function is intended for managing
the visibility of used indicators only during testing.
void TesterHideIndicators(
bool hide // flag
);

Parameters
hide
[in] Flag for hiding indicators when testing. S et true to hide created indicators, otherwise false.

Return Value

None.

Note

By default, all indicators created in a tested EA are displayed on the visual testing chart. Besides,
these indicators are displayed on the chart that is automatically opened when testing is complete.
The TesterHideIndicators() function allows developers to implement the ability to disable the display
of used indicators.
To disable the display of an applied indicator when testing an EA, call TesterHideIndicators() equal
to true before creating the EA's handle – all indicators created after that are marked with the hide
flag. These indicators are not displayed during a visual test and on the chart that is automatically
opened upon completion of the test.
To disable the hide mode of the newly created indicators, call TesterHideIndicators() equal to false.
Only indicators generated directly from the tested EA can be displayed on the testing chart. This rule
applies only to cases where there is not a single template in <data_folder>MQL5\Profiles \Templates.
If the <data_folder>MQL5\Profiles \Templates directory contains a special template <EA_name>.tpl,
only the indicators from this template are displayed during a visual testing and on the testing chart.
In this case, no indicators applied in the tested EA are displayed. This behavior remains even if
TesterHideIndicators() equal to true is called in the EA code.
If the <data_folder>MQL5\Profiles \Templates directory contains no special <EA_name>.tpl template
having tester.tpl instead, indicators from the tester.tpl and the ones from the EA not disabled by
the TesterHideIndicators() function are displayed during a visual testing and on the testing chart. If
there is no tester.tpl template, indicators from the default.tpl template are used instead.
If the strategy tester finds no suitable template (<EA_name>.tpl, tester.tpl or default.tpl), display of
the indicators applied in the EA is fully managed by the TesterHideIndicators() function.
Example:

bool CSampleExpert::InitIndicators(void)
{
TesterHideIndicators(true);
//--- create MACD indicator
if(m_handle_macd==INVALID_HANDLE)
if((m_handle_macd=iMACD(NULL,0,12,26,9,PRICE_CLOSE))==INVALID_HANDLE)

© 2000-2025, MetaQuotes Ltd.


1161 Common Functions

{
printf("Error creating MACD indicator");
return(false);
}
TesterHideIndicators(false);
//--- create EMA indicator and add it to collection
if(m_handle_ema==INVALID_HANDLE)
if((m_handle_ema=iMA(NULL,0,InpMATrendPeriod,0,MODE_EMA,PRICE_CLOSE))==INVALID_HANDLE)
{
printf("Error creating EMA indicator");
return(false);
}
//--- succeed
return(true);
}

See also

IndicatorRelease

© 2000-2025, MetaQuotes Ltd.


1162 Common Functions

TesterStatistics
The function returns the value of the specified statistical parameter calculated based on testing
results.
double TesterStatistics(
ENUM_STATISTICS statistic_id // ID
);

Parameters
statistic_id
[in] The ID of the statistical parameter from the ENUM _S TATIS TICS enumeration.

Return Value

The value of the statistical parameter from testing results.


Note

The function can be called inside OnTester() or OnDeinit() in the tester. In other cases the result is
undefined.

Example:

// The EA based on standard "MACD Sample.mq5" file


// shows the result of TesterStatistics() in the Tester event handler
#define MACD_MAGIC 1234502
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
//---
input double InpLots =0.1; // Lots
input int InpTakeProfit =50; // Take Profit (in pips)
input int InpTrailingStop =30; // Trailing Stop Level (in pips)
input int InpMACDOpenLevel =3; // MACD open level (in pips)
input int InpMACDCloseLevel=2; // MACD close level (in pips)
input int InpMATrendPeriod =26; // MA trend period
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit(void)
{
//--- create all the necessary objects
if(!ExtExpert.Init())
return(INIT_FAILED);
//--- successful initialization
return(INIT_SUCCEEDED);

© 2000-2025, MetaQuotes Ltd.


1163 Common Functions

}
//+------------------------------------------------------------------+
//| Expert new tick handling function |
//+------------------------------------------------------------------+
void OnTick(void)
{
static datetime limit_time=0; // last call time considering 'timeout'
//--- if the time exceeds the specified limit_time value
if(TimeCurrent()>=limit_time)
{
//--- check the data
if(Bars(Symbol(),Period())>2*InpMATrendPeriod)
{
//--- if successful, increase limit_time by 'timeout' seconds
if(ExtExpert.Processing())
limit_time=TimeCurrent()+ExtTimeOut;
}
}
}
//+------------------------------------------------------------------+
//| Expert tester handling function |
//+------------------------------------------------------------------+
double OnTester(void)
{
double ret=TesterStatistics(STAT_PROFIT_FACTOR);
double profit=TesterStatistics(STAT_PROFIT);
int trades_total=(int)TesterStatistics(STAT_TRADES);
int profit_total=(int)TesterStatistics(STAT_PROFIT_TRADES);
int loss_total=(int)TesterStatistics(STAT_LOSS_TRADES);
PrintFormat("%s: Profit = %.2f, trades total: %lu, profit trades total: %lu, loss trades total:
return(ret);
/*
Result:
OnTester: Profit = 209.84, trades total: 13, profit trades total: 11, loss trades total: 2, prof
final balance 10209.84 USD
OnTester result 3.020606644198363
*/
}

© 2000-2025, MetaQuotes Ltd.


1164 Common Functions

TesterStop
Gives program operation completion command when testing.
void TesterStop();

Return Value

No return value.
Note

The TesterS top() function is designed for a routine early shutdown of an EA on a test agent – for
example, when reaching a specified number of losing trades or a preset drawdown level.
TesterS top() call is considered a normal completion of a test, therefore the OnTester() function is
called, and the entire accumulated trading statistics and optimization criterion value are submitted
to the strategy tester.
Calling ExpertRemove() in the strategy tester also means normal test completion and allows for
obtaining trading statistics, but the EA is unloaded from the agent’s memory. In this case,
performing a pass on the next set of parameters requires time in order to reload the program.
Therefore, TesterS top() is a preferred option for an early routine completion of a test.

Example:

//--- defines
#define BALANCE_LOSS_STOP 100.0 // value of the balance drawdown, at which testing is stoppe
#define EQUITY_LOSS_STOP 100.0 // value of the equity drawdown, at which testing is stopped

//--- input parameters


input double InpLots = 0.1; // lots
input uint InpStopLoss = 50; // Stop loss in points
input uint InpTakeProfit = 150; // Take Profit in points
sinput ulong InpMagic = 123; // MagicNumber
sinput ulong InpDeviation = 5; // deviation
//--- global variables
CTrade trade; // trade class instance
CSymbolInfo symb; // symbol class instance
CAccountInfo account; // trading account class instance
...
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
...
//--- successful initialization
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1165 Common Functions

//| Expert tick function |


//+------------------------------------------------------------------+
void OnTick()
{
//--- update current quotes
if(!symb.RefreshRates())
return;
...

//--- if the balance or equity have dropped more than indicated in the BALANCE_LOSS_STOP and EQUITY
//--- the test is considered unsuccessful and the TesterStop() function is called
//--- check for loss of balance by more than BALANCE_LOSS_STOP
if(balance_prev!=account.Balance())
{
if(account.Balance()<balance_prev-BALANCE_LOSS_STOP)
{
PrintFormat("The initial balance of %.2f %s decreased by %.2f %s, and now has a value of %
TesterStop();
/*
Result:
The initial balance of 10000.00 USD decreased by 100.10 USD, and now has a value of 9899.9
TesterStop() called on 9% of testing interval
*/
}
}
//--- check the loss of equity by more than EQUITY_LOSS_STOP
if(equity_prev!=account.Equity())
{
if(account.Equity()<equity_prev-EQUITY_LOSS_STOP)
{
PrintFormat("The initial equity of %.2f %s decreased by %.2f %s, and now has a value of %.
TesterStop();
/*
Result:
The initial equity of 10000.00 USD decreased by 100.10 USD, and now has a value of 9899.90
TesterStop() called on 9% of testing interval
*/
}
}
}

See also
Program Running, Testing Trading S trategies, ExpertRemove, S etReturnError

© 2000-2025, MetaQuotes Ltd.


1166 Common Functions

TesterDeposit
The special function that emulates depositing funds during a test. It can be used in some money
management systems.
bool TesterDeposit(
double money // deposited sum
);

Parameters
money
[in] Money to be deposited to an account in the deposit currency.

Return Value

R eturns true if successful, otherwise - false.

Example:

//--- defines
#define BALANCE_LOSS_DEPOSIT 100.0 // value of the balance drawdown, at which funds will be dep

//--- input parameters


input double InpLots = 0.1; // Lots
input uint InpStopLoss = 50; // Stop loss in points
input uint InpTakeProfit = 150; // Take Profit in points
sinput ulong InpMagic = 123; // Magic number
sinput ulong InpDeviation = 5; // Deviation
//--- global variables
CTrade trade; // trade class instance
CSymbolInfo symb; // symbol class instance
CAccountInfo account; // trading account class instance
...
double balance_dep_summ; // total amount of balance top-ups
uint balance_dep_total; // number of balance top-ups
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
...
//--- save the initial balance values
balance_prev=account.Balance();
balance_dep_summ=0;
balance_dep_total=0;
//--- successful initialization
return(INIT_SUCCEEDED);
}

© 2000-2025, MetaQuotes Ltd.


1167 Common Functions

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- update current quotes
if(!symb.RefreshRates())
return;
...

//--- if the balance has dropped more than indicated in the BALANCE_LOSS_DEPOSIT macro substitution
//--- it is necessary to top up the account and call the TesterDeposit() function
//--- check for loss of balance by more than BALANCE_LOSS_DEPOSIT
if(balance_prev!=account.Balance())
{
if(account.Balance()<balance_prev-BALANCE_LOSS_DEPOSIT)
{
double loss=balance_prev-account.Balance();
PrintFormat("The initial balance of %.2f %s decreased by %.2f %s. It is necessary to make
if(TesterDeposit(loss))
{
balance_dep_total++;
balance_dep_summ+=loss;
balance_prev=account.Balance();
PrintFormat("Funds have been deposited into the account. Account balance: %.2f %s.",acc
PrintFormat("Total deposits: %lu. Amount of deposits: %.2f %s.",balance_dep_total,balan
}
/*
Result:
The initial balance of 10000.00 USD decreased by 116.00 USD. It is necessary to make a dep
deal #45 balance 116.00 [deposit] done
Funds have been deposited into the account. Account balance: 10000.00 USD.
Total deposits: 1. Amount of deposits: 116.00 USD.
*/
}
}
}
//+------------------------------------------------------------------+
//| Tester function |
//+------------------------------------------------------------------+
double OnTester()
{
//--- set the maximum balance drawdown in monetary terms as the output handler value
double ret=TesterStatistics(STAT_BALANCE_DD);
//--- display a message about the drawdown, the number of deposits and their total amount in the lo
PrintFormat("%s: Maximum balance drawdown in money: %.2f %s. Total deposits: %lu. Amount of depo
//--- return the result
return(ret);
/*

© 2000-2025, MetaQuotes Ltd.


1168 Common Functions

Result:
OnTester: Maximum balance drawdown in money: 5188.50 USD. Total deposits: 46. Amount of deposits
final balance 4867.50 USD
OnTester result 5188.5
*/
}

See also
TesterW ithdrawal

© 2000-2025, MetaQuotes Ltd.


1169 Common Functions

TesterWithdrawal
The special function to emulate the operation of money withdrawal in the process of testing. Can be
used in some asset management systems.
bool TesterWithdrawal(
double money // the sum to withdraw
);

Parameters
money
[in] The sum of money that we need to withdraw (in the deposit currency).

Return Value

If successful, returns true, otherwise - false.

Example:

//--- defines
#define BALANCE_PROFIT_WITHDRAWAL 5 // the value of the balance profit, at which funds are withd

//--- input parameters


input double InpLots = 0.1; // Lots
input uint InpStopLoss = 50; // Stop loss in points
input uint InpTakeProfit = 150; // Take Profit in points
sinput ulong InpMagic = 123; // Magic number
sinput ulong InpDeviation = 5; // Deviation
//--- global variables
CTrade trade; // trade class instance
CSymbolInfo symb; // symbol class instance
CAccountInfo account; // trading account class instance
...
double balance_op_sum; // total amount of balance operations
uint balance_op_total; // number of balance operations
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
...
//--- save the initial balance values
balance_prev=account.Balance();
balance_op_sum=0;
balance_op_total=0;
//--- successful initialization
return(INIT_SUCCEEDED);
}

© 2000-2025, MetaQuotes Ltd.


1170 Common Functions

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- update current quotes
if(!symb.RefreshRates())
return;
...

//--- if the balance profit exceeds the current balance by the value specified in the BALANCE_PROFI
//--- it is necessary to withdraw these funds from the account. Call the TesterWithdrawal() functio
//--- check the balance profit for exceeding BALANCE_PROFIT_WITHDRAWAL
if(balance_prev!=account.Balance())
{
if(account.Balance()>balance_prev+BALANCE_PROFIT_WITHDRAWAL)
{
double profit=account.Balance()-balance_prev;
PrintFormat("The account balance has been increased by %.2f %s. Need to withdraw these fun
if(TesterWithdrawal(profit))
{
balance_op_total++;
balance_op_summ+=profit;
balance_prev=account.Balance();
PrintFormat("Funds have been withdrawn from the account. Account balance: %.2f %s.",acc
PrintFormat("Total withdrawals: %lu. Amount of withdrawals: %.2f %s.",balance_op_total,
}
/*
Result:
The account balance has been increased by 21.00 USD. Need to withdraw these funds from the
deal #13 balance -21.00 [withdrawal] done
Funds have been withdrawn from the account. Account balance: 10000.00 USD.
Total withdrawals: 1. Amount of withdrawals: 21.00 USD.
*/
}
}
}
//+------------------------------------------------------------------+
//| Tester function |
//+------------------------------------------------------------------+
double OnTester()
{
//--- set the maximum balance drawdown in monetary terms as the output handler value
double ret=TesterStatistics(STAT_BALANCE_DD);
//--- display a message about the drawdown, the number of withdrawals and their total amount in the
PrintFormat("%s: Maximum balance drawdown in money: %.2f %s. Total withdrawals: %lu. Amount of w
//--- return the result
return(ret);
/*

© 2000-2025, MetaQuotes Ltd.


1171 Common Functions

Result:
OnTester: Maximum balance drawdown in money: 5188.50 USD. Total withdrawals: 2. Amount of withdr
final balance 4867.50 USD
OnTester result 5188.5
*/
}

See also
TesterDeposit

© 2000-2025, MetaQuotes Ltd.


1172 Common Functions

TranslateKey
R eturns a Unicode character by a virtual key code considering the current input language and the
status of control keys.
short TranslateKey(
int key_code // key code for receiving a Unicode character
);

Parameters
key_code
[in] Key code.

Return Value

Unicode character in case of a successful conversion. The function returns -1 in case of an error.
Note

The function uses ToUnicodeEx to convert keys pressed by a user into Unicode characters. An error
may occur in case ToUnicodeEx is not triggered – for example, when trying to receive the SHIFT key
character.
Example:

void OnChartEvent(const int id,const long& lparam,const double& dparam,const string& sparam)
{
if(id==CHARTEVENT_KEYDOWN)
{
short sym=TranslateKey((int)lparam);
//--- if the entered character is successfully converted to Unicode
if(sym>0)
Print(sym,"'",ShortToString(sym),"'");
else
Print("Error in TranslateKey for key=",lparam);
}
}

See also
Client terminal events, OnChartEvent

© 2000-2025, MetaQuotes Ltd.


1173 Common Functions

ZeroMemory
The function resets a variable passed to it by reference.
void ZeroMemory(
void & variable // reset variable
);

Parameters
variable
[in] [out] Variable passed by reference, you want to reset (initialize by zero values).

Return Value

No return value.
Note

If the function parameter is a string, the call will be equivalent to indicating NULL as its value.
For simple types and their arrays, as well as for structures /classes consisting of such types, this is a
simple reset.
For objects containing strings and dynamic arrays, ZeroMemory() is called for each element.
For any arrays not protected by the const modifier, this is the zeroing of all elements.
For arrays of complex objects, ZeroMemory() is called for each element.

ZeroMemory() can't be applied to classes with protected members or inheritance.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the string
string str="Test ZeroMemory func";
//--- send the line to the log before applying ZeroMemory() to it
PrintFormat("The line before applying ZeroMemory() to it: '%s'",str);
//--- reset the string and send the result to the log
ZeroMemory(str);
Print("The same line after applying ZeroMemory() to it: '",str,"'");
/*
Result:
The line before applying ZeroMemory() to it: 'Test ZeroMemory func'
The same line after applying ZeroMemory() to it: ''
*/

//--- declare and initialize the variable of int type


int var=123;
//--- send the line to the log before applying ZeroMemory() to it

© 2000-2025, MetaQuotes Ltd.


1174 Common Functions

PrintFormat("\nThe integer variable before applying ZeroMemory() to it: %d",var);


//--- reset the variable and send the result to the log
ZeroMemory(var);
PrintFormat("The same variable after applying ZeroMemory() to it: %d",var);
/*
Result:
The integer variable before applying ZeroMemory() to it: 123
The same variable after applying ZeroMemory() to it: 0
*/

//--- declare and initialize the array of int type


int arr[]={0,1,2,3,4,5,6,7,8,9};
//--- send the array to the log before applying ZeroMemory() to it
Print("\nThe integer array before applying ZeroMemory() to it:");
ArrayPrint(arr);
//--- reset the array and send the result to the log
ZeroMemory(arr);
Print("The same array after applying ZeroMemory() to it:");
ArrayPrint(arr);
/*
Result:
The integer array before applying ZeroMemory() to it:
0 1 2 3 4 5 6 7 8 9
The same array after applying ZeroMemory() to it:
0 0 0 0 0 0 0 0 0 0
*/

//--- declare a structure of two fields - string and integer ones


struct STest
{
string var_string;
long var_long;
};
//--- declare and initialize the array of STest structure type
STest arr_struct[]={ {"0",0}, {"1",1}, {"2",2}, {"3",3} };
//--- send the array to the log before applying ZeroMemory() to it
Print("\nThe array struct before applying ZeroMemory() to it:");
ArrayPrint(arr_struct);
//--- reset the structure array and send the result to the log
ZeroMemory(arr_struct);
Print("The same array struct after applying ZeroMemory() to it:");
ArrayPrint(arr_struct);
/*
Result:
The array struct before applying ZeroMemory() to it:
[var_string] [var_long]
[0] "0" 0
[1] "1" 1
[2] "2" 2

© 2000-2025, MetaQuotes Ltd.


1175 Common Functions

[3] "3" 3
The same array struct after applying ZeroMemory() to it:
[var_string] [var_long]
[0] null 0
[1] null 0
[2] null 0
[3] null 0
*/
}

© 2000-2025, MetaQuotes Ltd.


1176 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 R eturns index of the first found element in the first array dimension
ArrayCopy Copies one array into another
ArrayCompare R eturns the result of comparing two arrays of simple types or custom
structures without complex objects
ArrayFree Frees up buffer of any dynamic array and sets the size of the zero
dimension in 0.
ArrayGetAs S eries Checks direction of array indexing
ArrayInitialize S ets all elements of a numeric array into a single value
ArrayFill Fills an array with the specified value
ArrayIs S eries Checks whether an array is a timeseries
ArrayIs Dynamic Checks whether an array is dynamic
ArrayMaximum S earch for an element with the maximal value
ArrayMinimum S earch for an element with the minimal value
ArrayPrint Prints an array of a simple type or a simple structure into journal
ArrayR ange R eturns the number of elements in the specified dimension of the array
ArrayR esize S ets the new size in the first dimension of the array
ArrayInsert Inserts the specified number of elements from a source array to a
receiving one starting from a specified index
ArrayR emove R emoves the specified number of elements from the array starting with a
specified index
ArrayR everse R everses the specified number of elements in the array starting with a
specified index
ArrayS etAs S eries S ets the direction of array indexing
ArrayS ize R eturns the number of elements in the array
ArrayS ort S orting of numeric arrays by the first dimension
ArrayS wap S waps the contents of two dynamic arrays of the same type
ArrayToFP16 Copies an array of type float or double into an array of type ushort with
the given format

© 2000-2025, MetaQuotes Ltd.


1177 Array Functions

Function Action

ArrayToFP8 Copies an array of type float or double into an array of type uchar with
the given format
ArrayFromFP16 Copies an array of type ushort into an array of float or double type with
the given format
ArrayFromFP8 Copies an array of type uchar into an array of float or double type with
the given format

© 2000-2025, MetaQuotes Ltd.


1178 Array Functions

ArrayBsearch
S earchesfor a specified value in a multidimensional numeric array sorted ascending. S earch is
performed through the elements of the first dimension.
For searching in an array of double type

int ArrayBsearch(
const double& array[], // array for search
double value // what is searched for
);

For searching in an array of float type

int ArrayBsearch(
const float& array[], // array for search
float value // what is searched for
);

For searching in an array of long type

int ArrayBsearch(
const long& array[], // array for search
long value // what is searched for
);

For searching in an array of int type

int ArrayBsearch(
const int& array[], // array for search
int value // what is searched for
);

For searching in an array of short type

int ArrayBsearch(
const short& array[], // array for search
short value // what is searched for
);

For searching in an array of char type

int ArrayBsearch(
const char& array[], // array for search
char value // what is searched for
);

Parameters
array[]
[in] Numeric array for search.
value

© 2000-2025, MetaQuotes Ltd.


1179 Array Functions

[in] Value for search.

Return 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 ArrayS ort() function.
Example:

#property description "Script based on RSI indicator data displays"


#property description "how often the market was in"
#property description "overbought and oversold areas in the specified time interval."
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input int InpMAPeriod=14; // Moving average period
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Price type
input double InpOversoldValue=30.0; // Oversold level
input double InpOverboughtValue=70.0; // Overbought level
input datetime InpDateStart=D'2012.01.01 00:00'; // Analysis start date
input datetime InpDateFinish=D'2013.01.01 00:00'; // Analysis finish date
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
double rsi_buff[]; // array of the indicator values
int size=0; // array size
//--- receive RSI indicator handle
ResetLastError();
int rsi_handle=iRSI(Symbol(),Period(),InpMAPeriod,InpAppliedPrice);
if(rsi_handle==INVALID_HANDLE)
{
//--- failed to receive the indicator handle
PrintFormat("Indicator handle receiving error. Error code = %d",GetLastError());
return;
}
//--- being in the loop, until the indicator calculates all its values
while(BarsCalculated(rsi_handle)==-1)
{
//--- exit if the indicator has forcedly completed the script's operation
if(IsStopped())
return;
//--- a pause to allow the indicator to calculate all its values
Sleep(10);
}
//--- copy the indicator values for a certain period of time

© 2000-2025, MetaQuotes Ltd.


1180 Array Functions

ResetLastError();
if(CopyBuffer(rsi_handle,0,InpDateStart,InpDateFinish,rsi_buff)==-1)
{
PrintFormat("Failed to copy the indicator values. Error code = %d",GetLastError());
return;
}
//--- receive the array size
size=ArraySize(rsi_buff);
//--- sort out the array
ArraySort(rsi_buff);
//--- find out the time (in percentage terms) the market was in the oversold area
double ovs=(double)ArrayBsearch(rsi_buff,InpOversoldValue)*100/(double)size;
//--- find out the time (in percentage terms) the market was in the overbought area
double ovb=(double)(size-ArrayBsearch(rsi_buff,InpOverboughtValue))*100/(double)size;
//--- form the strings for displaying the data
string str="From "+TimeToString(InpDateStart,TIME_DATE)+" to "
+TimeToString(InpDateFinish,TIME_DATE)+" the market was:";
string str_ovb="in overbought area "+DoubleToString(ovb,2)+"% of time";
string str_ovs="in oversold area "+DoubleToString(ovs,2)+"% of time";
//--- display the data on the chart
CreateLabel("top",5,60,str,clrDodgerBlue);
CreateLabel("overbought",5,35,str_ovb,clrDodgerBlue);
CreateLabel("oversold",5,10,str_ovs,clrDodgerBlue);
//--- redraw the chart
ChartRedraw(0);
//--- pause
Sleep(10000);
}
//+------------------------------------------------------------------+
//| Display comment in the bottom left corner of the chart |
//+------------------------------------------------------------------+
void CreateLabel(const string name,const int x,const int y,
const string str,const color clr)
{
//--- create the label
ObjectCreate(0,name,OBJ_LABEL,0,0,0);
//--- bind the label to the bottom left corner
ObjectSetInteger(0,name,OBJPROP_CORNER,CORNER_LEFT_LOWER);
//--- change position of the anchor point
ObjectSetInteger(0,name,OBJPROP_ANCHOR,ANCHOR_LEFT_LOWER);
//--- distance from the anchor point in X-direction
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
//--- distance from the anchor point in Y-direction
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
//--- label text
ObjectSetString(0,name,OBJPROP_TEXT,str);
//--- text color
ObjectSetInteger(0,name,OBJPROP_COLOR,clr);
//--- text size

© 2000-2025, MetaQuotes Ltd.


1181 Array Functions

ObjectSetInteger(0,name,OBJPROP_FONTSIZE,12);
}

© 2000-2025, MetaQuotes Ltd.


1182 Array Functions

ArrayCopy
It copies an array into another one.
int ArrayCopy(
void& dst_array[], // destination array
const 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 source array
int count=WHOLE_ARRAY // number of elements
);

Parameters
dst_array[]
[out] Destination array

src_array[]
[in] S ource array

dst_start=0
[in] S tarting index from the destination array. By default, start index is 0.
src_start=0
[in] S tarting index for the source array. By default, start index is 0.
count=WHOLE_ARRAY
[in] Number of elements that should be copied. By default, the whole array is copied
(count=WHOLE_ARRAY).

Return Value

It returns the number of copied elements.


Note

If count<0 or count>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 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.
For dynamic arrays with indexing as in timeseries, the size of a destination array is automatically
increased to the amount of copied data (if the latter exceeds the array size). The destination array
size is not decreased automatically.
Example:

#property description "The indicator highlights the candlesticks that are local"
#property description "highs and lows. Interval length for finding"
#property description "extreme values should be found using an input parameters."

© 2000-2025, MetaQuotes Ltd.


1183 Array Functions

//--- indicator settings


#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots 1
//---- plot
#property indicator_label1 "Extremums"
#property indicator_type1 DRAW_COLOR_CANDLES
#property indicator_color1 clrLightSteelBlue,clrRed,clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- predefined constant
#define INDICATOR_EMPTY_VALUE 0.0
//--- input parameters
input int InpNum=4; // Half-interval length
//--- indicator buffers
double ExtOpen[];
double ExtHigh[];
double ExtLow[];
double ExtClose[];
double ExtColor[];
//--- global variables
int ExtStart=0; // index of the first candlestick that is not an extremum
int ExtCount=0; // number of non-extremums in the interval
//+------------------------------------------------------------------+
//| Filling out non-extremum candlesticks |
//+------------------------------------------------------------------+
void FillCandles(const double &open[],const double &high[],
const double &low[],const double &close[])
{
//--- fill out the candlesticks
ArrayCopy(ExtOpen,open,ExtStart,ExtStart,ExtCount);
ArrayCopy(ExtHigh,high,ExtStart,ExtStart,ExtCount);
ArrayCopy(ExtLow,low,ExtStart,ExtStart,ExtCount);
ArrayCopy(ExtClose,close,ExtStart,ExtStart,ExtCount);
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,ExtOpen);
SetIndexBuffer(1,ExtHigh);
SetIndexBuffer(2,ExtLow);
SetIndexBuffer(3,ExtClose);
SetIndexBuffer(4,ExtColor,INDICATOR_COLOR_INDEX);
//--- specify the value, which is not displayed
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,INDICATOR_EMPTY_VALUE);
//--- specify the names of indicator buffers for displaying in the data window

© 2000-2025, MetaQuotes Ltd.


1184 Array Functions

PlotIndexSetString(0,PLOT_LABEL,"Open;High;Low;Close");
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| 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[])
{
//--- set straight indexing in time series
ArraySetAsSeries(open,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(close,false);
//--- variable of the bar calculation start
int start=prev_calculated;
//--- calculation is not performed for the first InpNum*2 bars
if(start==0)
{
start+=InpNum*2;
ExtStart=0;
ExtCount=0;
}
//--- if the bar has just formed, check the next potential extremum
if(rates_total-start==1)
start--;
//--- bar index to be checked for the extremum
int ext;
//--- indicator value calculation loop
for(int i=start;i<rates_total-1;i++)
{
//--- initially on i bar without drawing
ExtOpen[i]=0;
ExtHigh[i]=0;
ExtLow[i]=0;
ExtClose[i]=0;
//--- extremum index for check
ext=i-InpNum;
//--- check for the local maximum
if(IsMax(high,ext))

© 2000-2025, MetaQuotes Ltd.


1185 Array Functions

{
//--- highlight an extremum candlestick
ExtOpen[ext]=open[ext];
ExtHigh[ext]=high[ext];
ExtLow[ext]=low[ext];
ExtClose[ext]=close[ext];
ExtColor[ext]=1;
//--- highlight other candles up to the extremum with a neutral color
FillCandles(open,high,low,close);
//--- change the variable colors
ExtStart=ext+1;
ExtCount=0;
//--- pass to the next iteration
continue;
}
//--- check for the local minimum
if(IsMin(low,ext))
{
//--- highlight an extremum candlestick
ExtOpen[ext]=open[ext];
ExtHigh[ext]=high[ext];
ExtLow[ext]=low[ext];
ExtClose[ext]=close[ext];
ExtColor[ext]=2;
//--- highlight other candles up to the extremum with a neutral color
FillCandles(open,high,low,close);
//--- change variable values
ExtStart=ext+1;
ExtCount=0;
//--- pass to the next iteration
continue;
}
//--- increase the number of non-extremums at the interval
ExtCount++;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Check if the current array element is a local high |
//+------------------------------------------------------------------+
bool IsMax(const double &price[],const int ind)
{
//--- interval start variable
int i=ind-InpNum;
//--- interval end period
int finish=ind+InpNum+1;
//--- check for the first half of the interval
for(;i<ind;i++)

© 2000-2025, MetaQuotes Ltd.


1186 Array Functions

{
if(price[ind]<=price[i])
return(false);
}
//--- check for the second half of the interval
for(i=ind+1;i<finish;i++)
{
if(price[ind]<=price[i])
return(false);
}
//--- this is an extremum
return(true);
}
//+------------------------------------------------------------------+
//| Check if the current array element is a local low |
//+------------------------------------------------------------------+
bool IsMin(const double &price[],const int ind)
{
//--- interval start variable
int i=ind-InpNum;
//--- interval end variable
int finish=ind+InpNum+1;
//--- check for the first half of the interval
for(;i<ind;i++)
{
if(price[ind]>=price[i])
return(false);
}
//--- check for the second half of the interval
for(i=ind+1;i<finish;i++)
{
if(price[ind]>=price[i])
return(false);
}
//--- this is an extremum
return(true);
}

© 2000-2025, MetaQuotes Ltd.


1187 Array Functions

ArrayCompare
The function returns the result of comparing two arrays of the same type. It can be used to compare
arrays of simple types or custom structures without complex objects, that is the custom structures
that do not contain strings, dynamic arrays, classes and other structures with complex objects.
int ArrayCompare(
const void& array1[], // first array
const void& array2[], // second array
int start1=0, // initial offset in the first array
int start2=0, // initial offset in the second array
int count=WHOLE_ARRAY // number of elements for comparison
);

Parameters
array1[]
[in] First array.

array2[]
[in] S econd array.

start1=0
[in] The element's initial index in the first array, from which comparison starts. The default start
index - 0.
start2=0
[in] The element's initial index in the second array, from which comparison starts. The default
start index - 0.
count=WHOLE_ARRAY
[in] Number of elements to be compared. All elements of both arrays participate in comparison by
default (count=WHOLE_ARRAY).

Return Value
· -1, if array1[] less than array2[]
· 0, if array1[] equal to array2[]
· 1, if array1[] more than array2[]
· -2, if an error occurs due to incompatibility of the types of compared arrays or if start1, start2 or
count values lead to falling outside the array.
Note

The function will not return 0 (the arrays will not be considered equal) if the arrays differ in size and
count=WHOLE_ARRAY for the case when one array is a faithful subset of another one. In this case,
the result of comparing the sizes of that arrays will be returned: -1, if the size of array1[] is less
than the size of array2[] , otherwise 1.

Example:

//--- global variables

© 2000-2025, MetaQuotes Ltd.


1188 Array Functions

double ExtArrayFirst[];
double ExtArraySecond[];

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set the array sizes
if(ArrayResize(ExtArrayFirst,10)!=10)
{
Print("ArrayResize() failed for ExtArrayFirst. Error code: ",GetLastError());
return;
}
if(ArrayResize(ExtArraySecond,10)!=10)
{
Print("ArrayResize() failed for ExtArraySecond. Error code: ",GetLastError());
return;
}

//--- fill the arrays with the values of i and j indices in a loop
int total=ArraySize(ExtArrayFirst);
for(int i=0, j=total-1; i<total; i++,j--)
{
//--- fill the ExtArrayFirst array from left to right
//--- fill the ExtArraySecond array from right to left
ExtArrayFirst[i]=i;
ExtArraySecond[i]=j;
}
//--- compare the arrays and print the result in the log
ArrayComparePrint(ExtArrayFirst,ExtArraySecond);
/*
Result:
ExtArrayFirst:
0.00000 1.00000 2.00000 3.00000 4.00000 5.00000 6.00000 7.00000 8.00000 9.00000
ExtArraySecond:
9.00000 8.00000 7.00000 6.00000 5.00000 4.00000 3.00000 2.00000 1.00000 0.00000
Result ArrayCompare(): ExtArrayFirst is smaller than ExtArraySecond (result = -1)
*/

//--- now let's flip the arrays


//--- fill the arrays with the values of i and j indices in a loop
for(int i=0, j=total-1; i<total; i++,j--)
{
//--- fill the ExtArrayFirst array from right to left
//--- fill the ExtArraySecond array from left to right
ExtArrayFirst[i]=j;
ExtArraySecond[i]=i;
}

© 2000-2025, MetaQuotes Ltd.


1189 Array Functions

//--- compare the arrays and print the result in the log
ArrayComparePrint(ExtArrayFirst,ExtArraySecond);
/*
Result:
ExtArrayFirst:
9.00000 8.00000 7.00000 6.00000 5.00000 4.00000 3.00000 2.00000 1.00000 0.00000
ExtArraySecond:
0.00000 1.00000 2.00000 3.00000 4.00000 5.00000 6.00000 7.00000 8.00000 9.00000
Result ArrayCompare(): ExtArrayFirst is larger than ExtArraySecond (result = 1)
*/

//--- now let's fill the arrays in one direction


//--- fill the arrays with the values of i index in a loop
for(int i=0; i<total; i++)
{
//--- fill both arrays from left to right
ExtArrayFirst[i]=i;
ExtArraySecond[i]=i;
}
//--- compare the arrays and print the result in the log
ArrayComparePrint(ExtArrayFirst,ExtArraySecond);
/*
Result:
ExtArrayFirst:
0.00000 1.00000 2.00000 3.00000 4.00000 5.00000 6.00000 7.00000 8.00000 9.00000
ExtArraySecond:
0.00000 1.00000 2.00000 3.00000 4.00000 5.00000 6.00000 7.00000 8.00000 9.00000
Result ArrayCompare(): ExtArrayFirst and ExtArraySecond are equal (result = 0)
*/
}
//+------------------------------------------------------------------+
//| Compare and display the result |
//+------------------------------------------------------------------+
void ArrayComparePrint(const double &array1[], const double &array2[])
{
//--- print the header and contents of the arrays
Print("ExtArrayFirst:");
ArrayPrint(array1);
Print("ExtArraySecond:");
ArrayPrint(array2);
//--- compare the arrays and print the comparison result
int res=ArrayCompare(array1,array2);
string res_str=(res>0 ? "ExtArrayFirst is larger than ExtArraySecond" : res<0 ? "ExtArrayFirst i
PrintFormat("Result ArrayCompare(): %s (result = %d)\n",res_str,res);
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1190 Array Functions

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.

Return Value

No return value.
Note

The need for using ArrayFree() function may not appear too often considering that all used memory
is freed at once and main work with the arrays comprises the access to the indicator buffers. The
sizes of the buffers are automatically managed by the terminal's executive subsystem.
In case it is necessary to manually manage the memory in complex dynamic environment of the
application, ArrayFree() function allows users to free the memory occupied by the already
unnecessary dynamic array explicitly and immediately.
Example:

#include <Controls\Dialog.mqh>
#include <Controls\Button.mqh>
#include <Controls\Label.mqh>
#include <Controls\ComboBox.mqh>
//--- predefined constants
#define X_START 0
#define Y_START 0
#define X_SIZE 280
#define Y_SIZE 300
//+------------------------------------------------------------------+
//| Dialog class for working with memory |
//+------------------------------------------------------------------+
class CMemoryControl : public CAppDialog
{
private:
//--- array size
int m_arr_size;
//--- arrays
char m_arr_char[];
int m_arr_int[];
float m_arr_float[];
double m_arr_double[];
long m_arr_long[];

© 2000-2025, MetaQuotes Ltd.


1191 Array Functions

//--- labels
CLabel m_lbl_memory_physical;
CLabel m_lbl_memory_total;
CLabel m_lbl_memory_available;
CLabel m_lbl_memory_used;
CLabel m_lbl_array_size;
CLabel m_lbl_array_type;
CLabel m_lbl_error;
CLabel m_lbl_change_type;
CLabel m_lbl_add_size;
//--- buttons
CButton m_button_add;
CButton m_button_free;
//--- combo boxes
CComboBox m_combo_box_step;
CComboBox m_combo_box_type;
//--- current value of the array type from the combo box
int m_combo_box_type_value;

public:
CMemoryControl(void);
~CMemoryControl(void);
//--- class object creation method
virtual bool Create(const long chart,const string name,const int subwin,const int x1,const
//--- handler of chart events
virtual bool OnEvent(const int id,const long &lparam,const double &dparam,const string &spa

protected:
//--- create labels
bool CreateLabel(CLabel &lbl,const string name,const int x,const int y,const string
//--- create control elements
bool CreateButton(CButton &button,const string name,const int x,const int y,const s
bool CreateComboBoxStep(void);
bool CreateComboBoxType(void);
//--- event handlers
void OnClickButtonAdd(void);
void OnClickButtonFree(void);
void OnChangeComboBoxType(void);
//--- methods for working with the current array
void CurrentArrayFree(void);
bool CurrentArrayAdd(void);
};
//+------------------------------------------------------------------+
//| Free memory of the current array |
//+------------------------------------------------------------------+
void CMemoryControl::CurrentArrayFree(void)
{
//--- reset array size
m_arr_size=0;

© 2000-2025, MetaQuotes Ltd.


1192 Array Functions

//--- free the array


if(m_combo_box_type_value==0)
ArrayFree(m_arr_char);
if(m_combo_box_type_value==1)
ArrayFree(m_arr_int);
if(m_combo_box_type_value==2)
ArrayFree(m_arr_float);
if(m_combo_box_type_value==3)
ArrayFree(m_arr_double);
if(m_combo_box_type_value==4)
ArrayFree(m_arr_long);
}
//+------------------------------------------------------------------+
//| Attempt to add memory for the current array |
//+------------------------------------------------------------------+
bool CMemoryControl::CurrentArrayAdd(void)
{
//--- exit if the size of the used memory exceeds the size of the physical memory
if(TerminalInfoInteger(TERMINAL_MEMORY_PHYSICAL)/TerminalInfoInteger(TERMINAL_MEMORY_USED)<2)
return(false);
//--- attempt to allocate memory according to the current type
if(m_combo_box_type_value==0 && ArrayResize(m_arr_char,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==1 && ArrayResize(m_arr_int,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==2 && ArrayResize(m_arr_float,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==3 && ArrayResize(m_arr_double,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==4 && ArrayResize(m_arr_long,m_arr_size)==-1)
return(false);
//--- memory allocated
return(true);
}
//+------------------------------------------------------------------+
//| Handling events |
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CMemoryControl)
ON_EVENT(ON_CLICK,m_button_add,OnClickButtonAdd)
ON_EVENT(ON_CLICK,m_button_free,OnClickButtonFree)
ON_EVENT(ON_CHANGE,m_combo_box_type,OnChangeComboBoxType)
EVENT_MAP_END(CAppDialog)
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CMemoryControl::CMemoryControl(void)
{
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1193 Array Functions

//| Destructor |
//+------------------------------------------------------------------+
CMemoryControl::~CMemoryControl(void)
{
}
//+------------------------------------------------------------------+
//| Class object creation method |
//+------------------------------------------------------------------+
bool CMemoryControl::Create(const long chart,const string name,const int subwin,
const int x1,const int y1,const int x2,const int y2)
{
//--- create base class object
if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
return(false);
//--- prepare strings for labels
string str_physical="Memory physical = "+(string)TerminalInfoInteger(TERMINAL_MEMORY_PHYSICAL)+"
string str_total="Memory total = "+(string)TerminalInfoInteger(TERMINAL_MEMORY_TOTAL)+" Mb";
string str_available="Memory available = "+(string)TerminalInfoInteger(TERMINAL_MEMORY_AVAILABLE
string str_used="Memory used = "+(string)TerminalInfoInteger(TERMINAL_MEMORY_USED)+" Mb";
//--- create labels
if(!CreateLabel(m_lbl_memory_physical,"physical_label",X_START+10,Y_START+5,str_physical,12,clrB
return(false);
if(!CreateLabel(m_lbl_memory_total,"total_label",X_START+10,Y_START+30,str_total,12,clrBlack))
return(false);
if(!CreateLabel(m_lbl_memory_available,"available_label",X_START+10,Y_START+55,str_available,12,
return(false);
if(!CreateLabel(m_lbl_memory_used,"used_label",X_START+10,Y_START+80,str_used,12,clrBlack))
return(false);
if(!CreateLabel(m_lbl_array_type,"type_label",X_START+10,Y_START+105,"Array type = double",12,cl
return(false);
if(!CreateLabel(m_lbl_array_size,"size_label",X_START+10,Y_START+130,"Array size = 0",12,clrBlac
return(false);
if(!CreateLabel(m_lbl_error,"error_label",X_START+10,Y_START+155,"",12,clrRed))
return(false);
if(!CreateLabel(m_lbl_change_type,"change_type_label",X_START+10,Y_START+185,"Change type",10,cl
return(false);
if(!CreateLabel(m_lbl_add_size,"add_size_label",X_START+10,Y_START+210,"Add to array",10,clrBlac
return(false);
//--- create control elements
if(!CreateButton(m_button_add,"add_button",X_START+15,Y_START+245,"Add",12,clrBlue))
return(false);
if(!CreateButton(m_button_free,"free_button",X_START+75,Y_START+245,"Free",12,clrBlue))
return(false);
if(!CreateComboBoxType())
return(false);
if(!CreateComboBoxStep())
return(false);
//--- initialize the variable
m_arr_size=0;

© 2000-2025, MetaQuotes Ltd.


1194 Array Functions

//--- successful execution


return(true);
}
//+------------------------------------------------------------------+
//| Create the button |
//+------------------------------------------------------------------+
bool CMemoryControl::CreateButton(CButton &button,const string name,const int x,
const int y,const string str,const int font_size,
const int clr)
{
//--- create the button
if(!button.Create(m_chart_id,name,m_subwin,x,y,x+50,y+20))
return(false);
//--- text
if(!button.Text(str))
return(false);
//--- font size
if(!button.FontSize(font_size))
return(false);
//--- label color
if(!button.Color(clr))
return(false);
//--- add the button to the control elements
if(!Add(button))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a combo box for the array size |
//+------------------------------------------------------------------+
bool CMemoryControl::CreateComboBoxStep(void)
{
//--- create the combo box
if(!m_combo_box_step.Create(m_chart_id,"step_combobox",m_subwin,X_START+100,Y_START+185,X_START+
return(false);
//--- add elements to the combo box
if(!m_combo_box_step.ItemAdd("100 000",100000))
return(false);
if(!m_combo_box_step.ItemAdd("1 000 000",1000000))
return(false);
if(!m_combo_box_step.ItemAdd("10 000 000",10000000))
return(false);
if(!m_combo_box_step.ItemAdd("100 000 000",100000000))
return(false);
//--- set the current combo box element
if(!m_combo_box_step.SelectByValue(1000000))
return(false);
//--- add the combo box to control elements

© 2000-2025, MetaQuotes Ltd.


1195 Array Functions

if(!Add(m_combo_box_step))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a combo box for the array type |
//+------------------------------------------------------------------+
bool CMemoryControl::CreateComboBoxType(void)
{
//--- create the combo box
if(!m_combo_box_type.Create(m_chart_id,"type_combobox",m_subwin,X_START+100,Y_START+210,X_START+
return(false);
//--- add elements to the combo box
if(!m_combo_box_type.ItemAdd("char",0))
return(false);
if(!m_combo_box_type.ItemAdd("int",1))
return(false);
if(!m_combo_box_type.ItemAdd("float",2))
return(false);
if(!m_combo_box_type.ItemAdd("double",3))
return(false);
if(!m_combo_box_type.ItemAdd("long",4))
return(false);
//--- set the current combo box element
if(!m_combo_box_type.SelectByValue(3))
return(false);
//--- store the current combo box element
m_combo_box_type_value=3;
//--- add the combo box to control elements
if(!Add(m_combo_box_type))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a label |
//+------------------------------------------------------------------+
bool CMemoryControl::CreateLabel(CLabel &lbl,const string name,const int x,
const int y,const string str,const int font_size,
const int clr)
{
//--- create a label
if(!lbl.Create(m_chart_id,name,m_subwin,x,y,0,0))
return(false);
//--- text
if(!lbl.Text(str))
return(false);
//--- font size

© 2000-2025, MetaQuotes Ltd.


1196 Array Functions

if(!lbl.FontSize(font_size))
return(false);
//--- color
if(!lbl.Color(clr))
return(false);
//--- add the label to control elements
if(!Add(lbl))
return(false);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Handler of clicking "Add" button event |
//+------------------------------------------------------------------+
void CMemoryControl::OnClickButtonAdd(void)
{
//--- increase the array size
m_arr_size+=(int)m_combo_box_step.Value();
//--- attempt to allocate memory for the current array
if(CurrentArrayAdd())
{
//--- memory allocated, display the current status on the screen
m_lbl_memory_available.Text("Memory available = "+(string)TerminalInfoInteger(TERMINAL_MEMORY
m_lbl_memory_used.Text("Memory used = "+(string)TerminalInfoInteger(TERMINAL_MEMORY_USED)+" M
m_lbl_array_size.Text("Array size = "+IntegerToString(m_arr_size));
m_lbl_error.Text("");
}
else
{
//--- failed to allocate memory, display the error message
m_lbl_error.Text("Array is too large, error!");
//--- return the previous array size
m_arr_size-=(int)m_combo_box_step.Value();
}
}
//+------------------------------------------------------------------+
//| Handler of clicking "Free" button event |
//+------------------------------------------------------------------+
void CMemoryControl::OnClickButtonFree(void)
{
//--- free the memory of the current array
CurrentArrayFree();
//--- display the current status on the screen
m_lbl_memory_available.Text("Memory available = "+(string)TerminalInfoInteger(TERMINAL_MEMORY_AV
m_lbl_memory_used.Text("Memory used = "+(string)TerminalInfoInteger(TERMINAL_MEMORY_USED)+" Mb")
m_lbl_array_size.Text("Array size = 0");
m_lbl_error.Text("");
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1197 Array Functions

//| Handler of the combo box change event |


//+------------------------------------------------------------------+
void CMemoryControl::OnChangeComboBoxType(void)
{
//--- check if the array's type has changed
if(m_combo_box_type.Value()!=m_combo_box_type_value)
{
//--- free the memory of the current array
OnClickButtonFree();
//--- work with another array type
m_combo_box_type_value=(int)m_combo_box_type.Value();
//--- display the new array type on the screen
if(m_combo_box_type_value==0)
m_lbl_array_type.Text("Array type = char");
if(m_combo_box_type_value==1)
m_lbl_array_type.Text("Array type = int");
if(m_combo_box_type_value==2)
m_lbl_array_type.Text("Array type = float");
if(m_combo_box_type_value==3)
m_lbl_array_type.Text("Array type = double");
if(m_combo_box_type_value==4)
m_lbl_array_type.Text("Array type = long");
}
}
//--- CMemoryControl class object
CMemoryControl ExtDialog;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create the dialog
if(!ExtDialog.Create(0,"MemoryControl",0,X_START,Y_START,X_SIZE,Y_SIZE))
return(INIT_FAILED);
//--- launch
ExtDialog.Run();
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
ExtDialog.Destroy(reason);
}
//+------------------------------------------------------------------+
//| Expert chart event function |

© 2000-2025, MetaQuotes Ltd.


1198 Array Functions

//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
ExtDialog.ChartEvent(id,lparam,dparam,sparam);
}

© 2000-2025, MetaQuotes Ltd.


1199 Array Functions

ArrayGetAsSeries
It checks direction of an array index.
bool ArrayGetAsSeries(
const void& array[] // array for checking
);

Parameters
array
[in] Checked array.

Return Value

R eturnstrue, 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 ArrayIs S eries() 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
ArrayS etAs S eries() function.

Example:

#property description "Indicator calculates absolute values of the difference between"


#property description "Open and Close or High and Low prices displaying them in a separate subwindo
#property description "as a histrogram."
//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_style1 STYLE_SOLID
#property indicator_width1 3
//--- input parameters
input bool InpAsSeries=true; // Indexing direction in the indicator buffer
input bool InpPrices=true; // Calculation prices (true - Open,Close; false - High,Low)
//--- indicator buffer
double ExtBuffer[];
//+------------------------------------------------------------------+
//| Calculating indicator values |
//+------------------------------------------------------------------+
void CandleSizeOnBuffer(const int rates_total,const int prev_calculated,
const double &first[],const double &second[],double &buffer[])
{
//--- start variable for calculation of bars
int start=prev_calculated;

© 2000-2025, MetaQuotes Ltd.


1200 Array Functions

//--- work at the last bar if the indicator values have already been calculated at the previous tic
if(prev_calculated>0)
start--;
//--- define indexing direction in arrays
bool as_series_first=ArrayGetAsSeries(first);
bool as_series_second=ArrayGetAsSeries(second);
bool as_series_buffer=ArrayGetAsSeries(buffer);
//--- replace indexing direction with direct one if necessary
if(as_series_first)
ArraySetAsSeries(first,false);
if(as_series_second)
ArraySetAsSeries(second,false);
if(as_series_buffer)
ArraySetAsSeries(buffer,false);
//--- calculate indicator values
for(int i=start;i<rates_total;i++)
buffer[i]=MathAbs(first[i]-second[i]);
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- bind indicator buffers
SetIndexBuffer(0,ExtBuffer);
//--- set indexing element in the indicator buffer
ArraySetAsSeries(ExtBuffer,InpAsSeries);
//--- check for what prices the indicator is calculated
if(InpPrices)
{
//--- Open and Close prices
PlotIndexSetString(0,PLOT_LABEL,"BodySize");
//--- set the indicator color
PlotIndexSetInteger(0,PLOT_LINE_COLOR,clrOrange);
}
else
{
//--- High and Low prices
PlotIndexSetString(0,PLOT_LABEL,"ShadowSize");
//--- set the indicator color
PlotIndexSetInteger(0,PLOT_LINE_COLOR,clrDodgerBlue);
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,

© 2000-2025, MetaQuotes Ltd.


1201 Array Functions

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[])
{
//--- calculate the indicator according to the flag value
if(InpPrices)
CandleSizeOnBuffer(rates_total,prev_calculated,open,close,ExtBuffer);
else
CandleSizeOnBuffer(rates_total,prev_calculated,high,low,ExtBuffer);
//--- return value of prev_calculated for next call
return(rates_total);
}

See also
Access to timeseries, ArrayS etAs S eries

© 2000-2025, MetaQuotes Ltd.


1202 Array Functions

ArrayInitialize
The function initializes a numeric array by a preset value.
For initialization of an array of char type

int ArrayInitialize(
char array[], // initialized array
char value // value that will be set
);

For initialization of an array of short type

int ArrayInitialize(
short array[], // initialized array
short value // value that will be set
);

For initialization of an array of int type

int ArrayInitialize(
int array[], // initialized array
int value // value that will be set
);

For initialization of an array of long type

int ArrayInitialize(
long array[], // initialized array
long value // value that will be set
);

For initialization of an array of float type

int ArrayInitialize(
float array[], // initialized array
float value // value that will be set
);

For initialization of an array of double type

int ArrayInitialize(
double array[], // initialized array
double value // value that will be set
);

For initialization of an array of bool type

int ArrayInitialize(
bool array[], // initialized array
bool value // value that will be set
);

© 2000-2025, MetaQuotes Ltd.


1203 Array Functions

For initialization of an array of uint type

int ArrayInitialize(
uint array[], // initialized array
uint 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.

Return Value

Number of initialized elements.


Note

The ArrayResize() function allows to set size of an array with a reserve for further expansion
without the physical relocation of memory. It is implemented for the better performance, because
the operations of memory relocation are reasonably slow.
Initialization of the array using ArrayInitialize(array, init_val) doesn't mean the initialization with
the same value of reserve elements allocated for this array. At further expanding of the array using
the ArrayResize() function, the elements will be added at the end of the array, their values will be
undefined and in most cases will not be equal to init_value.
Example:

void OnStart()
{
//--- dynamic array
double array[];
//--- let's set the array size for 100 elements and reserve a buffer for another 10 elements
ArrayResize(array,100,10);
//--- initialize the array elements with EMPTY_VALUE=DBL_MAX value
ArrayInitialize(array,EMPTY_VALUE);
Print("Values of 10 last elements after initialization");
for(int i=90;i<100;i++) printf("array[%d] = %G",i,array[i]);
//--- expand the array by 5 elements
ArrayResize(array,105);
Print("Values of 10 last elements after ArrayResize(array,105)");
//--- values of 5 last elements are obtained from reserve buffer
for(int i=95;i<105;i++) printf("array[%d] = %G",i,array[i]);
}

© 2000-2025, MetaQuotes Ltd.


1204 Array Functions

ArrayFill
The function fills an array with the specified value.
void ArrayFill(
void& array[], // array
int start, // starting index
int count, // number of elements to fill
void value // value
);

Parameters
array[]
[out] Array of simple type (char, uchar, short, ushort, int, uint, long, ulong, bool, color, datetime,
float, double).
start
[in] S tarting index. In such a case, specified AS_SERIES flag is ignored.
count
[in] Number of elements to fill.
value
[in] Value to fill the array with.

Return Value

No return value.
Note

W hen ArrayFill()function is called, normal indexation direction (from left to right) is always implied.
It means that the change of the order of access to the array elements using ArrayS etAs S eries()
function is ignored.
A multidimensional array is shown as one-dimensional when processed by ArrayFill() function. For
example, array[2][4] is processed as array[8]. Therefore, you may specify the initial element's index
to be equal to 5 when working with this array. Thus, the call of ArrayFill(array, 5, 2, 3.14) for
array[2][4] fills array[1][1] and array[1][2] elements with 3.14.
Example:

void OnStart()
{
//--- declare dynamic array
int a[];
//--- set size
ArrayResize(a,10);
//--- fill first 5 elements with 123
ArrayFill(a,0,5,123);
//--- fill next 5 elements with 456
ArrayFill(a,5,5,456);

© 2000-2025, MetaQuotes Ltd.


1205 Array Functions

//--- show values


for(int i=0;i<ArraySize(a);i++) printf("a[%d] = %d",i,a[i]);
}

© 2000-2025, MetaQuotes Ltd.


1206 Array Functions

ArrayIsDynamic
The function checks whether an array is dynamic.
bool ArrayIsDynamic(
const void& array[] // checked array
);

Parameters
array[]
[in] Checked array.

Return Value

It returns true if the selected array is dynamic, otherwise it returns false.


Example:

#property description "This indicator does not calculate values. It makes a single attempt to"
#property description "apply the call of ArrayFree() function to three arrays: dynamic one, static
#property description "an indicator buffer. Results are shown in Experts journal."
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//--- global variables
double ExtDynamic[]; // dynamic array
double ExtStatic[100]; // static array
bool ExtFlag=true; // flag
double ExtBuff[]; // indicator buffer
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- allocate memory for the array
ArrayResize(ExtDynamic,100);
//--- indicator buffers mapping
SetIndexBuffer(0,ExtBuff);
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const int begin,
const double &price[])

© 2000-2025, MetaQuotes Ltd.


1207 Array Functions

{
//--- perform a single analysis
if(ExtFlag)
{
//--- attempt to free memory for arrays
//--- 1. Dynamic array
Print("+============================+");
Print("1. Check dynamic array:");
Print("Size before memory is freed = ",ArraySize(ExtDynamic));
Print("Is this a dynamic array = ",ArrayIsDynamic(ExtDynamic) ? "Yes" : "No");
//--- attempt to free array memory
ArrayFree(ExtDynamic);
Print("Size after memory is freed = ",ArraySize(ExtDynamic));
//--- 2. Static array
Print("2. Check static array:");
Print("Size before memory is freed = ",ArraySize(ExtStatic));
Print("Is this a dynamic array = ",ArrayIsDynamic(ExtStatic) ? "Yes" : "No");
//--- attempt to free array memory
ArrayFree(ExtStatic);
Print("Size after memory is freed = ",ArraySize(ExtStatic));
//--- 3. Indicator buffer
Print("3. Check indicator buffer:");
Print("Size before memory is freed = ",ArraySize(ExtBuff));
Print("Is this a dynamic array = ",ArrayIsDynamic(ExtBuff) ? "Yes" : "No");
//--- attempt to free array memory
ArrayFree(ExtBuff);
Print("Size after memory is freed = ",ArraySize(ExtBuff));
//--- change the flag value
ExtFlag=false;
}
//--- return value of prev_calculated for next call
return(rates_total);
}

See also
Access to timeseries and indicators

© 2000-2025, MetaQuotes Ltd.


1208 Array Functions

ArrayIsSeries
The function checks whether an array is a timeseries.
bool ArrayIsSeries(
const void& array[] // checked array
);

Parameters
array[]
[in] Checked array.

Return 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 ArrayGetAs S eries().
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 clrRed
#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[],

© 2000-2025, MetaQuotes Ltd.


1209 Array Functions

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

© 2000-2025, MetaQuotes Ltd.


1210 Array Functions

ArrayMaximum
S earches for the largest element in the first dimension of a multidimensional numeric array.
int ArrayMaximum(
const void& 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. By default, searches in the entire array
(count=WHOLE_ARRAY).

Return Value

The function returns an index of a found element taking into account the array serial. In case of
failure it returns -1.
Note

The AS_SERIES flag value is taken into account while searching for a maximum.
Functions ArrayMaximum and ArrayMinimum accept any-dimensional arrays as a parameter.
H owever, searching is always applied to the first (zero) dimension.

Example:

#property description "The indicator displays larger timeframe's candlesticks on the current one."
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 16
#property indicator_plots 8
//---- plot 1
#property indicator_label1 "BearBody"
#property indicator_color1 clrSeaGreen,clrSeaGreen
//---- plot 2
#property indicator_label2 "BearBodyEnd"
#property indicator_color2 clrSeaGreen,clrSeaGreen
//---- plot 3
#property indicator_label3 "BearShadow"
#property indicator_color3 clrSalmon,clrSalmon
//---- plot 4
#property indicator_label4 "BearShadowEnd"
#property indicator_color4 clrSalmon,clrSalmon

© 2000-2025, MetaQuotes Ltd.


1211 Array Functions

//---- plot 5
#property indicator_label5 "BullBody"
#property indicator_color5 clrOlive,clrOlive
//---- plot 6
#property indicator_label6 "BullBodyEnd"
#property indicator_color6 clrOlive,clrOlive
//---- plot 7
#property indicator_label7 "BullShadow"
#property indicator_color7 clrSkyBlue,clrSkyBlue
//---- plot 8
#property indicator_label8 "BullShadowEnd"
#property indicator_color8 clrSkyBlue,clrSkyBlue
//--- predefined constant
#define INDICATOR_EMPTY_VALUE 0.0
//--- input parameters
input ENUM_TIMEFRAMES InpPeriod=PERIOD_H4; // Time frame for the indicator calculation
input datetime InpDateStart=D'2013.01.01 00:00'; // Analysis start date
//--- indicator buffers for bearish candlesticks
double ExtBearBodyFirst[];
double ExtBearBodySecond[];
double ExtBearBodyEndFirst[];
double ExtBearBodyEndSecond[];
double ExtBearShadowFirst[];
double ExtBearShadowSecond[];
double ExtBearShadowEndFirst[];
double ExtBearShadowEndSecond[];
//--- indicator buffers for bullish candlesticks
double ExtBullBodyFirst[];
double ExtBullBodySecond[];
double ExtBullBodyEndFirst[];
double ExtBullBodyEndSecond[];
double ExtBullShadowFirst[];
double ExtBullShadowSecond[];
double ExtBullShadowEndFirst[];
double ExtBullShadowEndSecond[];
//--- global variables
datetime ExtTimeBuff[]; // larger time frame's time buffer
int ExtSize=0; // time buffer size
int ExtCount=0; // index inside time buffer
int ExtStartPos=0; // initial position for the indicator calculation
bool ExtStartFlag=true; // auxiliary flag for receiving the initial position
datetime ExtCurrentTime[1]; // last time of the larger time frame's bar generation
datetime ExtLastTime; // last time from the larger time frame, for which the calculation is
bool ExtBearFlag=true; // flag for defining the order of writing the data to bearish indicato
bool ExtBullFlag=true; // flag for defining the order of writing the data to bullish indicato
int ExtIndexMax=0; // index of the maximum element in the array
int ExtIndexMin=0; // index of the minimum element in the array
int ExtDirectionFlag=0; // price movement direction for the current candlestick
//--- shift between the candlestick's open and close price for correct drawing

© 2000-2025, MetaQuotes Ltd.


1212 Array Functions

const double ExtEmptyBodySize=0.2*SymbolInfoDouble(Symbol(),SYMBOL_POINT);


//+------------------------------------------------------------------+
//| Filling the basic part of the candlestick |
//+------------------------------------------------------------------+
void FillCandleMain(const double &open[],const double &close[],
const double &high[],const double &low[],
const int start,const int last,const int fill_index,
int &index_max,int &index_min)
{
//--- find the index of the maximum and minimum elements in the arrays
index_max=ArrayMaximum(high,ExtStartPos,last-start+1); // maximum in High
index_min=ArrayMinimum(low,ExtStartPos,last-start+1); // minimum in Low
//--- define how many bars from the current time frame are to be filled out
int count=fill_index-start+1;
//--- if the close price at the first bar exceeds the one at the last bar, the candlestick is beari
if(open[start]>close[last])
{
//--- if the candlestick has been bullish before that, clear the values of bullish indicator
if(ExtDirectionFlag!=-1)
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,star
//--- bearish candlestick
ExtDirectionFlag=-1;
//--- generate the candlestick
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,open
close[last],high[index_max],low[index_min],start,count,ExtBearFlag);
//--- exit the function
return;
}
//--- if the close price at the first bar is less than the one at the last bar, the candlestick is
if(open[start]<close[last])
{
//--- if the candlestick has been bearish before that, clear the values of bearish indicator
if(ExtDirectionFlag!=1)
ClearCandle(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,star
//--- bullish candlestick
ExtDirectionFlag=1;
//--- generate the candlestick
FormCandleMain(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,clos
open[start],high[index_max],low[index_min],start,count,ExtBullFlag);
//--- exit the function
return;
}
//--- if you are in this part of the function, the open price at the first bar is equal to
//--- the close price at the last bar; such candlestick is considered bearish
//--- if the candlestick has been bullish before that, clear the values of bullish indicator buffer
if(ExtDirectionFlag!=-1)
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,start,c
//--- bearish candlestick
ExtDirectionFlag=-1;

© 2000-2025, MetaQuotes Ltd.


1213 Array Functions

//--- if close and open prices are equal, use the shift for correct display
if(high[index_max]!=low[index_min])
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,open
open[start]-ExtEmptyBodySize,high[index_max],low[index_min],start,count,ExtBea
else
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,
open[start],open[start]-ExtEmptyBodySize,high[index_max],
high[index_max]-ExtEmptyBodySize,start,count,ExtBearFlag);
}
//+------------------------------------------------------------------+
//| Fill out the end of the candlestick |
//+------------------------------------------------------------------+
void FillCandleEnd(const double &open[],const double &close[],
const double &high[],const double &low[],
const int start,const int last,const int fill_index,
const int index_max,const int index_min)
{
//--- do not draw in case of a single bar
if(last-start==0)
return;
//--- if the close price at the first bar exceeds the one at the last bar, the candlestick is beari
if(open[start]>close[last])
{
//--- generate the end of the candlestick
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start],close[last],high[index_max],low[index_min],fill_index,ExtBearFlag);
//--- exit the function
return;
}
//--- if the close price at the first bar is less than the one at the last bar, the candlestick is
if(open[start]<close[last])
{
//--- generate the end of the candlestick
FormCandleEnd(ExtBullBodyEndFirst,ExtBullBodyEndSecond,ExtBullShadowEndFirst,ExtBullShadowEnd
close[last],open[start],high[index_max],low[index_min],fill_index,ExtBullFlag);
//--- exit the function
return;
}
//--- if you are in this part of the function, the open price at the first bar is equal to
//--- the close price at the last bar; such candlestick is considered bearish
//--- generate the end of the candlestick
if(high[index_max]!=low[index_min])
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start]-ExtEmptyBodySize,high[index_max],low[index_min],fill_index,ExtBearF
else
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start]-ExtEmptyBodySize,high[index_max],high[index_max]-ExtEmptyBodySize,f
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1214 Array Functions

//| Custom indicator initialization function |


//+------------------------------------------------------------------+
int OnInit()
{
//--- check the indicator period
if(!CheckPeriod((int)Period(),(int)InpPeriod))
return(INIT_PARAMETERS_INCORRECT);
//--- display price data in the foreground
ChartSetInteger(0,CHART_FOREGROUND,0,1);
//--- binding indicator buffers
SetIndexBuffer(0,ExtBearBodyFirst);
SetIndexBuffer(1,ExtBearBodySecond);
SetIndexBuffer(2,ExtBearBodyEndFirst);
SetIndexBuffer(3,ExtBearBodyEndSecond);
SetIndexBuffer(4,ExtBearShadowFirst);
SetIndexBuffer(5,ExtBearShadowSecond);
SetIndexBuffer(6,ExtBearShadowEndFirst);
SetIndexBuffer(7,ExtBearShadowEndSecond);
SetIndexBuffer(8,ExtBullBodyFirst);
SetIndexBuffer(9,ExtBullBodySecond);
SetIndexBuffer(10,ExtBullBodyEndFirst);
SetIndexBuffer(11,ExtBullBodyEndSecond);
SetIndexBuffer(12,ExtBullShadowFirst);
SetIndexBuffer(13,ExtBullShadowSecond);
SetIndexBuffer(14,ExtBullShadowEndFirst);
SetIndexBuffer(15,ExtBullShadowEndSecond);
//--- set some property values for creating the indicator
for(int i=0;i<8;i++)
{
PlotIndexSetInteger(i,PLOT_DRAW_TYPE,DRAW_FILLING); // graphical construction type
PlotIndexSetInteger(i,PLOT_LINE_STYLE,STYLE_SOLID); // drawing line style
PlotIndexSetInteger(i,PLOT_LINE_WIDTH,1); // drawing line width
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| 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[])

© 2000-2025, MetaQuotes Ltd.


1215 Array Functions

{
//--- in case there are no calculated bars yet
if(prev_calculated==0)
{
//--- receive larger time frame's bars arrival time
if(!GetTimeData())
return(0);
}
//--- set direct indexing
ArraySetAsSeries(time,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(open,false);
ArraySetAsSeries(close,false);
//--- start variable for calculation of bars
int start=prev_calculated;
//--- if the bar is generated, recalculate the indicator value on it
if(start!=0 && start==rates_total)
start--;
//--- the loop for calculating the indicator values
for(int i=start;i<rates_total;i++)
{
//--- fill i elements of the indicator buffers by empty values
FillIndicatorBuffers(i);
//--- perform calculation for bars starting from InpDateStart date
if(time[i]>=InpDateStart)
{
//--- define position, from which the values are to be displayed, for the first time
if(ExtStartFlag)
{
//--- store the number of the initial bar
ExtStartPos=i;
//--- define the first date from the larger time frame exceeding time[i]
while(time[i]>=ExtTimeBuff[ExtCount])
if(ExtCount<ExtSize-1)
ExtCount++;
//--- change the value of the flag in order not to run into this block again
ExtStartFlag=false;
}
//--- check if there are still any elements in the array
if(ExtCount<ExtSize)
{
//--- wait for the current time frame's value to reach the larger time frame's one
if(time[i]>=ExtTimeBuff[ExtCount])
{
//--- draw the main part of the candlestick (without filling out the area between th
FillCandleMain(open,close,high,low,ExtStartPos,i-1,i-2,ExtIndexMax,ExtIndexMin);
//--- fill out the end of the candlestick (the area between the last and the penulti
FillCandleEnd(open,close,high,low,ExtStartPos,i-1,i-1,ExtIndexMax,ExtIndexMin);

© 2000-2025, MetaQuotes Ltd.


1216 Array Functions

//--- shift the initial position for drawing the next candlestick
ExtStartPos=i;
//--- increase the array counter
ExtCount++;
}
else
continue;
}
else
{
//--- reset the array values
ResetLastError();
//--- receive the last date from the larger time frame
if(CopyTime(Symbol(),InpPeriod,0,1,ExtCurrentTime)==-1)
{
Print("Data copy error, code = ",GetLastError());
return(0);
}
//--- if the new date is later, stop generating the candlestick
if(ExtCurrentTime[0]>ExtLastTime)
{
//--- clear the area between the last and penultimate bars in the main indicator buf
ClearEndOfBodyMain(i-1);
//--- fill out the area using auxiliary indicator buffers
FillCandleEnd(open,close,high,low,ExtStartPos,i-1,i-1,ExtIndexMax,ExtIndexMin);
//--- shift the initial position for drawing the next candlestick
ExtStartPos=i;
//--- reset price direction flag
ExtDirectionFlag=0;
//--- store the new last date
ExtLastTime=ExtCurrentTime[0];
}
else
{
//--- generate the candlestick
FillCandleMain(open,close,high,low,ExtStartPos,i,i,ExtIndexMax,ExtIndexMin);
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Check correctness of the specified indicator period |
//+------------------------------------------------------------------+
bool CheckPeriod(int current_period,int high_period)
{
//--- the indicator period should exceed the timeframe on which it is displayed

© 2000-2025, MetaQuotes Ltd.


1217 Array Functions

if(current_period>=high_period)
{
Print("Error! The value of the indicator period should exceed the value of the current time f
return(false);
}
//--- if the indicator period is one week or month, the period is correct
if(high_period>32768)
return(true);
//--- convert period values to minutes
if(high_period>30)
high_period=(high_period-16384)*60;
if(current_period>30)
current_period=(current_period-16384)*60;
//--- the indicator period should be multiple of the time frame it is displayed on
if(high_period%current_period!=0)
{
Print("Error! The value of the indicator period should be multiple of the value of the curren
return(false);
}
//--- the indicator period should exceed the time frame it is displayed on 3 or more times
if(high_period/current_period<3)
{
Print("Error! The indicator period should exceed the current time frame 3 or more times!");
return(false);
}
//--- the indicator period is correct for the current time frame
return(true);
}
//+------------------------------------------------------------------+
//| Receive time data from the larger time frame |
//+------------------------------------------------------------------+
bool GetTimeData(void)
{
//--- reset the error value
ResetLastError();
//--- copy all data for the current time
if(CopyTime(Symbol(),InpPeriod,InpDateStart,TimeCurrent(),ExtTimeBuff)==-1)
{
//--- receive the error code
int code=GetLastError();
//--- print out the error message
PrintFormat("Data copy error! %s",code==4401
? "History is still being uploaded!"
: "Code = "+IntegerToString(code));
//--- return false to make a repeated attempt to download data
return(false);
}
//--- receive the array size
ExtSize=ArraySize(ExtTimeBuff);

© 2000-2025, MetaQuotes Ltd.


1218 Array Functions

//--- set the loop index for the array to zero


ExtCount=0;
//--- set the current candlestick's position on the time frame to zero
ExtStartPos=0;
ExtStartFlag=true;
//--- store the last time value from the larger time frame
ExtLastTime=ExtTimeBuff[ExtSize-1];
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| Function forms the main part of the candlestick. Depending on the flag's |
//| value, the function defines what data and arrays are |
//| to be used for correct display. |
//+--------------------------------------------------------------------------+
void FormCandleMain(double &body_fst[],double &body_snd[],
double &shadow_fst[],double &shadow_snd[],
const double fst_value,const double snd_value,
const double fst_extremum,const double snd_extremum,
const int start,const int count,const bool flag)
{
//--- check the flag's value
if(flag)
{
//--- generate the candlestick's body
FormMain(body_fst,body_snd,fst_value,snd_value,start,count);
//--- generate the candlestick's shadow
FormMain(shadow_fst,shadow_snd,fst_extremum,snd_extremum,start,count);
}
else
{
//--- generate the candlestick's body
FormMain(body_fst,body_snd,snd_value,fst_value,start,count);
//--- generate the candlestick's shadow
FormMain(shadow_fst,shadow_snd,snd_extremum,fst_extremum,start,count);
}
}
//+-------------------------------------------------------------------------------+
//| The function forms the end of the candlestick. Depending on the flag's value, |
//| the function defines what data and arrays are |
//| to be used for correct display. |
//+-------------------------------------------------------------------------------+
void FormCandleEnd(double &body_fst[],double &body_snd[],
double &shadow_fst[],double &shadow_snd[],
const double fst_value,const double snd_value,
const double fst_extremum,const double snd_extremum,
const int end,bool &flag)
{
//--- check the flag's value

© 2000-2025, MetaQuotes Ltd.


1219 Array Functions

if(flag)
{
//--- generate the end of the candlestick's body
FormEnd(body_fst,body_snd,fst_value,snd_value,end);
//--- generate the end of the candlestick's shadow
FormEnd(shadow_fst,shadow_snd,fst_extremum,snd_extremum,end);
//--- change the flag's value to the opposite one
flag=false;
}
else
{
//--- generate the end of the candlestick's body
FormEnd(body_fst,body_snd,snd_value,fst_value,end);
//--- generate the end of the candlestick's shadow
FormEnd(shadow_fst,shadow_snd,snd_extremum,fst_extremum,end);
//--- change the flag's value to the opposite one
flag=true;
}
}
//+---------------------------------------------------------------------------------+
//| Clear the end of the candlestick (the area between the last and the penultimate |
//| bar) |
//+---------------------------------------------------------------------------------+
void ClearEndOfBodyMain(const int ind)
{
ClearCandle(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,ind,1);
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,ind,1);
}
//+--------------------------------------------------------------------------+
//| Clear the candlestick |
//+--------------------------------------------------------------------------+
void ClearCandle(double &body_fst[],double &body_snd[],double &shadow_fst[],
double &shadow_snd[],const int start,const int count)
{
//--- check
if(count!=0)
{
//--- fill indicator buffers with empty values
ArrayFill(body_fst,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(body_snd,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(shadow_fst,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(shadow_snd,start,count,INDICATOR_EMPTY_VALUE);
}
}
//+--------------------------------------------------------------------------+
//| Generate the main part of the candlestick |
//+--------------------------------------------------------------------------+
void FormMain(double &fst[],double &snd[],const double fst_value,
const double snd_value,const int start,const int count)

© 2000-2025, MetaQuotes Ltd.


1220 Array Functions

{
//--- check
if(count!=0)
{
//--- fill indicator buffers with values
ArrayFill(fst,start,count,fst_value);
ArrayFill(snd,start,count,snd_value);
}
}
//+-----------------------------------------------------------------------------+
//| Generate the end of the candlestick |
//+-----------------------------------------------------------------------------+
void FormEnd(double &fst[],double &snd[],const double fst_value,
const double snd_value,const int last)
{
//--- fill indicator buffers with values
ArrayFill(fst,last-1,2,fst_value);
ArrayFill(snd,last-1,2,snd_value);
}
//+------------------------------------------------------------------+
//| Fill i element of the indicator buffers by empty values |
//+------------------------------------------------------------------+
void FillIndicatorBuffers(const int i)
{
//--- set an empty value in the cell of the indicator buffers
ExtBearBodyFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodySecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodyEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodyEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodySecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowEndSecond[i]=INDICATOR_EMPTY_VALUE;
}

© 2000-2025, MetaQuotes Ltd.


1221 Array Functions

ArrayMinimum
S earches for the lowest element in the first dimension of a multidimensional numeric array.
int ArrayMinimum(
const void& 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. By default, searches in the entire array
(count=WHOLE_ARRAY).

Return Value

The function returns an index of a found element taking into account the array serial. In case of
failure it returns -1.
Note

The AS_SERIES flag value is taken into account while searching for a minimum.
Functions ArrayMaximum and ArrayMinimum accept any-dimensional arrays as a parameter.
H owever, searching is always applied to the first (zero) dimension.

Example:

#property description "The indicator displays larger timeframe's candlesticks on the current one."
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 16
#property indicator_plots 8
//---- plot 1
#property indicator_label1 "BearBody"
#property indicator_color1 clrSeaGreen,clrSeaGreen
//---- plot 2
#property indicator_label2 "BearBodyEnd"
#property indicator_color2 clrSeaGreen,clrSeaGreen
//---- plot 3
#property indicator_label3 "BearShadow"
#property indicator_color3 clrSalmon,clrSalmon
//---- plot 4
#property indicator_label4 "BearShadowEnd"
#property indicator_color4 clrSalmon,clrSalmon

© 2000-2025, MetaQuotes Ltd.


1222 Array Functions

//---- plot 5
#property indicator_label5 "BullBody"
#property indicator_color5 clrOlive,clrOlive
//---- plot 6
#property indicator_label6 "BullBodyEnd"
#property indicator_color6 clrOlive,clrOlive
//---- plot 7
#property indicator_label7 "BullShadow"
#property indicator_color7 clrSkyBlue,clrSkyBlue
//---- plot 8
#property indicator_label8 "BullShadowEnd"
#property indicator_color8 clrSkyBlue,clrSkyBlue
//--- predefined constant
#define INDICATOR_EMPTY_VALUE 0.0
//--- input parameters
input ENUM_TIMEFRAMES InpPeriod=PERIOD_H4; // Time frame for the indicator calculation
input datetime InpDateStart=D'2013.01.01 00:00'; // Analysis start date
//--- indicator buffers for bearish candlesticks
double ExtBearBodyFirst[];
double ExtBearBodySecond[];
double ExtBearBodyEndFirst[];
double ExtBearBodyEndSecond[];
double ExtBearShadowFirst[];
double ExtBearShadowSecond[];
double ExtBearShadowEndFirst[];
double ExtBearShadowEndSecond[];
//--- indicator buffers for bullish candlesticks
double ExtBullBodyFirst[];
double ExtBullBodySecond[];
double ExtBullBodyEndFirst[];
double ExtBullBodyEndSecond[];
double ExtBullShadowFirst[];
double ExtBullShadowSecond[];
double ExtBullShadowEndFirst[];
double ExtBullShadowEndSecond[];
//--- global variables
datetime ExtTimeBuff[]; // larger time frame's time buffer
int ExtSize=0; // time buffer size
int ExtCount=0; // index inside time buffer
int ExtStartPos=0; // initial position for the indicator calculation
bool ExtStartFlag=true; // auxiliary flag for receiving the initial position
datetime ExtCurrentTime[1]; // last time of the larger time frame's bar generation
datetime ExtLastTime; // last time from the larger time frame, for which the calculation is
bool ExtBearFlag=true; // flag for defining the order of writing the data to bearish indicato
bool ExtBullFlag=true; // flag for defining the order of writing the data to bullish indicato
int ExtIndexMax=0; // index of the maximum element in the array
int ExtIndexMin=0; // index of the minimum element in the array
int ExtDirectionFlag=0; // price movement direction for the current candlestick
//--- shift between the candlestick's open and close price for correct drawing

© 2000-2025, MetaQuotes Ltd.


1223 Array Functions

const double ExtEmptyBodySize=0.2*SymbolInfoDouble(Symbol(),SYMBOL_POINT);


//+------------------------------------------------------------------+
//| Filling the basic part of the candlestick |
//+------------------------------------------------------------------+
void FillCandleMain(const double &open[],const double &close[],
const double &high[],const double &low[],
const int start,const int last,const int fill_index,
int &index_max,int &index_min)
{
//--- find the index of the maximum and minimum elements in the arrays
index_max=ArrayMaximum(high,ExtStartPos,last-start+1); // maximum in High
index_min=ArrayMinimum(low,ExtStartPos,last-start+1); // minimum in Low
//--- define how many bars from the current time frame are to be filled out
int count=fill_index-start+1;
//--- if the close price at the first bar exceeds the one at the last bar, the candlestick is beari
if(open[start]>close[last])
{
//--- if the candlestick has been bullish before that, clear the values of bullish indicator
if(ExtDirectionFlag!=-1)
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,star
//--- bearish candlestick
ExtDirectionFlag=-1;
//--- generate the candlestick
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,open
close[last],high[index_max],low[index_min],start,count,ExtBearFlag);
//--- exit the function
return;
}
//--- if the close price at the first bar is less than the one at the last bar, the candlestick is
if(open[start]<close[last])
{
//--- if the candlestick has been bearish before that, clear the values of bearish indicator
if(ExtDirectionFlag!=1)
ClearCandle(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,star
//--- bullish candlestick
ExtDirectionFlag=1;
//--- generate the candlestick
FormCandleMain(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,clos
open[start],high[index_max],low[index_min],start,count,ExtBullFlag);
//--- exit the function
return;
}
//--- if you are in this part of the function, the open price at the first bar is equal to
//--- the close price at the last bar; such candlestick is considered bearish
//--- if the candlestick has been bullish before that, clear the values of bullish indicator buffer
if(ExtDirectionFlag!=-1)
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,start,c
//--- bearish candlestick
ExtDirectionFlag=-1;

© 2000-2025, MetaQuotes Ltd.


1224 Array Functions

//--- if close and open prices are equal, use the shift for correct display
if(high[index_max]!=low[index_min])
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,open
open[start]-ExtEmptyBodySize,high[index_max],low[index_min],start,count,ExtBea
else
FormCandleMain(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,
open[start],open[start]-ExtEmptyBodySize,high[index_max],
high[index_max]-ExtEmptyBodySize,start,count,ExtBearFlag);
}
//+------------------------------------------------------------------+
//| Fill out the end of the candlestick |
//+------------------------------------------------------------------+
void FillCandleEnd(const double &open[],const double &close[],
const double &high[],const double &low[],
const int start,const int last,const int fill_index,
const int index_max,const int index_min)
{
//--- do not draw in case of a single bar
if(last-start==0)
return;
//--- if the close price at the first bar exceeds the one at the last bar, the candlestick is beari
if(open[start]>close[last])
{
//--- generate the end of the candlestick
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start],close[last],high[index_max],low[index_min],fill_index,ExtBearFlag);
//--- exit the function
return;
}
//--- if the close price at the first bar is less than the one at the last bar, the candlestick is
if(open[start]<close[last])
{
//--- generate the end of the candlestick
FormCandleEnd(ExtBullBodyEndFirst,ExtBullBodyEndSecond,ExtBullShadowEndFirst,ExtBullShadowEnd
close[last],open[start],high[index_max],low[index_min],fill_index,ExtBullFlag);
//--- exit the function
return;
}
//--- if you are in this part of the function, the open price at the first bar is equal to
//--- the close price at the last bar; such candlestick is considered bearish
//--- generate the end of the candlestick
if(high[index_max]!=low[index_min])
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start]-ExtEmptyBodySize,high[index_max],low[index_min],fill_index,ExtBearF
else
FormCandleEnd(ExtBearBodyEndFirst,ExtBearBodyEndSecond,ExtBearShadowEndFirst,ExtBearShadowEnd
open[start]-ExtEmptyBodySize,high[index_max],high[index_max]-ExtEmptyBodySize,f
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1225 Array Functions

//| Custom indicator initialization function |


//+------------------------------------------------------------------+
int OnInit()
{
//--- check the indicator period
if(!CheckPeriod((int)Period(),(int)InpPeriod))
return(INIT_PARAMETERS_INCORRECT);
//--- display price data in the foreground
ChartSetInteger(0,CHART_FOREGROUND,0,1);
//--- binding indicator buffers
SetIndexBuffer(0,ExtBearBodyFirst);
SetIndexBuffer(1,ExtBearBodySecond);
SetIndexBuffer(2,ExtBearBodyEndFirst);
SetIndexBuffer(3,ExtBearBodyEndSecond);
SetIndexBuffer(4,ExtBearShadowFirst);
SetIndexBuffer(5,ExtBearShadowSecond);
SetIndexBuffer(6,ExtBearShadowEndFirst);
SetIndexBuffer(7,ExtBearShadowEndSecond);
SetIndexBuffer(8,ExtBullBodyFirst);
SetIndexBuffer(9,ExtBullBodySecond);
SetIndexBuffer(10,ExtBullBodyEndFirst);
SetIndexBuffer(11,ExtBullBodyEndSecond);
SetIndexBuffer(12,ExtBullShadowFirst);
SetIndexBuffer(13,ExtBullShadowSecond);
SetIndexBuffer(14,ExtBullShadowEndFirst);
SetIndexBuffer(15,ExtBullShadowEndSecond);
//--- set some property values for creating the indicator
for(int i=0;i<8;i++)
{
PlotIndexSetInteger(i,PLOT_DRAW_TYPE,DRAW_FILLING); // graphical construction type
PlotIndexSetInteger(i,PLOT_LINE_STYLE,STYLE_SOLID); // drawing line style
PlotIndexSetInteger(i,PLOT_LINE_WIDTH,1); // drawing line width
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| 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[])

© 2000-2025, MetaQuotes Ltd.


1226 Array Functions

{
//--- in case there are no calculated bars yet
if(prev_calculated==0)
{
//--- receive larger time frame's bars arrival time
if(!GetTimeData())
return(0);
}
//--- set direct indexing
ArraySetAsSeries(time,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(open,false);
ArraySetAsSeries(close,false);
//--- start variable for calculation of bars
int start=prev_calculated;
//--- if the bar is generated, recalculate the indicator value on it
if(start!=0 && start==rates_total)
start--;
//--- the loop for calculating the indicator values
for(int i=start;i<rates_total;i++)
{
//--- fill i elements of the indicator buffers by empty values
FillIndicatorBuffers(i);
//--- perform calculation for bars starting from InpDateStart date
if(time[i]>=InpDateStart)
{
//--- define position, from which the values are to be displayed, for the first time
if(ExtStartFlag)
{
//--- store the number of the initial bar
ExtStartPos=i;
//--- define the first date from the larger time frame exceeding time[i]
while(time[i]>=ExtTimeBuff[ExtCount])
if(ExtCount<ExtSize-1)
ExtCount++;
//--- change the value of the flag in order not to run into this block again
ExtStartFlag=false;
}
//--- check if there are still any elements in the array
if(ExtCount<ExtSize)
{
//--- wait for the current time frame's value to reach the larger time frame's one
if(time[i]>=ExtTimeBuff[ExtCount])
{
//--- draw the main part of the candlestick (without filling out the area between th
FillCandleMain(open,close,high,low,ExtStartPos,i-1,i-2,ExtIndexMax,ExtIndexMin);
//--- fill out the end of the candlestick (the area between the last and the penulti
FillCandleEnd(open,close,high,low,ExtStartPos,i-1,i-1,ExtIndexMax,ExtIndexMin);

© 2000-2025, MetaQuotes Ltd.


1227 Array Functions

//--- shift the initial position for drawing the next candlestick
ExtStartPos=i;
//--- increase the array counter
ExtCount++;
}
else
continue;
}
else
{
//--- reset the array values
ResetLastError();
//--- receive the last date from the larger time frame
if(CopyTime(Symbol(),InpPeriod,0,1,ExtCurrentTime)==-1)
{
Print("Data copy error, code = ",GetLastError());
return(0);
}
//--- if the new date is later, stop generating the candlestick
if(ExtCurrentTime[0]>ExtLastTime)
{
//--- clear the area between the last and penultimate bars in the main indicator buf
ClearEndOfBodyMain(i-1);
//--- fill out the area using auxiliary indicator buffers
FillCandleEnd(open,close,high,low,ExtStartPos,i-1,i-1,ExtIndexMax,ExtIndexMin);
//--- shift the initial position for drawing the next candlestick
ExtStartPos=i;
//--- reset price direction flag
ExtDirectionFlag=0;
//--- store the new last date
ExtLastTime=ExtCurrentTime[0];
}
else
{
//--- generate the candlestick
FillCandleMain(open,close,high,low,ExtStartPos,i,i,ExtIndexMax,ExtIndexMin);
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Check correctness of the specified indicator period |
//+------------------------------------------------------------------+
bool CheckPeriod(int current_period,int high_period)
{
//--- the indicator period should exceed the timeframe on which it is displayed

© 2000-2025, MetaQuotes Ltd.


1228 Array Functions

if(current_period>=high_period)
{
Print("Error! The value of the indicator period should exceed the value of the current time f
return(false);
}
//--- if the indicator period is one week or month, the period is correct
if(high_period>32768)
return(true);
//--- convert period values to minutes
if(high_period>30)
high_period=(high_period-16384)*60;
if(current_period>30)
current_period=(current_period-16384)*60;
//--- the indicator period should be multiple of the time frame it is displayed on
if(high_period%current_period!=0)
{
Print("Error! The value of the indicator period should be multiple of the value of the curren
return(false);
}
//--- the indicator period should exceed the time frame it is displayed on 3 or more times
if(high_period/current_period<3)
{
Print("Error! The indicator period should exceed the current time frame 3 or more times!");
return(false);
}
//--- the indicator period is correct for the current time frame
return(true);
}
//+------------------------------------------------------------------+
//| Receive time data from the larger time frame |
//+------------------------------------------------------------------+
bool GetTimeData(void)
{
//--- reset the error value
ResetLastError();
//--- copy all data for the current time
if(CopyTime(Symbol(),InpPeriod,InpDateStart,TimeCurrent(),ExtTimeBuff)==-1)
{
//--- receive the error code
int code=GetLastError();
//--- print out the error message
PrintFormat("Data copy error! %s",code==4401
? "History is still being uploaded!"
: "Code = "+IntegerToString(code));
//--- return false to make a repeated attempt to download data
return(false);
}
//--- receive the array size
ExtSize=ArraySize(ExtTimeBuff);

© 2000-2025, MetaQuotes Ltd.


1229 Array Functions

//--- set the loop index for the array to zero


ExtCount=0;
//--- set the current candlestick's position on the time frame to zero
ExtStartPos=0;
ExtStartFlag=true;
//--- store the last time value from the larger time frame
ExtLastTime=ExtTimeBuff[ExtSize-1];
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| Function forms the main part of the candlestick. Depending on the flag's |
//| value, the function defines what data and arrays are |
//| to be used for correct display. |
//+--------------------------------------------------------------------------+
void FormCandleMain(double &body_fst[],double &body_snd[],
double &shadow_fst[],double &shadow_snd[],
const double fst_value,const double snd_value,
const double fst_extremum,const double snd_extremum,
const int start,const int count,const bool flag)
{
//--- check the flag's value
if(flag)
{
//--- generate the candlestick's body
FormMain(body_fst,body_snd,fst_value,snd_value,start,count);
//--- generate the candlestick's shadow
FormMain(shadow_fst,shadow_snd,fst_extremum,snd_extremum,start,count);
}
else
{
//--- generate the candlestick's body
FormMain(body_fst,body_snd,snd_value,fst_value,start,count);
//--- generate the candlestick's shadow
FormMain(shadow_fst,shadow_snd,snd_extremum,fst_extremum,start,count);
}
}
//+--------------------------------------------------------------------------------+
//| The function forms the end of the candlestick. Depending on the flag's value, |
//| the function defines what data and arrays are |
//| to be used for correct display. |
//+--------------------------------------------------------------------------------+
void FormCandleEnd(double &body_fst[],double &body_snd[],
double &shadow_fst[],double &shadow_snd[],
const double fst_value,const double snd_value,
const double fst_extremum,const double snd_extremum,
const int end,bool &flag)
{
//--- check the flag's value

© 2000-2025, MetaQuotes Ltd.


1230 Array Functions

if(flag)
{
//--- generate the end of the candlestick's body
FormEnd(body_fst,body_snd,fst_value,snd_value,end);
//--- generate the end of the candlestick's shadow
FormEnd(shadow_fst,shadow_snd,fst_extremum,snd_extremum,end);
//--- change the flag's value to the opposite one
flag=false;
}
else
{
//--- generate the end of the candlestick's body
FormEnd(body_fst,body_snd,snd_value,fst_value,end);
//--- generate the end of the candlestick's shadow
FormEnd(shadow_fst,shadow_snd,snd_extremum,fst_extremum,end);
//--- change the flag's value to the opposite one
flag=true;
}
}
//+-------------------------------------------------------------------------------------+
//| Clear the end of the candlestick (the area between the last and the penultimate |
//| bar) |
//+-------------------------------------------------------------------------------------+
void ClearEndOfBodyMain(const int ind)
{
ClearCandle(ExtBearBodyFirst,ExtBearBodySecond,ExtBearShadowFirst,ExtBearShadowSecond,ind,1);
ClearCandle(ExtBullBodyFirst,ExtBullBodySecond,ExtBullShadowFirst,ExtBullShadowSecond,ind,1);
}
//+------------------------------------------------------------------+
//| Clear the candlestick |
//+------------------------------------------------------------------+
void ClearCandle(double &body_fst[],double &body_snd[],double &shadow_fst[],
double &shadow_snd[],const int start,const int count)
{
//--- check
if(count!=0)
{
//--- fill indicator buffers with empty values
ArrayFill(body_fst,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(body_snd,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(shadow_fst,start,count,INDICATOR_EMPTY_VALUE);
ArrayFill(shadow_snd,start,count,INDICATOR_EMPTY_VALUE);
}
}
//+------------------------------------------------------------------+
//| Generate the main part of the candlestick |
//+------------------------------------------------------------------+
void FormMain(double &fst[],double &snd[],const double fst_value,
const double snd_value,const int start,const int count)

© 2000-2025, MetaQuotes Ltd.


1231 Array Functions

{
//--- check
if(count!=0)
{
//--- fill indicator buffers with values
ArrayFill(fst,start,count,fst_value);
ArrayFill(snd,start,count,snd_value);
}
}
//+------------------------------------------------------------------+
//| Generate the end of the candlestick |
//+------------------------------------------------------------------+
void FormEnd(double &fst[],double &snd[],const double fst_value,
const double snd_value,const int last)
{
//--- fill indicator buffers with values
ArrayFill(fst,last-1,2,fst_value);
ArrayFill(snd,last-1,2,snd_value);
}
//+------------------------------------------------------------------+
//| Fill i element of the indicator buffers by empty values |
//+------------------------------------------------------------------+
void FillIndicatorBuffers(const int i)
{
//--- set an empty value in the cell of the indicator buffers
ExtBearBodyFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodySecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodyEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearBodyEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBearShadowEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodySecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullBodyEndSecond[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowEndFirst[i]=INDICATOR_EMPTY_VALUE;
ExtBullShadowEndSecond[i]=INDICATOR_EMPTY_VALUE;
}

© 2000-2025, MetaQuotes Ltd.


1232 Array Functions

ArrayPrint
Prints an array of a simple type or a simple structure into journal.
void ArrayPrint(
const void& array[], // printed array
uint digits=_Digits, // number of decimal places
const string separator=NULL, // separator of the structure field values
ulong start=0, // first printed element index
ulong count=WHOLE_ARRAY, // number of printed elements
ulong flags=ARRAYPRINT_HEADER|ARRAYPRINT_INDEX|ARRAYPRINT_LIMIT|ARRAYPRINT_ALIGN
);

Parameters
array[]
[in] Array of a simple type or a simple structure.
digits=_Digits
[in] The number of decimal places for real types. The default value is _Digits.
separator=NULL
[in] S eparator of the structure element field values. The default value NULL means an empty line.
A space is used as a separator in that case.

start=0
[in] The index of the first printed array element. It is printed from the zero index by default.
count=WHOLE_ARRAY
[in] Number of the array elements to be printed. The entire array is displayed by default
(count=WHOLE_ARRAY).
flags=ARRAYPRINT_HEADER|ARRAYPRINT_INDEX|ARRAYPRINT_LIMIT|ARRAYPRINT_ALIGN
[in] Combination of flags setting the output mode. All flags are enabled by default:
o ARRAYPRINT_HEADER – print headers for the structure array
o ARRAYPRINT_INDEX – print index at the left side
o ARRAYPRINT_LIMIT – print only the first 100 and the last 100 array elements. Use if you want to
print only a part of a large array.
o ARRAYPRINT_ALIGN – enable alignment of the printed values – numbers are aligned to the right,
while lines to the left.
o ARRAYPRINT_DATE – when printing datetime, print the date in the dd.mm.yyyy format
o ARRAYPRINT_MINUTES – when printing datetime, print the time in the HH:MM format
o ARRAYPRINT_SECONDS – when printing datetime, print the time in the HH:MM :SS format
Return Value
No

Note

ArrayPrint() does not print all structure array fields into journal – array and object pointer fields are
s kipped. These columns are simply not printed for more convenient presentation. If you need to

© 2000-2025, MetaQuotes Ltd.


1233 Array Functions

print all structure fields, you need to write your own mass print function with the desired
formatting.
Example:

//--- print the values of the last 10 bars


MqlRates rates[];
if(CopyRates(_Symbol,_Period,1,10,rates))
{
ArrayPrint(rates);
Print("Check\n[time]\t[open]\t[high]\t[low]\t[close]\t[tick_volume]\t[spread]\t[real_volume]"
for(int i=0;i<10;i++)
{
PrintFormat("[%d]\t%s\t%G\t%G\t%G\t%G\t%G\t%G\t%I64d\t",i,
TimeToString(rates[i].time,TIME_DATE|TIME_MINUTES|TIME_SECONDS),
rates[i].open,rates[i].high,rates[i].low,rates[i].close,
rates[i].tick_volume,rates[i].spread,rates[i].real_volume);
}
}
else
PrintFormat("CopyRates failed, error code=%d",GetLastError());
//--- example of printing
/*
[time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume]
[0] 2016.11.09 04:00:00 1.11242 1.12314 1.11187 1.12295 18110 10 17300175000
[1] 2016.11.09 05:00:00 1.12296 1.12825 1.11930 1.12747 17829 9 15632176000
[2] 2016.11.09 06:00:00 1.12747 1.12991 1.12586 1.12744 13458 10 9593492000
[3] 2016.11.09 07:00:00 1.12743 1.12763 1.11988 1.12194 15362 9 12352245000
[4] 2016.11.09 08:00:00 1.12194 1.12262 1.11058 1.11172 16833 9 12961333000
[5] 2016.11.09 09:00:00 1.11173 1.11348 1.10803 1.11052 15933 8 10720384000
[6] 2016.11.09 10:00:00 1.11052 1.11065 1.10289 1.10528 11888 9 8084811000
[7] 2016.11.09 11:00:00 1.10512 1.11041 1.10472 1.10915 7284 10 5087113000
[8] 2016.11.09 12:00:00 1.10915 1.11079 1.10892 1.10904 8710 9 6769629000
[9] 2016.11.09 13:00:00 1.10904 1.10913 1.10223 1.10263 8956 7 7192138000
Check
[time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume]
[0] 2016.11.09 04:00:00 1.11242 1.12314 1.11187 1.12295 18110 10 17300175000
[1] 2016.11.09 05:00:00 1.12296 1.12825 1.1193 1.12747 17829 9 15632176000
[2] 2016.11.09 06:00:00 1.12747 1.12991 1.12586 1.12744 13458 10 9593492000
[3] 2016.11.09 07:00:00 1.12743 1.12763 1.11988 1.12194 15362 9 12352245000
[4] 2016.11.09 08:00:00 1.12194 1.12262 1.11058 1.11172 16833 9 12961333000
[5] 2016.11.09 09:00:00 1.11173 1.11348 1.10803 1.11052 15933 8 10720384000
[6] 2016.11.09 10:00:00 1.11052 1.11065 1.10289 1.10528 11888 9 8084811000
[7] 2016.11.09 11:00:00 1.10512 1.11041 1.10472 1.10915 7284 10 5087113000
[8] 2016.11.09 12:00:00 1.10915 1.11079 1.10892 1.10904 8710 9 6769629000
[9] 2016.11.09 13:00:00 1.10904 1.10913 1.10223 1.10263 8956 7 7192138000
*/

See also

© 2000-2025, MetaQuotes Ltd.


1234 Array Functions

FileS ave, FileLoad

© 2000-2025, MetaQuotes Ltd.


1235 Array Functions

ArrayRange
The function returns the number of elements in a selected array dimension.
int ArrayRange(
const void& array[], // array for check
int rank_index // index of dimension
);

Parameters
array[]
[in] Checked array.
rank_index
[in] Index of dimension.

Return Value

Number of elements in a selected array dimension.


Note

S ince indexesstart at zero, the number of the array dimensions is one greater than the index of the
last dimension.
Example:

void OnStart()
{
//--- create four-dimensional array
double array[][5][2][4];
//--- set the size of the zero dimension
ArrayResize(array,10,10);
//--- print dimensions
int temp;
for(int i=0;i<4;i++)
{
//--- receive the size of i dimension
temp=ArrayRange(array,i);
//--- print
PrintFormat("dim = %d, range = %d",i,temp);
}
//--- Result
// dim = 0, range = 10
// dim = 1, range = 5
// dim = 2, range = 2
// dim = 3, range = 4
}

© 2000-2025, MetaQuotes Ltd.


1236 Array Functions

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 reserve_size=0 // reserve size value (excess)
);

Parameters
array[]
[out] Array for changing sizes.
new_size
[in] New size for the first dimension.
reserve_size=0
[in] Distributed size to get reserve.

Return Value

If executed successfully, it returns count of all elements contained in the array after resizing,
otherwise, returns -1, and array is not resized.
If ArrayResize() is applied to a static array, a timeseries or an indicator buffer, the array size
remains the same – these arrays will not be reallocated. In this case, if new_size<=ArrayS ize(array),
the function will only return new_size; otherwise a value of -1 will be returned.
Note

The function can be applied only to dynamic arrays. It should be noted that you cannot change the
size of dynamic arrays assigned as indicator buffers by the S etIndexBuffer() function. For indicator
buffers, all operations of resizing are performed by the runtime subsystem of the terminal.
Total amount of elements in the array cannot exceed 2147483647.
W ith the frequent memory allocation, it is recommended to use a third parameter that sets a
reserve to reduce the number of physical memory allocations. All the subsequent calls of ArrayResize
do not lead to physical reallocation of memory, but only change the size of the first array dimension
within the reserved memory. It should be remembered that the third parameter will be used only
during physical memory allocation. For example:
ArrayResize(arr,1000,1000);
for(int i=1;i<3000;i++)
ArrayResize(arr,i,1000);

In this case the memory will be reallocated twice, first before entering the 3000 iterations loop (the
array size will be set to 1000), and the second time with i equal to 2000. If we s kip the third
parameter, there will be 2000 physical reallocations of memory, which will slow down the program.
Example:

//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1237 Array Functions

//| Script program start function |


//+------------------------------------------------------------------+
void OnStart()
{
//--- Counters
ulong start=GetTickCount();
ulong now;
int count=0;
//--- An array for demonstration of a quick version
double arr[];
ArrayResize(arr,100000,100000);
//--- Check how fast the variant with memory reservation works
Print("--- Test Fast: ArrayResize(arr,100000,100000)");
for(int i=1;i<=300000;i++)
{
//--- Set a new array size specifying the reserve of 100,000 elements!
ArrayResize(arr,i,100000);
//--- When reaching a round number, show the array size and the time spent
if(ArraySize(arr)%100000==0)
{
now=GetTickCount();
count++;
PrintFormat("%d. ArraySize(arr)=%d Time=%d ms",count,ArraySize(arr),(now-start));
start=now;
}
}
//--- Now show, how slow the version without memory reservation is
double slow[];
ArrayResize(slow,100000,100000);
//---
count=0;
start=GetTickCount();
Print("---- Test Slow: ArrayResize(slow,100000)");
//---
for(int i=1;i<=300000;i++)
{
//--- Set a new array size, but without the additional reserve
ArrayResize(slow,i);
//--- When reaching a round number, show the array size and the time spent
if(ArraySize(slow)%100000==0)
{
now=GetTickCount();
count++;
PrintFormat("%d. ArraySize(slow)=%d Time=%d ms",count,ArraySize(slow),(now-start));
start=now;
}
}
}
//--- A sample result of the script

© 2000-2025, MetaQuotes Ltd.


1238 Array Functions

/*
Test_ArrayResize (EURUSD,H1) --- Test Fast: ArrayResize(arr,100000,100000)
Test_ArrayResize (EURUSD,H1) 1. ArraySize(arr)=100000 Time=0 ms
Test_ArrayResize (EURUSD,H1) 2. ArraySize(arr)=200000 Time=0 ms
Test_ArrayResize (EURUSD,H1) 3. ArraySize(arr)=300000 Time=0 ms
Test_ArrayResize (EURUSD,H1) ---- Test Slow: ArrayResize(slow,100000)
Test_ArrayResize (EURUSD,H1) 1. ArraySize(slow)=100000 Time=0 ms
Test_ArrayResize (EURUSD,H1) 2. ArraySize(slow)=200000 Time=0 ms
Test_ArrayResize (EURUSD,H1) 3. ArraySize(slow)=300000 Time=228511 ms
*/

See also
ArrayInitialize

© 2000-2025, MetaQuotes Ltd.


1239 Array Functions

ArrayInsert
Inserts the specified number of elements from a source array to a receiving one starting from a
specified index.
bool ArrayInsert(
void& dst_array[], // receiving array
const void& src_array[], // source array
uint dst_start, // receiver array index to be inserted
uint src_start=0, // source array index to be copied
uint count=WHOLE_ARRAY // number of elements to insert
);

Parameters
dst_array[]
[in][out] R eceiving array the elements should be added to.
src_array[]
[in] S ource array the elements are to be added from.
dst_start
[in] Index in the receiving array for inserting elements from the source array.
src_start=0
[in] Index in the source array, starting from which the elements of the source array are taken for
insertion.
count
[in] Number of elements to be added from the source array. The WH OL E_ARRAY means all
elements from the specified index up to the end of the array.

Return Value

R eturns true if successful, otherwise - false. To get information about the error, call the
GetLastError() function. Possible errors :
· 5052 – ERR_S M ALL _ARRAY (the start and/or count parameters are set incorrectly or the
src_array[] source array is empty),
· 5056 – ERR_SERIES_ARRAY (the array cannot be changed, indicator buffer),
· 4006 – ERR_INVALID_ARRAY (copying to oneself is not allowed, or the arrays are of different
types, or there is a fixed-size array containing class objects or destructor structures),
· 4005 - ERR_S T RUCT _W IT H OBJECT S_OR CL ASS (the array contains no POD structures meaning a
simple copying is impossible),
· Errors occurred when changing the dst_array[] receiving array size are provided in the
ArrayR emove() function description.

Note

If the function is used for a fixed-size array, the size of the dst_array[] receiving array itself does
not change. S tarting from the dst_start position, the elements of the receiving array are shifted to

© 2000-2025, MetaQuotes Ltd.


1240 Array Functions

the right (the last counts of the elements " come off" ), while the elements copied from the source
array take their place.
You cannot insert the elements to the dynamic arrays designated as the indicator buffers by the
S etIndex Buffer() function. For indicator buffers, all size changing operations are performed by the
terminal's executing subsystem.
In the source array, the elements are copied starting from the src_start index. The source array size
remains unchanged. The elements to be added to the receiving array are not links to the source
array elements. This means that subsequent changes of the elements in any of the two arrays are
not reflected in the second one.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare the fixed-size array and fill in the values
int array_dest[10];
for(int i=0;i<10;i++)
{
array_dest[i]=i;
}
//--- source array
int array_source[10];
for(int i=0;i<10;i++)
{
array_source[i]=10+i;
}
//--- display arrays before inserting the elements
Print("Before calling ArrayInsert()");
ArrayPrint(array_dest);
ArrayPrint(array_source);
//--- insert 3 elements from the source array and show the new set of the receiving array
ArrayInsert(array_dest,array_source,4,0,3);
Print("After calling ArrayInsert()");
ArrayPrint(array_dest);
/*
Execution result
Before calling ArrayInsert()
0 1 2 3 4 5 6 7 8 9
After calling ArrayInsert()
0 1 2 3 10 11 12 7 8 9
*/

See also
ArrayR emove, ArrayCopy, ArrayR esize, ArrayFree

© 2000-2025, MetaQuotes Ltd.


1241 Array Functions

© 2000-2025, MetaQuotes Ltd.


1242 Array Functions

ArrayRemove
R emoves the specified number of elements from the array starting with a specified index.
bool ArrayRemove(
void& array[], // array of any type
uint start, // index the removal starts from
uint count=WHOLE_ARRAY // number of elements
);

Parameters
array[]
[in][out] Array.

start
[in] Index, starting from which the array elements are removed.
count=WHOLE_ARRAY
[in] Number of removed elements. The WHOLE_ARRAY value means removing all elements from
the specified index up the end of the array.

Return Value

R eturns true if successful, otherwise - false. To get information about the error, call the
GetLastError() function. Possible errors :
· 5052 – ERR_S M ALL_ARRAY (too big start value),
· 5056 – ERR_SERIES_ARRAY (the array cannot be changed, indicator buffer),
· 4003 – ERR_INVALID_PARAM ET ER (too big count value),
· 4005 - ERR_S T RUCT _W IT H OBJECT S_OR CL ASS (fixed-size array containing complex objects with
the destructor),
· 4006 - ERR_INVALID_ARRAY (fixed-size array containing structure or class objects with a
destructor).

Note

If the function is used for a fixed-size array, the array size does not change: the remaining " tail" is
physically copied to the start position. For accurate understanding of how the function works, see
the example below. " Physical" copying means the copied objects are not created by calling the
constructor or copying operator. Instead, the binary representation of an object is copied. For this
reason, you cannot apply the ArrayRemove() function to the fixed-size array containing objects with
the destructor (the ERR_INVALID_ARRAY or ERR_S TRUCT_W ITHOBJECTS_ORCLASS error is
activated). W hen removing such an object, the destructor should be called twice – for the original
object and its copy.
You cannot remove elements from dynamic arrays designated as the indicator buffers by the
S etIndex Buffer() function. This will result in the ERR_SER IES_ARRAY error. For indicator buffers, all
size changing operations are performed by the terminal's executing subsystem.
Example:

//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1243 Array Functions

//| Script program start function |


//+------------------------------------------------------------------+
void OnStart()
{
//--- declare the fixed-size array and fill in the values
int array[10];
for(int i=0;i<10;i++)
{
array[i]=i;
}
//--- display the array before removing the elements
Print("Before calling ArrayRemove()");
ArrayPrint(array);
//--- delete 2 elements from the array and display the new set
ArrayRemove(array,4,2);
Print("After calling ArrayRemove()");
ArrayPrint(array);
/*
Execution result:
Before calling ArrayRemove()
0 1 2 3 4 5 6 7 8 9
After calling ArrayRemove()
0 1 2 3 6 7 8 9 8 9
*/

See also
ArrayInsert, ArrayCopy, ArrayR esize, ArrayFree

© 2000-2025, MetaQuotes Ltd.


1244 Array Functions

ArrayReverse
R everses the specified number of elements in the array starting with a specified index.
bool ArrayReverse(
void& array[], // array of any type
uint start=0, // index to start reversing the array from
uint count=WHOLE_ARRAY // number of elements
);

Parameters
array[]
[in][out] Array.

start=0
[in] Index the array reversal starts from.
count=WHOLE_ARRAY
[in] Number of reversed elements. If WHOLE_ARRAY, then all array elements are moved in the
inversed manner starting with the specified start index up to the end of the array.

Return Value

R eturns true if successful, otherwise - false.


Note

The ArrayS etAs S eries() function does not move the array elements physically. Instead, it only
changes the indexation direction backwards to arrange the access to the elements as in the
timeseries. The ArrayReverse() function physically moves the array elements so that the array is
" reversed" .

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare the fixed-size array and fill in the values
int array[10];
for(int i=0;i<10;i++)
{
array[i]=i;
}
//--- display the array before reversing the elements
Print("Before calling ArrayReverse()");
ArrayPrint(array);
//--- reverse 3 elements in the array and show the new set
ArrayReverse(array,4,3);
Print("After calling ArrayReverse()");

© 2000-2025, MetaQuotes Ltd.


1245 Array Functions

ArrayPrint(array);
/*
Execution result:
Before calling ArrayReverse()
0 1 2 3 4 5 6 7 8 9
After calling ArrayReverse()
0 1 2 3 6 5 4 7 8 9
*/

See also
ArrayInsert, ArrayR emove, ArrayCopy, ArrayR esize, ArrayFree, ArrayGetAs S eries, ArrayS etAs S eries

© 2000-2025, MetaQuotes Ltd.


1246 Array Functions

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(
const void& array[], // array by reference
bool flag // true denotes reverse order of indexing
);

Parameters
array[]
[in][out] Numeric array to set.
flag
[in] Array indexing direction.

Return Value

The function returns true on success, otherwise - false.


Note

The AS_SERIES flag can't be set for multi-dimensional arrays or static arrays (arrays, whose size in
s quare 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 towards the beginning
(from the newest to oldest data).
Example: Indicator that shows bar number

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
//---- plot Numeration

© 2000-2025, MetaQuotes Ltd.


1247 Array Functions

#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 array is displayed in DataWindow
PlotIndexSetString(0,PLOT_LABEL,"Bar #");
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| 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 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 from the 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);
}

© 2000-2025, MetaQuotes Ltd.


1248 Array Functions

See also
Access to timeseries, ArrayGetAs S eries

© 2000-2025, MetaQuotes Ltd.


1249 Array Functions

ArraySize
The function returns the number of elements of a selected array.
int ArraySize(
const void& array[] // checked array
);

Parameters
array[]
[in] Array of any type.

Return Value

Value of int type.


Note

For a one-dimensional array, the value to be returned by the ArrayS ize is equal to that of
ArrayR ange(array,0).

Example:

void OnStart()
{
//--- create arrays
double one_dim[];
double four_dim[][10][5][2];
//--- sizes
int one_dim_size=25;
int reserve=20;
int four_dim_size=5;
//--- auxiliary variable
int size;
//--- allocate memory without backup
ArrayResize(one_dim,one_dim_size);
ArrayResize(four_dim,four_dim_size);
//--- 1. one-dimensional array
Print("+==========================================================+");
Print("Array sizes:");
Print("1. One-dimensional array");
size=ArraySize(one_dim);
PrintFormat("Zero dimension size = %d, Array size = %d",one_dim_size,size);
//--- 2. multidimensional array
Print("2. Multidimensional array");
size=ArraySize(four_dim);
PrintFormat("Zero dimension size = %d, Array size = %d",four_dim_size,size);
//--- dimension sizes
int d_1=ArrayRange(four_dim,1);
int d_2=ArrayRange(four_dim,2);
int d_3=ArrayRange(four_dim,3);

© 2000-2025, MetaQuotes Ltd.


1250 Array Functions

Print("Check:");
Print("Zero dimension = Array size / (First dimension * Second dimension * Third dimension)");
PrintFormat("%d = %d / (%d * %d * %d)",size/(d_1*d_2*d_3),size,d_1,d_2,d_3);
//--- 3. one-dimensional array with memory backup
Print("3. One-dimensional array with memory backup");
//--- double the value
one_dim_size*=2;
//--- allocate memory with backup
ArrayResize(one_dim,one_dim_size,reserve);
//--- print out the size
size=ArraySize(one_dim);
PrintFormat("Size with backup = %d, Actual array size = %d",one_dim_size+reserve,size);
}

© 2000-2025, MetaQuotes Ltd.


1251 Array Functions

ArraySort
S orts the values in the first dimension of a multidimensional numeric array in the ascending order.
bool ArraySort(
void& array[] // array for sorting
);

Parameters
array[]
[in][out] Numeric array for sorting.

Return Value

The function returns true on success, otherwise - false.


Note

An array is always sorted in the ascending order irrespective of the AS_SER IES flag value.
Functions ArrayS ort and ArrayBS earch accept any-dimensional arrays as a parameter. However,
searching and sorting are always applied to the first (zero) dimension.
Example:

#property description "The indicator analyzes data for the last month and draws all candlesticks wi
#property description "and large tick volumes. The tick volume array is sorted out"
#property description "to define such candlesticks. The candlesticks having the volumes comprising
#property description "per cent of the array are considered small. The candlesticks having the tick
#property description "the last InpBigVolume per cent of the array are considered large."
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots 1
//--- plot
#property indicator_label1 "VolumeFactor"
#property indicator_type1 DRAW_COLOR_CANDLES
#property indicator_color1 clrDodgerBlue,clrOrange
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
//--- predefined constant
#define INDICATOR_EMPTY_VALUE 0.0
//--- input parameters
input int InpSmallVolume=15; // Percentage value of small volumes (<50)
input int InpBigVolume=20; // Percentage value of large volumes (<50)
//--- analysis start time (will be shifted)
datetime ExtStartTime;
//--- indicator buffers
double ExtOpenBuff[];
double ExtHighBuff[];
double ExtLowBuff[];

© 2000-2025, MetaQuotes Ltd.


1252 Array Functions

double ExtCloseBuff[];
double ExtColorBuff[];
//--- volume boundary values for displaying the candlesticks
long ExtLeftBorder=0;
long ExtRightBorder=0;
//+------------------------------------------------------------------+
//| Receive border values for tick volumes |
//+------------------------------------------------------------------+
bool GetVolumeBorders(void)
{
//--- variables
datetime stop_time; // copy end time
long buff[]; // buffer for copying
//--- end time is the current one
stop_time=TimeCurrent();
//--- start time is one month earlier from the current one
ExtStartTime=GetStartTime(stop_time);
//--- receive the values of tick volumes
ResetLastError();
if(CopyTickVolume(Symbol(),Period(),ExtStartTime,stop_time,buff)==-1)
{
//--- failed to receive the data, return false to launch recalculation command
PrintFormat("Failed to receive tick volume values. Error code = %d",GetLastError());
return(false);
}
//--- calculate array size
int size=ArraySize(buff);
//--- sort out the array
ArraySort(buff);
//--- define the values of the left and right border for tick volumes
ExtLeftBorder=buff[size*InpSmallVolume/100];
ExtRightBorder=buff[(size-1)*(100-InpBigVolume)/100];
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Receive the data that is one month less than the passed one |
//+------------------------------------------------------------------+
datetime GetStartTime(const datetime stop_time)
{
//--- convert end time into MqlDateTime type structure variable
MqlDateTime temp;
TimeToStruct(stop_time,temp);
//--- receive the data that is one month less
if(temp.mon>1)
temp.mon-=1; // the current month is not the first one in the year, therefore, the number of
else
{
temp.mon=12; // the current month is the first in the year, therefore, the number of the pre

© 2000-2025, MetaQuotes Ltd.


1253 Array Functions

temp.year-=1; // while the year number is one less


}
//--- day number will not exceed 28
if(temp.day>28)
temp.day=28;
//--- return the obtained date
return(StructToTime(temp));
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- check if input parameters satisfy the conditions
if(InpSmallVolume<0 || InpSmallVolume>=50 || InpBigVolume<0 || InpBigVolume>=50)
{
Print("Incorrect input parameters");
return(INIT_PARAMETERS_INCORRECT);
}
//--- indicator buffers mapping
SetIndexBuffer(0,ExtOpenBuff);
SetIndexBuffer(1,ExtHighBuff);
SetIndexBuffer(2,ExtLowBuff);
SetIndexBuffer(3,ExtCloseBuff);
SetIndexBuffer(4,ExtColorBuff,INDICATOR_COLOR_INDEX);
//--- set the value that will not be displayed
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,INDICATOR_EMPTY_VALUE);
//--- set labels for indicator buffers
PlotIndexSetString(0,PLOT_LABEL,"Open;High;Low;Close");
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| 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[])
{
//--- check if unhandled bars are still present
if(prev_calculated<rates_total)
{

© 2000-2025, MetaQuotes Ltd.


1254 Array Functions

//--- receive new values of the right and left borders for volumes
if(!GetVolumeBorders())
return(0);
}
//--- start variable for bar calculation
int start=prev_calculated;
//--- work at the last bar if the indicator values have already been calculated at the previous tic
if(start>0)
start--;
//--- set direct indexing in time series
ArraySetAsSeries(time,false);
ArraySetAsSeries(open,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(close,false);
ArraySetAsSeries(tick_volume,false);
//--- the loop of calculation of the indicator values
for(int i=start;i<rates_total;i++)
{
//--- fill out candlesticks starting from the initial date
if(ExtStartTime<=time[i])
{
//--- if the value is not less than the right border, fill out the candlestick
if(tick_volume[i]>=ExtRightBorder)
{
//--- receive data for drawing the candlestick
ExtOpenBuff[i]=open[i];
ExtHighBuff[i]=high[i];
ExtLowBuff[i]=low[i];
ExtCloseBuff[i]=close[i];
//--- DodgerBlue color
ExtColorBuff[i]=0;
//--- continue the loop
continue;
}
//--- fill out the candlestick if the value does not exceed the left border
if(tick_volume[i]<=ExtLeftBorder)
{
//--- receive data for drawing the candlestick
ExtOpenBuff[i]=open[i];
ExtHighBuff[i]=high[i];
ExtLowBuff[i]=low[i];
ExtCloseBuff[i]=close[i];
//--- Orange color
ExtColorBuff[i]=1;
//--- continue the loop
continue;
}
}

© 2000-2025, MetaQuotes Ltd.


1255 Array Functions

//--- set empty values for bars that have not been included in the calculation
ExtOpenBuff[i]=INDICATOR_EMPTY_VALUE;
ExtHighBuff[i]=INDICATOR_EMPTY_VALUE;
ExtLowBuff[i]=INDICATOR_EMPTY_VALUE;
ExtCloseBuff[i]=INDICATOR_EMPTY_VALUE;
}
//--- return value of prev_calculated for next call
return(rates_total);
}

See also
ArrayBsearch

© 2000-2025, MetaQuotes Ltd.


1256 Array Functions

ArraySwap
S waps the contents of two dynamic arrays of the same type. For multidimensional arrays, the number
of elements in all dimensions except the first one should match.
bool ArraySwap(
void& array1[], // first array
void& array2[] // second array
);

Parameters
array1[]
[in][out] Array of numerical type.
array2[]
[in][out] Array of numerical type.

Return Value

R eturns true if successful, otherwise false. In this case, GetLastError() returns the
ERR_INVALID_ARRAY error code.

Note

The function accepts dynamic arrays of the same type and the same dimensions except the first
one. For integer types, the sign is ignored, i.e. char==uchar)
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- arrays for storing quotes
double source_array[][8];
double dest_array[][8];
MqlRates rates[];
//--- get the data of the last 20 candles on the current timeframe
int copied=CopyRates(NULL,0,0,20,rates);
if(copied<=0)
{
PrintFormat("CopyRates(%s,0,0,20,rates) failed, error=%d",
Symbol(),GetLastError());
return;
}
//--- set the array size for the amount of copied data
ArrayResize(source_array,copied);
//--- fill the rate_array_1[] array by data from rates[]
for(int i=0;i<copied;i++)
{

© 2000-2025, MetaQuotes Ltd.


1257 Array Functions

source_array[i][0]=(double)rates[i].time;
source_array[i][1]=rates[i].open;
source_array[i][2]=rates[i].high;
source_array[i][3]=rates[i].low;
source_array[i][4]=rates[i].close;
source_array[i][5]=(double)rates[i].tick_volume;
source_array[i][6]=(double)rates[i].spread;
source_array[i][7]=(double)rates[i].real_volume;
}
//--- swap data between source_array[] and dest_array[]
if(!ArraySwap(source_array,dest_array))
{
PrintFormat("ArraySwap(source_array,rate_array_2) failed, error code=%d",GetLastError());
return;
}
//--- ensure that the source array has become zero after the swap
PrintFormat("ArraySwap() done: ArraySize(source_array)=%d",ArraySize(source_array));
//--- display the data of the dest_array[] destination array
ArrayPrint(dest_array);
}

See also
ArrayCopy, ArrayFill, ArrayR ange, ArrayIs Dynamic

© 2000-2025, MetaQuotes Ltd.


1258 Array Functions

ArrayToFP16
Copies an array of type float or double into an array of type ushort with the given format.
bool ArrayToFP16(
const ushort& dst_array[], // copy to
const float& src_array[], // copy from
ENUM_FLOAT16_FORMAT fmt // format
);

Overloading for the double type


bool ArrayToFP16(
const ushort& dst_array[], // copy to
const double& src_array[], // copy from
ENUM_FLOAT16_FORMAT fmt // format
);

Parameters
dst_array[]
[out] R eceiver array or type ushort.
src_array[]
[in] S ource array of type float or double.
fmt
[in] Copying format from the ENUM _FLOAT16_FORM AT enumeration.

Return Value

R eturns true if successful or false otherwise.

Note

Formats FLOAT 16 and BFLOAT16 are defined in the ENUM _FLOAT16_FORM AT enumeration and are
used in MQL5 only for operations with ONNX models.
The function converts input parameters of type float or double to type FLOAT16 and BFLOAT 16.
These input parameters are then used in the OnnxRun function.
FLOAT 16, also known as half-precision float, uses 16 bits to represent floating-point numbers. This
format provides a balance between accuracy and computational efficiency. FLOAT16 is widely used
in deep learning algorithms and neural networks, which require high-performance processing of large
datasets. This format accelerates computations calculations by reducing the size of numbers, which
is especially important when training deep neural networks on GPUs.
BFLOAT 16 (or Brain Floating Point 16) also uses 16 bits but differs from FLOAT16 in the approach to
format representation. In this format, 8 bits are allocated for representing the exponent, while the
remaining 7 bits are used for representing the mantissa. This format was developed for use in deep
learning and artificial intelligence, especially in Google's Tensor Processing Unit (TPU). BFLOAT16

© 2000-2025, MetaQuotes Ltd.


1259 Array Functions

demonstrates excellent performance in neural network training and can effectively accelerate
computations.

Example: function from the article W orking with ONNX models in float16 and float8 formats
//+------------------------------------------------------------------+
//| RunCastFloat16ToDouble |
//+------------------------------------------------------------------+
bool RunCastFloat16ToDouble(long model_handle)
{
PrintFormat("test=%s",__FUNCTION__);
double test_data[12]= {1,2,3,4,5,6,7,8,9,10,11,12};
ushort data_uint16[12];
if(!ArrayToFP16(data_uint16,test_data,FLOAT_FP16))
{
Print("error in ArrayToFP16. error code=",GetLastError());
return(false);
}
Print("test array:");
ArrayPrint(test_data);
Print("ArrayToFP16:");
ArrayPrint(data_uint16);
U<ushort> input_float16_values[3*4];
U<double> output_double_values[3*4];
float test_data_float[];
if(!ArrayFromFP16(test_data_float,data_uint16,FLOAT_FP16))
{
Print("error in ArrayFromFP16. error code=",GetLastError());
return(false);
}
for(int i=0; i<12; i++)
{
input_float16_values[i].value=data_uint16[i];
PrintFormat("%d input value =%f Hex float16 = %s ushort value=%d",i,test_data_float[i],Arra
}
Print("ONNX input array:");
ArrayPrint(input_float16_values);
bool res=OnnxRun(model_handle,ONNX_NO_CONVERSION,input_float16_values,output_double_values);
if(!res)
{
PrintFormat("error in OnnxRun. error code=%d",GetLastError());
return(false);
}
Print("ONNX output array:");
ArrayPrint(output_double_values);
//---
double sum_error=0.0;
for(int i=0; i<12; i++)

© 2000-2025, MetaQuotes Ltd.


1260 Array Functions

{
double delta=test_data[i]-output_double_values[i].value;
sum_error+=MathAbs(delta);
PrintFormat("%d output double %f = %s difference=%f",i,output_double_values[i].value,ArrayTo
}
//---
PrintFormat("test=%s sum_error=%f",__FUNCTION__,sum_error);
//---
return(true);
}

See also
ArrayFromFP16, ArrayCopy

© 2000-2025, MetaQuotes Ltd.


1261 Array Functions

ArrayToFP8
Copies an array of type float or double into an array of type uchar with the given format.
bool ArrayToFP8(
const uchar& dst_array[], // copy to
const float& src_array[], // copy from
ENUM_FLOAT8_FORMAT fmt // format
);

Overloading for the double type


bool ArrayToFP8(
const uchar& dst_array[], // copy to
const double& src_array[], // copy from
ENUM_FLOAT8_FORMAT fmt // format
);

Parameters
dst_array[]
[out] R eceiver array or type uchar.
src_array[]
[in] S ource array of type float or double.
fmt
[in] Copying format from the ENUM _FLOAT8_FORM AT enumeration.

Return Value

R eturns true if successful or false otherwise.

Note

All k inds
of FP8 format are defined in the ENUM _FLOAT8_FORM AT enumeration and are used in
MQL5 only for operations with ONNX models.
The function converts input parameters of type float or double into one of FP8 types. These input
parameters are then used in the OnnxRun function.
FP8 (8-bit floating point) is one of the data types used to represent floating point numbers. In FP8,
each number is represented by 8 data bits, typically divided into three components : sign, exponent
and mantissa. This format offers a balance between accuracy and storage efficiency, making it
attractive for applications that require memory and computational efficiency.
By employing compact number representation, FP8 reduces memory requirements and accelerates
calculations. In addition, FP8 can be useful for implementing low-level operations such as arithmetic
calculations and signal processing.

© 2000-2025, MetaQuotes Ltd.


1262 Array Functions

Example: function from the article W orking with ONNX models in float16 and float8 formats
//+------------------------------------------------------------------+
//| RunCastFloat8Float |
//+------------------------------------------------------------------+
bool RunCastFloat8ToFloat(long model_handle,const ENUM_FLOAT8_FORMAT fmt)
{
PrintFormat("TEST: %s(%s)",__FUNCTION__,EnumToString(fmt));
//---
float test_data[15] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
uchar data_float8[15] = {};
if(!ArrayToFP8(data_float8,test_data,fmt))
{
Print("error in ArrayToFP8. error code=",GetLastError());
OnnxRelease(model_handle);
return(false);
}
U<uchar> input_float8_values[3*5];
U<float> output_float_values[3*5];
float test_data_float[];
//--- convert float8 to float
if(!ArrayFromFP8(test_data_float,data_float8,fmt))
{
Print("error in ArrayFromFP8. error code=",GetLastError());
OnnxRelease(model_handle);
return(false);
}
for(uint i=0; i<data_float8.Size(); i++)
{
input_float8_values[i].value=data_float8[i];
PrintFormat("%d input value =%f Hex float8 = %s ushort value=%d",i,test_data_float[i],Array
}
Print("ONNX input array: ",ArrayToString(input_float8_values));
//--- execute model (convert float8 to float using ONNX)
if(!OnnxRun(model_handle,ONNX_NO_CONVERSION,input_float8_values,output_float_values))
{
PrintFormat("error in OnnxRun. error code=%d",GetLastError());
OnnxRelease(model_handle);
return(false);
}
Print("ONNX output array: ",ArrayToString(output_float_values));
//--- calculate error (compare ONNX and ArrayFromFP8 results)
double sum_error=0.0;
for(uint i=0; i<test_data.Size(); i++)
{
double delta=test_data_float[i]-(double)output_float_values[i].value;
sum_error+=MathAbs(delta);
PrintFormat("%d output float %f = %s difference=%f",i,output_float_values[i].value,ArrayToHex
}

© 2000-2025, MetaQuotes Ltd.


1263 Array Functions

//---
PrintFormat("%s(%s): sum_error=%f\n",__FUNCTION__,EnumToString(fmt),sum_error);
return(true);
}

See also
ArrayFromFP8, ArrayCopy

© 2000-2025, MetaQuotes Ltd.


1264 Array Functions

ArrayFromFP16
Copies an array of type ushort into an array of float or double type with the given format.
bool ArrayFromFP16(
const float& dst_array[], // copy to
const ushort& src_array[], // copy from
ENUM_FLOAT16_FORMAT fmt // format
);

Overloading for the double type


bool ArrayFromFP16(
const double& dst_array[], // copy to
const ushort& src_array[], // copy from
ENUM_FLOAT16_FORMAT fmt // format
);

Parameters
dst_array[]
[out] R eceiver array of type float or double.
src_array[]
[in] S ource array of type ushort.
fmt
[in] Copying format from the ENUM _FLOAT16_FORM AT enumeration.

Return Value

R eturns true if successful or false otherwise.

Note

Formats FLOAT 16 and BFLOAT16 are defined in the ENUM _FLOAT16_FORM AT enumeration and are
used in MQL5 only for operations with ONNX models.
If the output parameters obtained from the OnnxRun function execution are of type FLOAT16 and
BFLOAT 16, you can use this function to convert the result to float or double arrays.

FLOAT 16, also known as half-precision float, uses 16 bits to represent floating-point numbers. This
format provides a balance between accuracy and computational efficiency. FLOAT16 is widely used
in deep learning algorithms and neural networks, which require high-performance processing of large
datasets. This format accelerates computations calculations by reducing the size of numbers, which
is especially important when training deep neural networks on GPUs.
BFLOAT 16 (or Brain Floating Point 16) also uses 16 bits but differs from FLOAT16 in the approach to
format representation. In this format, 8 bits are allocated for representing the exponent, while the
remaining 7 bits are used for representing the mantissa. This format was developed for use in deep
learning and artificial intelligence, especially in Google's Tensor Processing Unit (TPU). BFLOAT16

© 2000-2025, MetaQuotes Ltd.


1265 Array Functions

demonstrates excellent performance in neural network training and can effectively accelerate
computations.

Example: function from the article W orking with ONNX models in float16 and float8 formats
//+------------------------------------------------------------------+
//| RunCastFloat16ToDouble |
//+------------------------------------------------------------------+
bool RunCastFloat16ToDouble(long model_handle)
{
PrintFormat("test=%s",__FUNCTION__);
double test_data[12]= {1,2,3,4,5,6,7,8,9,10,11,12};
ushort data_uint16[12];
if(!ArrayToFP16(data_uint16,test_data,FLOAT_FP16))
{
Print("error in ArrayToFP16. error code=",GetLastError());
return(false);
}
Print("test array:");
ArrayPrint(test_data);
Print("ArrayToFP16:");
ArrayPrint(data_uint16);
U<ushort> input_float16_values[3*4];
U<double> output_double_values[3*4];
float test_data_float[];
if(!ArrayFromFP16(test_data_float,data_uint16,FLOAT_FP16))
{
Print("error in ArrayFromFP16. error code=",GetLastError());
return(false);
}
for(int i=0; i<12; i++)
{
input_float16_values[i].value=data_uint16[i];
PrintFormat("%d input value =%f Hex float16 = %s ushort value=%d",i,test_data_float[i],Arra
}
Print("ONNX input array:");
ArrayPrint(input_float16_values);
bool res=OnnxRun(model_handle,ONNX_NO_CONVERSION,input_float16_values,output_double_values);
if(!res)
{
PrintFormat("error in OnnxRun. error code=%d",GetLastError());
return(false);
}
Print("ONNX output array:");
ArrayPrint(output_double_values);
//---
double sum_error=0.0;
for(int i=0; i<12; i++)

© 2000-2025, MetaQuotes Ltd.


1266 Array Functions

{
double delta=test_data[i]-output_double_values[i].value;
sum_error+=MathAbs(delta);
PrintFormat("%d output double %f = %s difference=%f",i,output_double_values[i].value,ArrayTo
}
//---
PrintFormat("test=%s sum_error=%f",__FUNCTION__,sum_error);
//---
return(true);
}

See also
ArrayToFP16, ArrayCopy

© 2000-2025, MetaQuotes Ltd.


1267 Array Functions

ArrayFromFP8
Copies an array of type uchar into an array of float or double type with the given format.
bool ArrayFromFP8(
const float& dst_array[], // copy to
const uchar& src_array[], // copy from
ENUM_FLOAT8_FORMAT fmt // format
);

Overloading for the double type


bool ArrayFromFP8(
const double& dst_array[], // copy to
const uchar& src_array[], // copy from
ENUM_FLOAT8_FORMAT fmt // format
);

Parameters
dst_array[]
[out] R eceiver array of type float or double.
src_array[]
[in] S ource array of type uchar.
fmt
[in] Copying format from the ENUM _FLOAT8_FORM AT enumeration.

Return Value

R eturns true if successful or false otherwise.

Note

All k inds
of FP8 format are defined in the ENUM _FLOAT8_FORM AT enumeration and are used in
MQL5 only for operations with ONNX models.
If the output parameters obtained from the OnnxRun function execution are of FP8 from the
ENUM _FLOAT 8_FOR M AT enumeration, you can use this function to convert the result into float or
double arrays.
FP8 (8-bit floating point) is one of the data types used to represent floating point numbers. In FP8,
each number is represented by 8 data bits, typically divided into three components : sign, exponent
and mantissa. This format offers a balance between accuracy and storage efficiency, making it
attractive for applications that require memory and computational efficiency.
By employing compact number representation, FP8 reduces memory requirements and accelerates
calculations. In addition, FP8 can be useful for implementing low-level operations such as arithmetic
calculations and signal processing.

© 2000-2025, MetaQuotes Ltd.


1268 Array Functions

Example: function from the article W orking with ONNX models in float16 and float8 formats
//+------------------------------------------------------------------+
//| RunCastFloat8Float |
//+------------------------------------------------------------------+
bool RunCastFloat8ToFloat(long model_handle,const ENUM_FLOAT8_FORMAT fmt)
{
PrintFormat("TEST: %s(%s)",__FUNCTION__,EnumToString(fmt));
//---
float test_data[15] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
uchar data_float8[15] = {};
if(!ArrayToFP8(data_float8,test_data,fmt))
{
Print("error in ArrayToFP8. error code=",GetLastError());
OnnxRelease(model_handle);
return(false);
}
U<uchar> input_float8_values[3*5];
U<float> output_float_values[3*5];
float test_data_float[];
//--- convert float8 to float
if(!ArrayFromFP8(test_data_float,data_float8,fmt))
{
Print("error in ArrayFromFP8. error code=",GetLastError());
OnnxRelease(model_handle);
return(false);
}
for(uint i=0; i<data_float8.Size(); i++)
{
input_float8_values[i].value=data_float8[i];
PrintFormat("%d input value =%f Hex float8 = %s ushort value=%d",i,test_data_float[i],Array
}
Print("ONNX input array: ",ArrayToString(input_float8_values));
//--- execute model (convert float8 to float using ONNX)
if(!OnnxRun(model_handle,ONNX_NO_CONVERSION,input_float8_values,output_float_values))
{
PrintFormat("error in OnnxRun. error code=%d",GetLastError());
OnnxRelease(model_handle);
return(false);
}
Print("ONNX output array: ",ArrayToString(output_float_values));
//--- calculate error (compare ONNX and ArrayFromFP8 results)
double sum_error=0.0;
for(uint i=0; i<test_data.Size(); i++)
{
double delta=test_data_float[i]-(double)output_float_values[i].value;
sum_error+=MathAbs(delta);

© 2000-2025, MetaQuotes Ltd.


1269 Array Functions

PrintFormat("%d output float %f = %s difference=%f",i,output_float_values[i].value,ArrayToHex


}
//---
PrintFormat("%s(%s): sum_error=%f\n",__FUNCTION__,EnumToString(fmt),sum_error);
return(true);
}

See also
ArrayToFP8, ArrayCopy

© 2000-2025, MetaQuotes Ltd.


1270 Matrix and Vector Methods

Matrices and vectors


A matrix is a two-dimensional array of double, float, or complex numbers.
A vector is a one-dimensional array of double, float, or complex numbers. The vector has no indication
of whether it is vertical or horizontal. It is determined from the use context. For example, the vector
operation Dot assumes that the left vector is horizontal and the right one is vertical. If the type
indication is required, one-row or one-column matrices can be used. However, this is generally not
necessary.
Matrices and vectors allocate memory for data dynamically. In fact, matrices and vectors are objects
that have certain properties, such as the type of data they contain and dimensions. Matrix and vector
properties can be obtained using methods such as vector_a.S ize(), matrix_b.Rows(), vector_c.Norm(),
matrix_d.Cond() and others. Any dimension can be changed.
W hen creating and initializing matrices, so-called static methods are used (these are like static
methods of a class). For example: matrix::Eye(), matrix::Identity(), matrix::Ones(), vector::Ones(),
matrix: :Zeros(), vector::Zeros(), matrix::Full(), vector::Full(), matrix::Tri().
At themoment, matrix and vector operations do not imply the use of the complex data type, as this
development direction has not yet been completed.
MQL5 supports passing of matrices and vectors to DLLs. This enables the import of functions utilizing
the relevant types, from external variables.
Matrices and vectors are passed to a DLL as a pointer to a buffer. For example, to pass a matrix of
type float, the corresponding parameter of the function exported from the DLL must take a float-type
buffer pointer.
MQL5
#import "mmlib.dll"
bool sgemm(uint flags, matrix<float> &C, const matrix<float> &A, const matrix<float> &B, ulong M, u
#import

C++
extern "C" __declspec(dllexport) bool sgemm(UINT flags, float *C, const float *A, const float *B, U

In addition to buffers, you should pass matrix and vector sizes for correct processing.
All matrix and vector methods are listed below in alphabetical order.

Function Action Category

Activation Compute activation function Machine learning


values and write them to the
passed vector/matrix
ArgMax R eturnthe index of the S tatistics
maximum value
ArgMin R eturnthe index of the S tatistics
minimum value

© 2000-2025, MetaQuotes Ltd.


1271 Matrix and Vector Methods

Function Action Category

Arg S ort R eturn the sorted index Manipulations


Assign Copies a matrix, vector or array Initialization
with auto cast
Average Compute the weighted average S tatistics
of matrix/vector values
Choles ky Compute the Choles ky Transformations
decomposition
Clip Limits the elements of a Manipulations
matrix/vector to a given range
of valid values
Col R eturn acolumn vector. W rite a Manipulations
vector to the specified column.
Cols R eturn the number of columns in Features
a matrix
Compare Compare the elements of two Manipulations
matrices /vectors with the
specified precision
CompareByDigits Compare the elements of two Manipulations
matrices /vectors with the
significant figures precision
Cond Compute the condition number Features
of a matrix
Convolve R eturn the discrete, linear Products
convolution of two vectors
Copy R eturn a copy of the given Manipulations
matrix/vector
CopyIndicatorBuffer Get the data of the specified Initialization
indicator buffer in the specified
quantity to a vector

CopyRates Gets the historical series of


the Initialization
M qlRates structure of the
specified symbol-period in the
specified amount into a matrix
or vector
CopyTicks Get ticks from an M qlTick Initialization
structure into a matrix or a
vector
CopyTicks Range Get ticks from an M qlTick Initialization
structure into a matrix or a

© 2000-2025, MetaQuotes Ltd.


1272 Matrix and Vector Methods

Function Action Category

vector within the specified date


range
CorrCoef Compute the Pearson correlation Products
coefficient (linear correlation
coefficient)
Correlate Compute the cross-correlation Products
of two vectors
Cov Compute the covariance matrix Products
CumProd R eturn the cumulative product S tatistics
of matrix/vector elements,
including those along the given
axis
CumS um R eturn the cumulative sum of S tatistics
matrix/vector elements,
including those along the given
axis
Derivative Compute activation function Machine learning
derivative values and write
them to the passed
vector/matrix
Det Compute the determinant of a Features
s quare invertible matrix
Diag Extract adiagonal or construct a Manipulations
diagonal matrix
Dot Dot product of two vectors Products
Eig Computes the eigenvalues and Transformations
right eigenvectors of a s quare
matrix
Eig Vals Computes the eigenvalues of a Transformations
general matrix
Eye R eturna matrix with ones on Initialization
the diagonal and zeros
elsewhere
Fill Fillan existing matrix or vector Initialization
with the specified value
Flat Access a matrix element Manipulations
through one index instead of
two

© 2000-2025, MetaQuotes Ltd.


1273 Matrix and Vector Methods

Function Action Category

Full Create and return a new matrix Initialization


filled with the given value
GeMM The GeMM (General Matrix Products
Multiply) method implements
the general multiplication of two
matrices
H as Nan R eturn the number of NaN Manipulations
values in a matrix/vector
H split S plit a matrix horizontally into Manipulations
multiple submatrices. S ame as
S plit with axis =0

Identity Create an identity matrix of the Initialization


specified size
Init Matrix or vector initialization Initialization
Inner Inner product of two matrices Products
Inv Compute the multiplicative S olutions
inverse of a s quare invertible
matrix by the Jordan-Gauss
method
Kron R eturn Kroneck er
product of two Products
matrices, matrix and vector,
vector and matrix or two
vectors
Loss Compute loss function values Machine learning
and write them to the passed
vector/matrix
LstSq R eturn the least-s quares S olutions
solution of linear algebraic
equations (for non-s quare or
degenerate matrices)
LU Implement an LU decomposition Transformations
of a matrix: the product of a
lower triangular matrix and an
upper triangular matrix
LUP Implement an LUP factorization Transformations
with partial permutation, which
refers to LU decomposition with
row permutations only: PA=LU
MatMul Matrix product of two matrices Products

© 2000-2025, MetaQuotes Ltd.


1274 Matrix and Vector Methods

Function Action Category

Max R eturn the maximum value in a S tatistics


matrix/vector
Mean Compute the arithmetic mean of S tatistics
element values
Median Compute the median of the S tatistics
matrix/vector elements
Min R eturn the minimum value in a S tatistics
matrix/vector
Norm R eturn matrix or vector norm Features

Ones Create and return a new matrix Initialization


filled with ones
Outer Compute the outer product of Products
two matrices or two vectors
Percentile R eturn the specified percentile S tatistics
of values of matrix/vector
elements or elements along the
specified axis
PInv Compute the pseudo-inverse of S olutions
a matrix by the Moore-Penrose
method
Power R aise a s quare matrix to an Products
integer power
Prod R eturn the product of S tatistics
matrix/vectorelements, which
can also be executed for the
given axis
Ptp R eturn the range of values of a S tatistics
matrix/vector or of the given
matrix axis
QR Compute the qr factorization of Transformations
a matrix
Quantile R eturn the specified quantile of S tatistics
values of matrix/vector
elements or elements along the
specified axis
R ank R eturn matrix rank using the Features
Gaussian method

R egressionMetric Compute the regression metric S tatistics


as the deviation error from the

© 2000-2025, MetaQuotes Ltd.


1275 Matrix and Vector Methods

Function Action Category

regression line constructed on


the specified data array
R eshape Change the shape of a matrix Manipulations
without changing its data
R esize R eturna new matrix with a Manipulations
changed shape and size
R ow R eturn a row vector. W rite the Manipulations
vector to the specified row
R ows R eturn the number of rows in a Features
matrix
S et S etsthe value for a vector Manipulations
element by the specified index
S ize R eturn the size of vector Features

S Log Det Compute the sign and logarithm Features


of the determinant of an matrix
S olve S olvea linear matrix equation S olutions
or a system of linear algebraic
equations
S ort S ort by place Manipulations
S pectrum Compute spectrum of a matrix Features
as the set of its eigenvalues
from the product AT*A
S plit S plit
a matrix into multiple Manipulations
submatrices
S td R eturn the standard deviation of S tatistics
values of matrix/vector
elements or elements along the
specified axis
S um R eturn the sum of S tatistics
matrix/vector elements,which
can also be executed for the
given axis (axes)
SVD S ingular value decomposition Transformations
S wapCols S wap columns in a matrix Manipulations
S wapR ows S wap rows in a matrix Manipulations
Trace R eturn the sum along diagonals Features
of the matrix

© 2000-2025, MetaQuotes Ltd.


1276 Matrix and Vector Methods

Function Action Category

Transpose Transpose (swap the axes) and Manipulations


return the modified matrix
Tri Construct a matrix with ones on Initialization
a specified diagonal and below,
and zeros elsewhere
TriL R eturn a copy of a matrix with Manipulations
elements above the k-th
diagonal zeroed. Lower
triangular matrix
TriU R eturn a copy of a matrix with Manipulations
the elements below the k-th
diagonal zeroed. Upper
triangular matrix
Var Compute the variance of values S tatistics
of matrix/vector elements
Vsplit S plit a matrix vertically into Manipulations
multiple submatrices. S ame as
S plit with axis =1

Zeros Create and return a new matrix Initialization


filled with zeros

© 2000-2025, MetaQuotes Ltd.


1277 Matrix and Vector Methods

Matrix and Vector Types


Matrix and vector are special data types in MQL5 which enable linear algebra operations. The following
data types exist:
· matrix — a matrix containing double elements.

· matrixf — a matrix containing float elements.

· matrixc — a matrix containing complex elements.

· vector — a vector containing double elements.

· vectorf — a vector containing float elements.

· vectorc — a vector containing complex elements.

Template functions support notations like matrix<double>, matrix<float>, vector<double>,


vector<float> instead of the corresponding types.
Matrix and vector initialization methods

Function Action

Eye R eturn a matrix with ones on the diagonal and zeros elsewhere
Identity Create an identity matrix of the specified size
Ones Create and return a new matrix filled with ones
Zeros Create and return a new matrix filled with zeros
Full Create and return a new matrix filled with given value
Tri Construct a matrix with ones at and below the given diagonal and
zeros elsewhere

Init Initialize a matrix or a vector


Fill Fill an existing matrix or vector with the specified value

© 2000-2025, MetaQuotes Ltd.


1278 Matrix and Vector Methods

Enumeration for matrix and vector operations


This section describes the enumerations that are used in various matrix and vector methods.

ENUM_AVERAGE_MODE

S moothing type enumeration.

ID Description

AVERAGE_NONE No averaging. Results are provided for each label separately


AVERAGE_BINARY Label 1 result for binary classification
AVERAGE_MICR O Average error matrix result (confusion matrix)
AVERAGE_M ACR O Average result from the results of the error matrices of each
label
AVERAGE_WEIGH T ED W eighted average result

ENUM_VECTOR_NORM

Enumeration of vector norms for vector::Norm.

ID Description

VECTOR_NOR M _INF Inf norm


VECTOR_NOR M _MINUS_INF Minus Inf norm
VECTOR_NOR M _P Norm P

ENUM_MATRIX _NORM

Enumeration of matrix norms for matrix::Norm and for obtaining the matrix::Cond matrix condition
number.

ID Description

M ATRIX_NORM _FROBENIUS Frobenius norm


M ATRIX_NORM _S PECTRAL S pectral norm

M ATRIX_NORM _NUCLEAR Nuclear norm


M ATRIX_NORM _INF Inf norm
M ATRIX_NORM _P1 P1 norm

© 2000-2025, MetaQuotes Ltd.


1279 Matrix and Vector Methods

ID Description

M ATRIX_NORM _P2 P2 norm


M ATRIX_NORM _MINUS_INF Minus Inf norm
M ATRIX_NORM _MINUS_P1 Minus P1 norm
M ATRIX_NORM _MINUS_P2 Minus P2 norm

ENUM_VECTOR_CONVOLVE

Enumeration for convolution vector::Convolve and cross-correlation vector::Correlate.

ID Description

VECTOR_CONVOL VE_FULL Convolve full


VECTOR_CONVOL VE_SAM E Convolve same
VECTOR_CONVOL VE_VALID Convolve valid

ENUM_REGRESSION_METRIC

Enumeration of regression metrics for vector::RegressionMetric.

ID Description

REGRESS ION_M AE Mean Absolute Error


REGRESS ION_M SE Mean Squared Error
REGRESS ION_R M SE R oot Mean Squared Error

REGRESS ION_R2 R -Squared

REGRESS ION_M APE Mean Absolute Percentage Error


REGRESS ION_M S PE Mean Squared Percentage Error
REGRESS ION_R M S L E R oot Mean Squared Logarithmic Error

REGRESS ION_S M APE S ymmetric Mean Absolute Percentage Error

REGRESS ION_M AXE Maximal Absolute Error


REGRESS ION_M EDE Median Absolute Error
REGRESS ION_MPD Mean Poisson Deviance
REGRESS ION_M GD Mean Gamma Deviance
REGRESS ION_EXPV Explained Variance

© 2000-2025, MetaQuotes Ltd.


1280 Matrix and Vector Methods

ENUM_CLASSIFICATION_METRIC

Enumeration of metrics for classification problems.

ID Description

CLASS IFICATION_ACCURACY Model quality in terms of prediction accuracy for all


classes
CLASS IFICATION_AVERAGE_PRECIS ION Average model accuracy

CLASS IFICATION_BALANCED_ACCURACY Balanced prediction accuracy

CLASS IFICATION_F1 F1 score. Harmonic mean between the model precision


and recall
CLASS IFICATION_JACCARD Jaccard score

CLASS IFICATION_PRECIS ION Model accuracy in predicting true positives for the
target class
CLASS IFICATION_RECALL Model completeness
CLASS IFICATION_ROC_AUC Area under the error curve
CLASS IFICATION_TOP_K_ACCURACY Frequency of the correct label appearing at the top of
k predicted labels

ENUM_LOSS_FUNCTION

Enumeration for loss function calculations vector::Loss.

ID Description

LOSS_M SE R oot mean s quare error

LOSS_M AE Mean Absolute Error


LOSS_CCE Categorical Crossentropy
LOSS_BCE Binary Crossentropy

LOSS_M APE Mean Absolute Percentage Error


LOSS_M S LE Mean Squared Logarithmic Error
LOSS_KLD Kullback -Leibler Divergence

LOSS_COS INE Cosine similarity/proximity


LOSS_POISS ON Poisson
LOSS_HINGE H inge

© 2000-2025, MetaQuotes Ltd.


1281 Matrix and Vector Methods

ID Description

LOSS_S Q_HINGE Squared H inge

LOSS_CAT_HINGE Categorical Hinge


LOSS_LOG_COSH Logarithm of the Hyperbolic Cosine
LOSS_HUBER H uber

ENUM_ACTIVATION_FUNCTION

Enumeration for the activation function vector::Activation and for the activation function derivative
vector::Derivative.

ID Description

AF_EL U Exponential Linear Unit

AF_EXP Exponential

AF_GEL U Gaussian Error Linear Unit


AF_HARD_S IGMOID H ard S igmoid

AF_LINEAR Linear
AF_L REL U Leaky Rectified Linear Unit
AF_REL U REctified Linear Unit

AF_SEL U S caled Exponential Linear Unit

AF_S IGMOID S igmoid

AF_S OFTM AX S oftmax

AF_S OFTPL US S oftplus

AF_S OFT S IGN S oftsign

AF_SW ISH S wish

AF_T ANH The hyperbolic tangent function


AF_T REL U Thresholded Rectified Linear Unit

ENUM_SORT_MODE

Enumeration of sort types for the S ort function.

ID Description

S OR T _AS CENDING S ort ascending

© 2000-2025, MetaQuotes Ltd.


1282 Matrix and Vector Methods

ID Description

S OR T _DES CENDING S ort descending

ENUM_MATRIX _AX IS

Enumeration for specifying the axis in all statistical functions for matrices.

ID Description

AXIS_NONE The axis is not specified. Calculation is performed over all


matrix elements, as if it were a vector (see the Flat method).
AXIS_H ORZ H orizontal axis

AXIS_VER T Vertical axis

© 2000-2025, MetaQuotes Ltd.


1283 Matrix and Vector Methods

Initialization
There are several ways to declare and initialize matrices and vectors.

Function Action

Assign Copies a matrix, vector or array with auto cast


CopyIndicatorBuffer Get the data of the specified indicator buffer in the specified
quantity to a vector

CopyRates Getsthe historical series of the M qlRates structure of the specified


symbol-period in the specified amount into a matrix or vector
CopyTicks Get tick s from an M qlTick structure into a matrix or a vector
CopyTicks Range Get tick sfrom an M qlTick structure into a matrix or a vector within
the specified date range
Eye R eturn a matrix with ones on the diagonal and zeros elsewhere
Identity Create an identity matrix of the specified size
Ones Create and return a new matrix filled with ones
Zeros Create and return a new matrix filled with zeros
Full Create and return a new matrix filled with given value
Tri Construct a matrix with ones at and below the given diagonal and
zeros elsewhere

Init Initialize a matrix or a vector


Fill Fill an existing matrix or vector with the specified value

Declaration without specifying the size (no memory allocation for the data):
matrix matrix_a; // double type matrix
matrix<double> matrix_a1; // another way to declare a double matrix; can be used in templates
matrixf matrix_a2; // float matrix
matrix<float> matrix_a3; // float matrix
vector vector_a; // double vector
vector<double> vector_a1;
vectorf vector_a2; // float vector
vector<float> vector_a3;

Declaration with the specified size (with memory allocation for the data, but without any
initialization):
matrix matrix_a(128,128); // the parameters can be either constants
matrix<double> matrix_a1(InpRows,InpCols); // or variables
matrixf matrix_a2(1,128); // analog of a horizontal vector
matrix<float> matrix_a3(InpRows,1); // analog of a vertical vector

© 2000-2025, MetaQuotes Ltd.


1284 Matrix and Vector Methods

vector vector_a(256);
vector<double> vector_a1(InpSize);
vectorf vector_a2(SomeFunc()); // function SomeFunc returns a number of type ulong,
vector<float> vector_a3(InpSize+16); // expression can be used as a parameter

Declaration with initialization (matrix and vector sizes are determined by the initializing
sequence):
matrix matrix_a={{0.1,0.2,0.3},{0.4,0.5,0.6}};
matrix<double> matrix_a1=matrix_a; // must be matrices of the same type
matrixf matrix_a2={{1,0,0},{0,1,0},{0,0,1}};
matrix<float> matrix_a3={{1,2},{3,4}};
vector vector_a={-5,-4,-3,-2,-1,0,1,2,3,4,5};
vector<double> vector_a1={1,5,2.4,3.3};
vectorf vector_a2={0,1,2,3};
vector<float> vector_a3=vector_a2; // must be vectors of the same type

Declaration with initialization:


template<typename T>
void MatrixArange(matrix<T> &mat,T value=0.0,T step=1.0)
{
for(ulong i=0; i<mat.Rows(); i++)
{
for(ulong j=0; j<mat.Cols(); j++,value+=step)
mat[i][j]=value;
}
}
template<typename T>
void VectorArange(vector<T> &vec,T value=0.0,T step=1.0)
{
for(ulong i=0; i<vec.Size(); i++,value+=step)
vec[i]=value;
}
...

matrix matrix_a(size_m,size_k,MatrixArange,-M_PI,0.1); // first an uninitialized matrix sized si


matrixf matrix_a1(10,20,MatrixArange); // after creating the matrix, function Ma
vector vector_a(size,VectorArange,-10.0); // after creating the vector, function Ve
vectorf vector_a1(128,VectorArange);

Please note that the matrix or vector dimensions can be changed, since the memory for data is always
dynamic.

Static methods

© 2000-2025, MetaQuotes Ltd.


1285 Matrix and Vector Methods

S tatic methods for creating matrices and vectors of the specified size, initialized in a certain way:
matrix matrix_a =matrix::Eye(4,5,1);
matrix<double> matrix_a1=matrix::Full(3,4,M_PI);
matrixf matrix_a2=matrixf::Identity(5,5);
matrixf<float> matrix_a3=matrixf::Ones(5,5);
matrix matrix_a4=matrix::Tri(4,5,-1);
vector vector_a =vector::Ones(256);
vectorf vector_a1=vector<float>::Zeros(16);
vector<float> vector_a2=vectorf::Full(128,float_value);

Methods for initializing already created matrices and vectors:


matrix matrix_a;
matrix_a.Init(size_m,size_k,MatrixArange,-M_PI,0.1);
matrixf matrix_a1(3,4);
matrix_a1.Init(10,20,MatrixArange);
vector vector_a;
vector_a.Init(128,VectorArange);
vectorf vector_a1(10);
vector_a1.Init(vector_size,VectorArange,start_value,step);

matrix_a.Fill(double_value);
vector_a1.Fill(FLT_MIN);
matrix_a1.Identity();

© 2000-2025, MetaQuotes Ltd.


1286 Matrix and Vector Methods

Assign
Copies a matrix, vector or array with auto cast.
bool matrix::Assign(
const matrix<T> &mat // copied matrix
);
bool matrix::Assign(
const void &array[] // copied array
);
bool vector::Assign(
const vector<T> &vec // copied vector
);
bool vector::Assign(
const void &array[] // copied array
);

Parameters
m, v or array
[in] The matrix, vector or array the values are copied from.

Return Value

R eturns true if successful, otherwise — false.


Note

Unlik e Copy,the Assign method allows copying arrays as well. In this case, the auto cast takes place,
while the resulting matrix or vector adjusts to the size of the copied array.

Example:

//--- copy the matrices


matrix a= {{2, 2}, {3, 3}, {4, 4}};
matrix b=a+2;
matrix c;
Print("matrix a \n", a);
Print("matrix b \n", b);
c.Assign(b);
Print("matrix c \n", a);

//--- copy the array to the matrix


matrix double_matrix=matrix::Full(2,10,3.14);
Print("double_matrix before Assign() \n", double_matrix);
int int_arr[5][5]= {{1, 2}, {3, 4}, {5, 6}};
Print("int_arr: ");
ArrayPrint(int_arr);
double_matrix.Assign(int_arr);

© 2000-2025, MetaQuotes Ltd.


1287 Matrix and Vector Methods

Print("double_matrix after Assign(int_arr) \n", double_matrix);


/*
matrix a
[[2,2]
[3,3]
[4,4]]
matrix b
[[4,4]
[5,5]
[6,6]]
matrix c
[[2,2]
[3,3]
[4,4]]

double_matrix before Assign()


[[3.14,3.14,3.14,3.14,3.14,3.14,3.14,3.14,3.14,3.14]
[3.14,3.14,3.14,3.14,3.14,3.14,3.14,3.14,3.14,3.14]]

int_arr:
[,0][,1][,2][,3][,4]
[0,] 1 2 0 0 0
[1,] 3 4 0 0 0
[2,] 5 6 0 0 0
[3,] 0 0 0 0 0
[4,] 0 0 0 0 0

double_matrix after Assign(int_arr)


[[1,2,0,0,0]
[3,4,0,0,0]
[5,6,0,0,0]
[0,0,0,0,0]
[0,0,0,0,0]]

*/

See also
Copy

© 2000-2025, MetaQuotes Ltd.


1288 Matrix and Vector Methods

CopyIndicatorBuffer
Get the data of the specified indicator buffer in the specified quantity to a vector.
The data will be copied into the vector locating the oldest element at the beginning of the physical
memory allocated for the vector. There are three function options.
Access by the initial position and the number of required elements
bool vector::CopyIndicatorBuffer(
long indicator_handle, // indicator handle
ulong buffer_index, // indicator buffer number
ulong start_pos, // starting position to copy
ulong count // number of elements to copy
);

Access by the start date and the number of required elements


bool vector::CopyIndicatorBuffer(
long indicator_handle, // indicator handle
ulong buffer_index, // indicator buffer number
datetime start_time, // from which date to copy
ulong count // number of elements to copy
);

Access by the initial and final dates of the required time interval
bool vector::CopyIndicatorBuffer(
long indicator_handle, // indicator handle
ulong buffer_index, // indicator buffer number
datetime start_time, // from which date to copy
datetime stop_time // up to which date to copy
);

Parameters
indicator_handle
[in] The indicator handle obtained by the relevant indicator function.
buffer_index
[in] The number of the indicator buffer.
start_pos
[in] The number of the first copied element index.
count
[in] The number of copied elements.
start_time
[in] Bar time corresponding to the first element.
stop_time
[in] Bar time corresponding to the last element.

© 2000-2025, MetaQuotes Ltd.


1289 Matrix and Vector Methods

Return Value

The function returns 'true' on success or 'false' if an error occurs.


Note

The elements of the copied data (the indicator buffer with index buffer_index) are counted down
from the present to the past, and thus the starting position equal to 0 means the current bar (the
indicator value for the current bar).
W hen copying an unknown amount of data, you should declare a vector without specifying a size
(without allocating memory for the data), since the CopyBuffer() function tries to distribute the size
of the receiving vector to the size of the copied data.
W hen partialcopying of the indicator values is needed, you should use an intermediate vector into
which the required quantity is copied. From this intermediate vector, you can copy the required
number of values member by member, to the required places of the receiving vector.
If you are copying a predetermined amount of data, it is recommended to pre-declare a vector and
specify its size to avoid unnecessary memory reallocation.
W hen requesting data from an indicator, the function immediately returns false if requested
timeseries have not yet been constructed or they need to be downloaded from the server, while it
initiates loading/constructing.
W hen requesting data from an EA or a script, download from the server is initiated if the terminal
does not have the appropriate data locally, or construction of the necessary timeseries starts if the
data can be constructed from the local history but the required timeframes are not ready yet. The
function returns the amount that will be ready by the time the timeout expires.

See also

CopyBuffer

© 2000-2025, MetaQuotes Ltd.


1290 Matrix and Vector Methods

CopyRates
Gets the historical series of the M qlRates structure of the specified symbol-period in the specified
amount into a matrix or vector. Elements are counted down from the present to the past, which means
that the starting position equal to 0 means the current bar.
The data is copied so that the oldest element is placed at the beginning of the matrix/vector. There
are three function options.
Access by the initial position and the number of required elements
bool matrix::CopyRates(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ulong rates_mask, // combination of flags to specify the requested series
ulong start, // index of the initial bar copying starts from
ulong count // how many to copy
);

Access by the initial date and the number of required elements


bool matrix::CopyRates(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ulong rates_mask, // combination of flags to specify the requested series
datetime from, // start date
ulong count // how many to copy
);

Access by the initial and final dates of the required time interval
bool matrix::CopyRates(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ulong rates_mask, // combination of flags to specify the requested series
datetime from, // start date
datetime to // end date
);

Vector Methods
Access by the initial position and the number of required elements
bool vector::CopyRates(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ulong rates_mask, // combination of flags to specify the requested series
ulong start, // index of the initial bar copying starts from
ulong count // how many to copy
);

Access by the initial date and the number of required elements

© 2000-2025, MetaQuotes Ltd.


1291 Matrix and Vector Methods

bool vector::CopyRates(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ulong rates_mask, // combination of flags to specify the requested series
datetime from, // start date
ulong count // how many to copy
);

Access by the initial and final dates of the required time interval
bool vector::CopyRates(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // period
ulong rates_mask, // combination of flags to specify the requested series
datetime from, // start date
datetime to // end date
);

Parameters
symbol
[in] S ymbol.

period
[in] Period.
rates_mask
[in] The ENUM _COPY_RATES enumeration combination of flags specifying the type of requested
series. W hen copying to a vector, only one value from the ENUM _COPY_RATES enumeration can
be specified, otherwise an error occurs.
start
[in] First copied element index.

count
[in] Number of copied elements.
from
[in] Bar time corresponding to the first element.
to
[in] Bar time corresponding to the last element.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

If the interval of the requested data is completely outside the available data on the server, then the
function returns false. If the data outside TERMINAL_M AXBARS (maximum number of bars on the
chart) is requested, the function also returns false.

© 2000-2025, MetaQuotes Ltd.


1292 Matrix and Vector Methods

W hen requesting data from an EA or a script, download from the server is initiated if the terminal
does not have the appropriate data locally, or construction of the necessary timeseries starts if the
data can be constructed from the local history but they are not ready yet. The function returns the
amount that will be ready by the time the timeout expires, however the history download continues,
and the function returns more data during the next similar request.
W hen requesting data by the start date and the number of required items, only data whose date is
less than (before) or equal to the specified one is returned. The interval is set and considered up to
a second. In other words, the opening date of any bar the value is returned for (volume, spread,
Open, High, Low, Close or Time) is always equal to or less than the specified one.
W hen requesting data in a given date range, only data that falls within the requested interval is
returned. The interval is set and considered up to a second. In other words, the opening time of any
bar the value is returned for (volume, spread, indicator buffer value, Open, High, Low, Close or
Time) is always located in the requested interval.
For example, if the current day of the week is S aturday, the function returns 0 when attempting to
copy data on the weekly timeframe by setting start_time=Last_Tuesday and stop_time=Last_Friday
because the open time on the weekly timeframe always falls on S unday, but not a single weekly bar
falls within the specified range.
If you need to get the value corresponding to the current incomplete bar, then you can use the first
call form indicating start_pos =0 and count=1.

ENUM_COPY _RATES

The ENUM _COPY_RATES enumeration contains the flags to specify the type of data to be passed to the
matrix or array. The flag combination allows getting several series from the history in one request.
The order of the rows in the matrix will correspond to the order of the values in the
ENUM _COPY_RAT ES enumeration. In other words, the row with H igh data will always be higher in the
matrix than the row with Low data.
ID Value Description

COPY_RATES_OPEN 1 Open price series


COPY_RATES_HIGH 2 H igh price series

COPY_RATES_LOW 4 Low price series


COPY_RATES_CLOSE 8 Close price series
COPY_RATES_TIM E 16 Time series (bar open time)

Getting time in float of the vector and the


matrix (vectord and matrixf) causes losses
of ~100 seconds since float accuracy is
severely limited and integers greater than
1<<24 cannot be accurately represented in
float.
COPY_RATES_VOLUM E_TICK 32 Tick Volumes
COPY_RATES_VOLUM E_REAL 64 Trade Volumes

© 2000-2025, MetaQuotes Ltd.


1293 Matrix and Vector Methods

ID Value Description

COPY_RATES_S PREAD 128 S preads

Combination

COPY_RATES_OHLC 15 Open, High, Low and Close series


COPY_RATES_OHLCT 31 Open, High, Low, Close and Time series
Data arrangement

COPY_RATES_VERTICAL 32768 S eriesare copied into the matrix along the


vertical axis. The received series values will
be arranged vertically in the matrix, i.e.,
the oldest data will be in the first row, while
the most recent data will be in the last
matrix row.

W ithdefault copying, series are added into


a matrix along the horizontal axis.

The flag is only applicable when copying to a


matrix.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get quotes to the matrix
matrix matrix_rates;
if(matrix_rates.CopyRates(Symbol(), PERIOD_CURRENT, COPY_RATES_OHLCT, 1, 10))
Print("matrix rates: \n", matrix_rates);
else
Print("matrix_rates.CopyRates failed. Error ", GetLastError());
//--- check
MqlRates mql_rates[];
if(CopyRates(Symbol(), PERIOD_CURRENT, 1, 10, mql_rates)>0)
{
Print("mql_rates array:");
ArrayPrint(mql_rates);
}
else
Print("CopyRates(Symbol(), PERIOD_CURRENT,1, 10, mql_rates). Error ", GetLastError());
//--- get quotes into the vector = invalid call
vector vector_rates;
if(vector_rates.CopyRates(Symbol(), PERIOD_CURRENT, COPY_RATES_OHLC, 1, 15))
Print("vector_rates COPY_RATES_OHLC: \n", vector_rates);
else

© 2000-2025, MetaQuotes Ltd.


1294 Matrix and Vector Methods

Print("vector_rates.CopyRates COPY_RATES_OHLC failed. Error ", GetLastError());


//--- get close prices into the vector
if(vector_rates.CopyRates(Symbol(), PERIOD_CURRENT, COPY_RATES_CLOSE, 1, 15))
Print("vector_rates COPY_RATES_CLOSE: \n", vector_rates);
else
Print("vector_rates.CopyRates failed. Error ", GetLastError());
};
/*
matrix rates:
[[0.99686,0.99638,0.99588,0.99441,0.99464,0.99594,0.99698,0.99758,0.99581,0.9952800000000001]
[0.99708,0.99643,0.99591,0.9955000000000001,0.99652,0.99795,0.99865,0.99764,0.99604,0.9957]
[0.9961100000000001,0.99491,0.99426,0.99441,0.99448,0.99494,0.9964499999999999,0.99472,0.9936,0
[0.99641,0.99588,0.99441,0.99464,0.99594,0.99697,0.99758,0.99581,0.9952800000000001,0.99259]
[1662436800,1662440400,1662444000,1662447600,1662451200,1662454800,1662458400,1662462000,166246
mql_rates array:
[time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume]
[0] 2022.09.06 04:00:00 0.99686 0.99708 0.99611 0.99641 4463 0 0
[1] 2022.09.06 05:00:00 0.99638 0.99643 0.99491 0.99588 4519 0 0
[2] 2022.09.06 06:00:00 0.99588 0.99591 0.99426 0.99441 3060 0 0
[3] 2022.09.06 07:00:00 0.99441 0.99550 0.99441 0.99464 3867 0 0
[4] 2022.09.06 08:00:00 0.99464 0.99652 0.99448 0.99594 5280 0 0
[5] 2022.09.06 09:00:00 0.99594 0.99795 0.99494 0.99697 7227 0 0
[6] 2022.09.06 10:00:00 0.99698 0.99865 0.99645 0.99758 10130 0 0
[7] 2022.09.06 11:00:00 0.99758 0.99764 0.99472 0.99581 7012 0 0
[8] 2022.09.06 12:00:00 0.99581 0.99604 0.99360 0.99528 6166 0 0
[9] 2022.09.06 13:00:00 0.99528 0.99570 0.99220 0.99259 6950 0 0
vector_rates.CopyRates COPY_RATES_OHLC failed. Error 4003
vector_rates COPY_RATES_CLOSE:
[0.9931,0.99293,0.99417,0.99504,0.9968399999999999,0.99641,0.99588,0.99441,0.99464,0.99594,0.996
*/

See also
Access to Timeseries and Indicators, CopyRates

© 2000-2025, MetaQuotes Ltd.


1295 Matrix and Vector Methods

CopyTicks
Get tick s from an M qlTick structure into a matrix or a vector. Elements are counted from the past to
the present, which means that the tick with index 0 is the oldest one. To analyze a tick, check the
flags field which shows what exactly has changed in the tick .

bool matrix::CopyTicks(
string symbol, // symbol name
ulong flags, // flag indicating the type of ticks to be received
ulong from_msc, // time from which ticks are requested
ulong count // number of ticks to be received
);

Vector Method
bool vector::CopyTicks(
string symbol, // symbol name
ulong flags, // flag indicating the type of ticks to be received
ulong from_msc, // time from which ticks are requested
ulong count // number of ticks to be received
);

Parameters
symbol
[in] S ymbol.

flags
[in] A combination of flags from the ENUM _COPY_TICKS enumeration indicating the contents of
the requested data. W hen copying to a vector, you can specify only one value from the
ENUM _COPY_TICKS enumeration, otherwise an error will occur.

from_msc
[in] Time starting from which tick s are requested. Time is specified in milliseconds since
01/01/1970. If from_msc=0, the last number of tick s equal to 'count' are returned.

count
[in] The number of requested ticks. If parameters 'from_msc' and 'count' are not specified, all
available ticks, but no more than 2000, will be written.

Return Value

R eturns true on success or false if error occurs.


Note

The first call of CopyTicks() initiates synchronization of the relevant symbol's tick database stored
on the hard drive. If the local database does not provide all the requested ticks, then missing ticks
will be automatically downloaded from the trade server. Ticks from from_msc specified in
CopyTicks() to the current moment will be synchronized. After that, all ticks arriving for this symbol
will be added to the tick database thus keeping it in the synchronized state.

© 2000-2025, MetaQuotes Ltd.


1296 Matrix and Vector Methods

If from_msc and count parameters are not specified, all available ticks, but no more than 2000, will
be written to the matrix/vector.
In indicators, the CopyTicks() method returns the result immediately: W hen called from an
indicator, CopyTick() immediately returns all available ticks of a symbol and launches
synchronization of the tick database if available data is not enough. All indicators on the same
symbol operate in one common thread, so the indicator cannot wait for the completion of
synchronization. After synchronization, CopyTicks() will return all requested ticks during the next
call. In indicators, the OnCalculate() function is called after the arrival of each tick.
In Expert Advisors and scripts, CopyTicks() can wait for the result for 45 seconds: as distinct
from indicators, every Expert Advisor or script operates in a separate thread, and therefore can
wait up to 45 seconds for the synchronization to complete. If the required amount of ticks fails to be
synchronized during this time, CopyTicks() will return available ticks by timeout and will continue
synchronization. OnTick() in Expert Advisors is not a handler of every tick, while it only notifies the
Expert Advisor about changes in the mark et. This can be a batch of changes : the terminal can
simultaneously receive multiple ticks, while OnTick() will be called only once, to notify the Expert
Advisor about the latest mark et state.

Rate of data return: the terminal stores 4096 last tick s for each instrument in the fast access cache
(65536 ticks for symbols with the Market Depth running). Requests concerning this data are
executed the fastest. If requested ticks for the current trading session are beyond the cache,
CopyTicks() calls the ticks stored in the terminal memory. These requests require more time to
complete. The slowest requests are those requesting ticks for other days, since the data is read
from the drive in this case.

ENUM_COPY _TICKS

The ENUM _COPY_TICKS enumeration contains the flags to specify the type of data to be passed to the
matrix or array. The flag combination allows getting several series from the history in one request.
The order of the rows in the matrix will correspond to the order of the values in the
ENUM _COPY_TICKS enumeration. In other words, the row with H igh data will always be higher in the
matrix than the row with Low data.
ID Value Description

COPY_TICKS_INFO 1 All tick s

COPY_TICKS_TRADE 2 Ticks containing Bid and/or As k price


changes
COPY_TICKS_ALL 3 Ticks containing Last and/or Volume price
changes
COPY_TICKS_TIM E_M S 1<<8 Tick time in milliseconds
COPY_TICKS_BID 1<<9 Bid price

COPY_TICKS_ASK 1<<10 As k price


COPY_TICKS_LAS T 1<<11 Last price (last deal price)
COPY_TICKS_VOLUM E 1<<12 Last price Volume

© 2000-2025, MetaQuotes Ltd.


1297 Matrix and Vector Methods

ID Value Description

COPY_TICKS_FLAGS 1<<13 Tick Flags


Data arrangement

COPY_TICKS_VERTICAL 1<<15 Ticks are copied into the matrix along the
vertical axis. The received ticks will be
arranged vertically in the matrix, i.e., the
oldest ticks will be in the first row, while the
most recent ticks will be in the last matrix
row.

W ith default copying, tick s are added into a


matrix along the horizontal axis.

The flag is only applicable when copying to a


matrix.
Analyze the tickflags to find out which data has changed:
· TICK_FLAG_BID — the tick has changed the bid price
· TICK_FLAG_ASK — the tick has changed the as k price
· TICK_FLAG_LAS T — the tick has changed the last deal price
· TICK_FLAG_VOLUM E — the tick has changed the volume
· TICK_FLAG_BUY — the tick is a result of a buy deal
· TICK_FLAG_SELL — the tick is a result of a sell deal

See also
Access to Timeseries and Indicators, CopyTicks

© 2000-2025, MetaQuotes Ltd.


1298 Matrix and Vector Methods

CopyTicksRange
Get tick s from an M qlTick structure into a matrix or a vector within the specified date range.
Elements are counted from the past to the present, which means that the tick with index 0 is the
oldest one. To analyze a tick, check the flags field which shows what exactly has changed in the tick.
bool matrix::CopyTicksRange(
string symbol, // symbol name
ulong flags, // flag indicating the type of ticks to be received
ulong from_msc, // time from which ticks are requested
ulong to_msc // time up to which ticks are requested
);

Vector Method
bool vector::CopyTicksRange(
string symbol, // symbol name
ulong flags, // flag indicating the type of ticks to be received
ulong from_msc, // time from which ticks are requested
ulong to_msc // time up to which ticks are requested
);

Parameters
symbol
[in] S ymbol.

flags
[in] A combination of flags from the ENUM _COPY_TICKS enumeration indicating the contents of
the requested data. W hen copying to a vector, you can specify only one value from the
ENUM _COPY_TICKS enumeration, otherwise an error will occur.

from_msc
[in] Time starting from which tick s are requested. Time is specified in milliseconds since
01/01/1970. If the 'from_msc' parameter is not specified, tick s from the beginning of the history
are returned. Ticks with the time >= from_msc will be returned.
to_msc
[in] Time up to which tick s are requested. Time is specified in milliseconds since 01/01/1970.
Ticks with the time <= to_msc are returned. If the to_msc parameter is not specified, all ticks up
to the history end are returned.

Return Value

R eturns true on success or false if error occurs. GetLastError() can return the following errors :
· ERR_H IS TORY_TIM EOUT — timeout for tick synchronization has expired, the function has returned
all it had.
· ERR_H IS TORY_S M ALL _BUFFER — static buffer is too small. Only the amount the array can store
has been returned.
· ERR_NOT _ENOUGH_M EMORY — not enough memory to receive historical data from the specified
range into a dynamic tick array. Failed to allocate enough memory for the tick array.

© 2000-2025, MetaQuotes Ltd.


1299 Matrix and Vector Methods

Analyze the tickflags to find out which data has changed:


· TICK_FLAG_BID — the tick has changed the bid price
· TICK_FLAG_ASK — the tick has changed the as k price
· TICK_FLAG_LAS T — the tick has changed the last deal price
· TICK_FLAG_VOLUM E — the tick has changed the volume
· TICK_FLAG_BUY — the tick is a result of a buy deal
· TICK_FLAG_SELL — the tick is a result of a sell deal

Note

The CopyTicks Range() method is used to request ticks from exactly the specified range. For
example, ticks for a specific day in history. CopyTicks() allows specifying only the start date, for
example, to receive all ticks from the beginning of the month up to now.

See also
Access to Timeseries and Indicators, CopyTicks Range

© 2000-2025, MetaQuotes Ltd.


1300 Matrix and Vector Methods

Eye
A static function. Constructs a matrix having a specified size with ones on the main diagonal and
zeros elsewhere. R eturns a matrix with ones on the diagonal and zeros elsewhere.

static matrix matrix::Eye(


const ulong rows, // number of rows
const ulong cols, // number of columns
const int ndiag=0 // index of the diagonal
);

Parameters
rows
[in] Number of rows in the output.
cols
[in] Number of columns in the output.
ndiag=0
[in] Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to
an upper diagonal, and a negative value to a lower diagonal.

Return Value

A matrix where all elements are equal to zero, except for the k-th diagonal, whose values are equal
to one.

MQL5 example:

matrix eye=matrix::Eye(3, 3);


Print("eye = \n", eye);

eye=matrix::Eye(4, 4,1);
Print("eye = \n", eye);
/*
eye =
[[1,0,0]
[0,1,0]
[0,0,1]]
eye =
[[0,1,0,0]
[0,0,1,0]
[0,0,0,1]
[0,0,0,0]]
*/

Python example:
np.eye(3, dtype=int)

© 2000-2025, MetaQuotes Ltd.


1301 Matrix and Vector Methods

array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])

np.eye(4, k=1)
array([[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.],
[0., 0., 0., 0.]])

© 2000-2025, MetaQuotes Ltd.


1302 Matrix and Vector Methods

Identity
It is a static function which creates an identity matrix of the specified size (not necessarily s quare).
An identity matrix contains ones on the main diagonal and zeros elsewhere. The main diagonal
consists of the matrix elements having equal row and column indexes, such as [0,0],[1,1],[2,2] etc.
Creates a new identity matrix.
There is also the method Identity that transforms an already existing matrix into an identity one.
static matrix matrix::Identity(
const ulong rows, // number of rows
const ulong cols, // number of columns
);

void matrix::Identity();

Parameters
rows
[in] Number of rows (and columns) in n x n matrix.

Return Value

R eturn the identity matrix. The identity matrix is a s quare matrix with ones on the main diagonal.

MQL5 example:

matrix identity=matrix::Identity(3,3);
Print("identity = \n", identity);
/*
identity =
[[1,0,0]
[0,1,0]
[0,0,1]]
*/
matrix identity2(3,5);
identity2.Identity();
Print("identity2 = \n", identity2);
/*
identity2 =
[[1,0,0,0,0]
[0,1,0,0,0]
[0,0,1,0,0]]
*/

Python example:

np.identity(3)
array([[1., 0., 0.],

© 2000-2025, MetaQuotes Ltd.


1303 Matrix and Vector Methods

[0., 1., 0.],


[0., 0., 1.]])

© 2000-2025, MetaQuotes Ltd.


1304 Matrix and Vector Methods

Ones
This is a static function that creates and returns a new matrix filled with ones.
static matrix matrix::Ones(
const ulong rows, // number of rows
const ulong cols // number of columns
);

static vector vector::Ones(


const ulong size, // vector size
);

Parameters
rows
[in] Number of rows.
cols
[in] Number of columns.

Return Value

A new matrix of given rows and columns, filled with ones.

MQL5 example:

matrix ones=matrix::Ones(4, 4);


Print("ones = \n", ones);
/*
ones =
[[1,1,1,1]
[1,1,1,1]
[1,1,1,1]
[1,1,1,1]]
*/

Python example:

np.ones((4, 1))
array([[1.],
[1.]])

© 2000-2025, MetaQuotes Ltd.


1305 Matrix and Vector Methods

Zeros
This is a static function that creates and returns a new matrix filled with zeros.
static matrix matrix::Zeros(
const ulong rows, // number of rows
const ulong cols // number of columns
);

static vector vector::Zeros(


const ulong size, // vector size
);

Parameters
rows
[in] Number of rows.
cols
[in] Number of columns.

Return Value

A new matrix of given rows and columns, filled with zeros.


MQL5 example:

matrix zeros=matrix::Zeros(3, 4);


Print("zeros = \n", zeros);
/*
zeros =
[[0,0,0,0]
[0,0,0,0]
[0,0,0,0]]
*/

Python example:

np.zeros((2, 1))
array([[ 0.],
[ 0.]])

© 2000-2025, MetaQuotes Ltd.


1306 Matrix and Vector Methods

Full
The static function creates and returns a new matrix filled with given value.
static matrix matrix::Full(
const ulong rows, // number or rows
const ulong cols, // number of columns
const double value // value to fill
);

static vector vector::Full(


const ulong size, // vector size
const double value // value to fill
);

Parameters
rows
[in] Number of rows.
cols
[in] Number of columns.
value
[in] Value to fill all the matrix elements.

Return Value

R eturn a new matrix of given rows and columns, filled with specified value.
MQL5 example:

matrix full=matrix::Full(3,4,10);
Print("full = \n", full);
/*
full =
[[10,10,10,10]
[10,10,10,10]
[10,10,10,10]]
*/

Example

np.full((2, 2), 10)


array([[10, 10],
[10, 10]])

© 2000-2025, MetaQuotes Ltd.


1307 Matrix and Vector Methods

Tri
This is a static function Construct a matrix with ones at and below the given diagonal and zeros
elsewhere.
static matrix matrix::Tri(
const ulong rows, // number of rows
const ulong cols, // number of columns
const int ndiag=0 // number of diagonal
);

Parameters
rows
[in] Number of rows in the array.
cols
[in] Number of columns in the array.
ndiag=0
[in] The sub-diagonal at and below which the array is filled. k = 0 is the main diagonal, while k <0
is below it, and k > 0 is above. The default is 0.

Return Value

Array with its lower triangle filled with ones and zero elsewhere.
MQL5 example:

matrix matrix_a=matrix::Tri(3,4,1);
Print("Tri(3,4,1)\n",matrix_a);
matrix_a=matrix::Tri(4,3,-1);
Print("Tri(4,3,-1)\n",matrix_a);

/*
Tri(3,4,1)
[[1,1,0,0]
[1,1,1,0]
[1,1,1,1]]
Tri(4,3,-1)
[[0,0,0]
[1,0,0]
[1,1,0]
[1,1,1]]
*/

Example

np.tri(3, 5, 2, dtype=int)
array([[1, 1, 1, 0, 0],
[1, 1, 1, 1, 0],
[1, 1, 1, 1, 1]])

© 2000-2025, MetaQuotes Ltd.


1308 Matrix and Vector Methods

Init
Initialize a matrix or a vector.
void matrix::Init(
const ulong rows, // number of rows
const ulong cols, // number of columns
func_name init_func=NULL, // init function placed in some scope or static method of class
... parameters
);

void vector::Init(
const ulong size, // vector size
func_name init_func=NULL, // init function placed in some scope or static method of class
... parameters
);

Parameters
rows
[in] Number of rows.
cols
[in] Number of columns.
func_name
[in] Initializing function.
...
[in] Parameters of the initializing function.

Return Value

No return value.

Example

template<typename T>
void MatrixArange(matrix<T> &mat,T value=0.0,T step=1.0)
{
for(ulong i=0; i<mat.Rows(); i++)
{
for(ulong j=0; j<mat.Cols(); j++,value+=step)
mat[i][j]=value;
}
}
template<typename T>
void VectorArange(vector<T> &vec,T value=0.0,T step=1.0)
{

© 2000-2025, MetaQuotes Ltd.


1309 Matrix and Vector Methods

for(ulong i=0; i<vec.Size(); i++,value+=step)


vec[i]=value;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int size_m=3, size_k=4;
matrix m(size_m,size_k,MatrixArange,-2.,0.1); // first an uninitialized matrix sized size_m x si
Print("matrix m \n",m); // then function MatrixArange with the parameters
matrixf m_float(5,5,MatrixArange,-2.f,0.1f); // after a matrix of float type is created, the Ma
Print("matrix m_float \n",m_float);
vector v(size_k,VectorArange,-10.0); // after a vector is created, VectorArange with on
Print("vector v \n",v);
/*
matrix m
[[-2,-1.9,-1.8,-1.7]
[-1.6,-1.5,-1.399999999999999,-1.299999999999999]
[-1.199999999999999,-1.099999999999999,-0.9999999999999992,-0.8999999999999992]]
matrix m_float
[[-2,-1.9,-1.8,-1.6999999,-1.5999999]
[-1.4999999,-1.3999999,-1.2999998,-1.1999998,-1.0999998]
[-0.99999976,-0.89999974,-0.79999971,-0.69999969,-0.59999967]
[-0.49999967,-0.39999968,-0.29999968,-0.19999969,-0.099999689]
[3.1292439e-07,0.10000031,0.20000032,0.30000031,0.4000003]]
vector v
[-10,-9,-8,-7]
*/
}

© 2000-2025, MetaQuotes Ltd.


1310 Matrix and Vector Methods

Fill
Fill an existing matrix or vector with the specified value.
void matrix::Fill(
const double value // value to fill
);

void vector::Fill(
const double value // value to fill
);

Parameters
value
[in] Value to fill all the matrix elements.

Return Value

No return value. The matrix is filled in place with the specified value.

Example

matrix matrix_a(2,2);
matrix_a.Fill(10);
Print("matrix_a\n",matrix_a);

/*
matrix_a
[[10,10]
[10,10]]
*/

© 2000-2025, MetaQuotes Ltd.


1311 Matrix and Vector Methods

Matrix and vector manipulations


These are methods for basic matrix operations : filling, copying, getting a part of a matrix,
transposing, splitting and sorting.
There are also several methods for operations with matrix rows and columns.

Function Action

H as Nan R eturn the number of NaN values in a matrix/vector


Transpose R everse or permute the axes of a matrix; returns the modified
matrix
TransposeConjugate Transposing a complex matrix with conjugation. Reverse or permute
the axes of a matrix by changing a sign of an imaginary part of a
complex number, return the modified matrix
TriL R eturn a copy of a matrix with elements above the k-th diagonal
zeroed. Lower triangular matrix

TriU R eturn a copy of a matrix with elements below the k-th diagonal
zeroed. Upper triangular matrix

Diag Extract a diagonal or construct a diagonal matrix


R ow R eturn a row vector. W rite a vector to the specified row
Col R eturn a column vector. W rite a vector to the specified column
Copy R eturn a copy of the given matrix/vector
Compare Compare the elements of two matrices /vectors with the specified
precision
CompareByDigits Compare the elements of two matrices /vectors up to significant
digits
CompareEqual Perform an absolute comparison of two matrices by unfolding
successive rows into one-dimensional vectors
Flat Allows addressing a matrix element through one index instead of two
Clip Limit the elements of a matrix/vector to a specified range of valid
values
R eshape Change the shape of a matrix without changing its data
R esize R eturn a new matrix with a changed shape and size
S wapR ows S wap rows in a matrix
S wapCols S wap columns in a matrix
S plit S plit a matrix into multiple submatrices
H split S plit
a matrix horizontally into multiple submatrices. S ame as S plit
with axis =0

© 2000-2025, MetaQuotes Ltd.


1312 Matrix and Vector Methods

Function Action

Vsplit S plit a matrix vertically into multiple submatrices. S ame as S plit with
axis =1
Arg S ort Indirectly sort a matrix or vector.
S ort S ort a matrix or vector in place.

© 2000-2025, MetaQuotes Ltd.


1313 Matrix and Vector Methods

HasNan
R eturn the number of NaN values in a matrix/vector.
ulong vector::HasNan();

ulong matrix::HasNan();

Return Value

The number of matrix/vector elements that contain a NaN value.

Note

W hen comparing the appropriate pair of elements having NaN values, the Compare and
CompareByDigits methods consider these elements equal, while in case of a usual comparison of
floating-point numbers NaN != NaN.

Example:

void OnStart(void)
{
double x=sqrt(-1);

Print("single: ",x==x);

vector<double> v1={x};
vector<double> v2={x};

Print("vector: ", v1.Compare(v2,0)==0);


}

/* Result:

single: false
vector: true
*/

See also
MathClassify, Compare, CompareByDigits

© 2000-2025, MetaQuotes Ltd.


1314 Matrix and Vector Methods

Transpose
Matrix transposition. Reverse or permute the axes of a matrix; returns the modified matrix.
matrix matrix::Transpose()

Return Value

Transposed matrix.

A simple matrix transposition algorithm in MQL5:

matrix MatrixTranspose(const matrix& matrix_a)


{
matrix matrix_c(matrix_a.Cols(),matrix_a.Rows());

for(ulong i=0; i<matrix_c.Rows(); i++)


for(ulong j=0; j<matrix_c.Cols(); j++)
matrix_c[i][j]=matrix_a[j][i];

return(matrix_c);
}

MQL5 example:

matrix a= {{0, 1, 2}, {3, 4, 5}};


Print("matrix a \n", a);
Print("a.Transpose() \n", a.Transpose());

/*
matrix a
[[0,1,2]
[3,4,5]]
a.Transpose()
[[0,3]
[1,4]
[2,5]]
*/

Python example:

import numpy as np

a = np.arange(6).reshape((2,3))
print("a \n",a)
print("np.transpose(a) \n",np.transpose(a))

© 2000-2025, MetaQuotes Ltd.


1315 Matrix and Vector Methods

a
[[0 1 2]
[3 4 5]]
np.transpose(a)
[[0 3]
[1 4]
[2 5]]

© 2000-2025, MetaQuotes Ltd.


1316 Matrix and Vector Methods

TransposeConjugate
Transposing a complex matrix with conjugation. Reverse or permute the axes of a matrix by changing
a sign of an imaginary part of a complex number, return the modified matrix.
matrix matrix::TransposeConjugate()

Return Value

Transposed complex conjugate matrix.

S imple algorithm of transposing a complex matrix with conjugation - method explanation


//--- Complex matrix transpose function with conjugation
matrix MatrixTranspose(const matrix& matrix_a) {
//--- create a new matrix_c with dimensions inverse to matrix_a
matrix matrix_c(matrix_a.Cols(), matrix_a.Rows());

//--- go through all the rows of the new matrix


for (ulong i = 0; i < matrix_c.Rows(); i++) {
//--- go through all the columns of the new matrix
for (ulong j = 0; j < matrix_c.Cols(); j++) {
//--- transfer the real part of the element by transposing the index
matrix_c[i][j].real = matrix_a[j][i].real;

//--- transfer the imaginary part of the element by changing the sign (conjugation)
matrix_c[i][j].imag = -matrix_a[j][i].imag;
}
}

//--- return the transposed matrix with conjugation


return (matrix_c);
}

© 2000-2025, MetaQuotes Ltd.


1317 Matrix and Vector Methods

TriL
R eturn a copy of a matrix with elements above the k-th diagonal zeroed. Lower triangular matrix.
matrix matrix::Tril(
const int ndiag=0 // index of diagonal
);

Parameters
ndiag=0
[in] Diagonal above which to zero elements. ndiag =0 (the default) is the main diagonal, ndiag <
0 is below it and ndiag > 0 is above.

Return Value

Array with its lower triangle filled with ones and zero elsewhere.

MQL5 example:

matrix a={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
matrix b=a.TriL(-1);
Print("matrix b \n",b);

/*
matrix_c
[[0,0,0]
[4,0,0]
[7,8,0]
[10,11,12]]
*/

Python example:

import numpy as np

a=np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)

[[ 0 0 0]
[ 4 0 0]
[ 7 8 0]
[10 11 12]]

© 2000-2025, MetaQuotes Ltd.


1318 Matrix and Vector Methods

TriU
R eturn a copy of a matrix with the elements below the k-th diagonal zeroed. Upper triangular matrix.
matrix matrix::Triu(
const int ndiag=0 // index of diagonal
);

Parameters
ndiag=0
[in] Diagonal below which to zero elements. ndiag = 0 (the default) is the main diagonal, ndiag < 0
is below it and ndiag > 0 is above.

MQL5 example:

matrix a={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
matrix b=a.TriU(-1);
Print("matrix b \n",b);

/*
matrix b
[[1,2,3]
[4,5,6]
[0,8,9]
[0,0,12]]
*/

Python example:

import numpy as np

a=np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
print(a)

[[ 1 2 3]
[ 4 5 6]
[ 0 8 9]
[ 0 0 12]]

© 2000-2025, MetaQuotes Ltd.


1319 Matrix and Vector Methods

Diag
Extract a diagonal or construct a diagonal matrix.
vector matrix::Diag(
const int ndiag=0 // number of diagonal
);

void matrix::Diag(
const vector v, // diagonal vector
const int ndiag=0 // number of diagonal
);

Parameters
v
[in] Avector whose elements will be contained in the corresponding diagonal (ndiag=0 is the main
diagonal).
ndiag=0
[in] Diagonal in question. The default is 0. Use ndiag >0 for diagonals above the main diagonal,
and ndiag<0 for diagonals below the main diagonal.

Note

A diagonal can be set for unallocated matrices (which do not have dimensions). In this case, a zero
matrix of the size will be created with the size corresponding to the size of the diagonal vector,
after which the vector values will be populated in the corresponding diagonal. If the diagonal is set
to an already existing matrix, the matrix dimensions do not change and the values of the matrix
elements outside the diagonal vector do not change.

Example

vector v1={1,2,3};
matrix m1;
m1.Diag(v1);
Print("m1\n",m1);
matrix m2;
m2.Diag(v1,-1);
Print("m2\n",m2);
matrix m3;
m3.Diag(v1,1);
Print("m3\n",m3);
matrix m4=matrix::Full(4,5,9);
m4.Diag(v1,1);
Print("m4\n",m4);

Print("diag -1 - ",m4.Diag(-1));

© 2000-2025, MetaQuotes Ltd.


1320 Matrix and Vector Methods

Print("diag 0 - ",m4.Diag());
Print("diag 1 - ",m4.Diag(1));

/*

m1
[[1,0,0]
[0,2,0]
[0,0,3]]
m2
[[0,0,0]
[1,0,0]
[0,2,0]
[0,0,3]]
m3
[[0,1,0,0]
[0,0,2,0]
[0,0,0,3]]
m4
[[9,1,9,9,9]
[9,9,2,9,9]
[9,9,9,3,9]
[9,9,9,9,9]]
diag -1 - [9,9,9]
diag 0 - [9,9,9,9]
diag 1 - [1,2,3,9]
*/

© 2000-2025, MetaQuotes Ltd.


1321 Matrix and Vector Methods

Row
R eturn a row vector. W rite a vector to the specified row
vector matrix::Row(
const ulong nrow // row number
);

void matrix::Row(
const vector v, // row vector
const ulong nrow // row number
);

Parameters
nrow
[in] Number of row.

Return Value

Vector.

Note

A row can be set for unallocated matrices (which do not have dimensions). In this case, a zero
matrix will be created with the size of the vector size x row number+1, after which the values of the
vector elements will be populated in the corresponding row. If the row is set to an already existing
matrix, the matrix dimensions do not change and the values of the matrix elements outside the row
vector do not change.

Example

vector v1={1,2,3};
matrix m1;
m1.Row(v1,1);
Print("m1\n",m1);
matrix m2=matrix::Full(4,5,7);
m2.Row(v1,2);
Print("m2\n",m2);

Print("row 1 - ",m2.Row(1));
Print("row 2 - ",m2.Row(2));

/*
m1
[[0,0,0]
[1,2,3]]
m2

© 2000-2025, MetaQuotes Ltd.


1322 Matrix and Vector Methods

[[7,7,7,7,7]
[7,7,7,7,7]
[1,2,3,7,7]
[7,7,7,7,7]]
row 1 - [7,7,7,7,7]
row 2 - [1,2,3,7,7]
*/

© 2000-2025, MetaQuotes Ltd.


1323 Matrix and Vector Methods

Col
R eturn a column vector. W rite a vector to the specified column.
vector matrix::Col(
const ulong ncol // column number
);

void matrix::Col(
const vector v, // column vector
const ulong ncol // column number
);

Parameters
ncol
[in] Number of column.

Return Value

Vector.

Note

A column can be set for unallocated matrices (which do not have dimensions). In this case, a zero
matrix will be created with the size of the vector size x column number+1, after which the values of
the vector elements will be populated in the corresponding column. If the column is set to an already
existing matrix, the matrix dimensions do not change and the values of the matrix elements outside
the column vector do not change.

Example

vector v1={1,2,3};
matrix m1;
m1.Col(v1,1);
Print("m1\n",m1);
matrix m2=matrix::Full(4,5,8);
m2.Col(v1,2);
Print("m2\n",m2);

Print("col 1 - ",m2.Col(1));
Print("col 2 - ",m2.Col(2));

/*
m1
[[0,1]
[0,2]
[0,3]]
m2

© 2000-2025, MetaQuotes Ltd.


1324 Matrix and Vector Methods

[[8,8,1,8,8]
[8,8,2,8,8]
[8,8,3,8,8]
[8,8,8,8,8]]
col 1 - [8,8,8,8]
col 2 - [1,2,3,8]
*/

© 2000-2025, MetaQuotes Ltd.


1325 Matrix and Vector Methods

Copy
Create a copy of the given matrix/vector.
bool matrix::Copy(
const matrix& a // copied matrix
);
bool vector::Copy(
const vector& v // copied vector
);

Parameters
v
[in] Matrix or vector to copy.

Return Value

R eturns true on success, false otherwise.

MQL5 example:

matrix a=matrix::Eye(3, 4);


matrix b;
b.Copy(a);
matrix c=a;
Print("matrix b \n", b);
Print("matrix_c \n", c);

/*
/*
matrix b
[[1,0,0,0]
[0,1,0,0]
[0,0,1,0]]
matrix_c
[[1,0,0,0]
[0,1,0,0]
[0,0,1,0]]
*/
*/

Python example:

import numpy as np

a = np.eye(3,4)
print('a \n',a)
b = a

© 2000-2025, MetaQuotes Ltd.


1326 Matrix and Vector Methods

print('b \n',b)
c = np.copy(a)
print('c \n',c)

a
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
b
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
c
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]

© 2000-2025, MetaQuotes Ltd.


1327 Matrix and Vector Methods

Compare
Compare the elements of two matrices /vectors with the specified precision.
ulong vector::Compare(
const vector& vec, // vector to compare
const double epsilon // precision
);

ulong matrix::Compare(
const matrix& mat, // matrix to compare
const double epsilon // precision
);

Parameters
vec
[in] Vector to compare.
mat
[in] Matrix to compare.
epsilon
[in] Precision.

Return Value

The number of mismatched elements of the matrices or vectors being compared: 0 if the matrices
are equal, greater than 0 otherwise.

Note

The comparison operators == or != execute an exact element-wise comparison. It is known that the
exact comparison of real numbers is of limited use, so the epsilon comparison method was added. It
may happen that one matrix can contain elements in a range, for example from 1e-20 to 1e+20.
S uch matrices can be processed using element-wise comparison up to significant figures.

For complex matrices /vectors, the comparison involves estimating the distance between complex
numbers. The distance is calculated as s qrt(pow(r1-r2, 2) + pow(i1-i2, 2) and is a real number that
can already be compared with epsilon.

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4}};
matrix matrix_i=matrix::Identity(3,3);
matrix matrix_c=matrix_a.Inv();
matrix matrix_check=matrix_a.MatMul(matrix_c);
Print("matrix_check\n",matrix_check);

ulong errors=matrix_check.Compare(matrix::Identity(3,3),1e-15);

© 2000-2025, MetaQuotes Ltd.


1328 Matrix and Vector Methods

Print("errors=",errors);

/*
matrix_check
[[1,0,0]
[4.440892098500626e-16,1,8.881784197001252e-16]
[4.440892098500626e-16,2.220446049250313e-16,0.9999999999999996]]
errors=0

*/

© 2000-2025, MetaQuotes Ltd.


1329 Matrix and Vector Methods

CompareByDigits
Compare the elements of two matrices /vectors with the significant digits precision.
ulong vector::CompareByDigits(
const vector& vec, // vector to compare
const int digits // number of significant digits
);

ulong matrix::CompareByDigits(
const matrix& mat, // matrix to compare
const int digits // number of significant digits
);

Parameters
vec
[in] Vector to compare.
mat
[in] Matrix to compare.
digits
[in] Number of significant digits to compare.

Return Value

The number of mismatched elements of the matrices or vectors being compared: 0 if the matrices
are equal, greater than 0 otherwise.
Note

The comparison operators == or != execute an exact element-wise comparison. It is known that the
exact comparison of real numbers is of limited use, so the epsilon comparison method was added. It
may happen that one matrix can contain elements in a range, for example from 1e-20 to 1e+20.
S uch matrices can be processed using element-wise comparison up to significant digits.

Example

int size_m=128;
int size_k=256;
matrix matrix_a(size_m,size_k);
//--- fill the matrix
double value=0.0;
for(int i=0; i<size_m; i++)
{
for(int j=0; j<size_k; j++)
{
if(i==j)

© 2000-2025, MetaQuotes Ltd.


1330 Matrix and Vector Methods

matrix_a[i][j]=1.0+i;
else
{
value+=1.0;
matrix_a[i][j]=value/1e+20;
}
}
}
//--- get another matrix
matrix matrix_c = matrix_a * -1;

ulong errors_epsilon=matrix_a.Compare(matrix_c,1e-15);
ulong errors_digits=matrix_a.CompareByDigits(matrix_c,15);

printf("Compare matrix %d x %d errors_epsilon=%I64u errors_digits=%I64u",size_m,size_k,errors_

/*
Compare matrix 128 x 256 errors_epsilon=128 errors_digits=32768
*/

© 2000-2025, MetaQuotes Ltd.


1331 Matrix and Vector Methods

CompareEqual
Perform an absolute comparison of two matrices by unfolding successive rows into one-dimensional
vectors.
ulong vector::Compare(
const vector& vec // vector to compare
);

ulong matrix::CompareEqual(
const matrix& mat // matrix to compare
);

Parameters
vec
[in] Vector to compare.
mat
[in] Matrix to compare.

Method description

Let us have two matrices : matrix A the method is called for and matrix B, which is passed as a
method parameter. The comparison is performed as follows :
1. Matrices are expanded into one-dimensional vectors by successive concatenation of rows.
2. Vectors are compared element by element until the first mismatched element.
3. Depending on the comparison results, one of the values described below is returned.

Return Value

-1 — if the matrix A element is less than the corresponding matrix B element.


0— if all elements of A and B matrices are identical.
1— if the matrix A element exceeds the corresponding matrix B element.

Note

NaN value elements are taken into account when comparing.


NaN value elements are considered equal if they are present in both matrices at corresponding
positions.
The NaN sign is not taken into account in the comparison.
An element with a NaN value is considered to be less than any other numeric value.

Example

//+------------------------------------------------------------------+
//| Script program start function |

© 2000-2025, MetaQuotes Ltd.


1332 Matrix and Vector Methods

//+------------------------------------------------------------------+
void OnStart()
{
//---
matrix matrix_a= {{10, 3, 2}, {1, 8, 12}, {6, 5, 4}};
matrix matrix_i=matrix::Identity(3, 3);
matrix matrix_c=matrix_a.Inv();
matrix matrix_check=matrix_a.MatMul(matrix_c);
Print("matrix_check\n", matrix_check);

ulong errors=matrix_check.Compare(matrix::Identity(3, 3), 1e-15);


Print("errors=", errors);
/*
matrix_check
[[1,0,0]
[4.440892098500626e-16,1,8.881784197001252e-16]
[4.440892098500626e-16,2.220446049250313e-16,0.9999999999999996]]
errors=0
*/

//--- absolute comparison of matrices


matrix<double> A = matrix_a; // Matrix A initialization
matrix<double> B = matrix_c; // Matrix B initialization
int result = A.CompareEqual(B);
switch(result)
{
case -1:
Print("Matrix A is smaller than matrix B");
break;
case 0:
Print("Matrices A and B are identical");
break;
case 1:
Print("Matrix A is greater than matrix B");
break;
case -2:
Print("Error! Matrix A is not initialized");
break;
case 2:
Print("Error! Matrix B is not initialized");
break;
case -3:
Print("Error! The size of matrix A is less than the size of matrix B");
break;
case 3:
Print("Error! The size of matrix A is greater than the size of matrix B");
break;
default:
Print("Error! Unknown error");

© 2000-2025, MetaQuotes Ltd.


1333 Matrix and Vector Methods

break;
}
}

© 2000-2025, MetaQuotes Ltd.


1334 Matrix and Vector Methods

Flat
Allows addressing a matrix element through one index instead of two.
bool matrix::Flat(
const ulong index, // index
const double value // value to set
);

double matrix::Flat(
const ulong index, // index
);

Parameters
index
[in] Flat index

value
[in] Value to set by given index.

Return Value

Value by given index.

Note

For the matrix mat(3,3), access can be written as follows :


· reading: 'x=mat.Flat(4)', which is equivalent to 'x=mat[1][1]'
· writing: 'mat.Flat(5, 42)', equivalent to 'mat[1][2]=42'

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);
ulong arg_max=matrix_a.ArgMax();
Print("max_value=",matrix_a.Flat(arg_max));
matrix_a.Flat(arg_max,0);
arg_max=matrix_a.ArgMax();
Print("max_value=",matrix_a.Flat(arg_max));

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]

© 2000-2025, MetaQuotes Ltd.


1335 Matrix and Vector Methods

max_value=12.0
max_value=11.0
*/

© 2000-2025, MetaQuotes Ltd.


1336 Matrix and Vector Methods

Clip
Limit the elements of a matrix/vector to a specified range of valid values.
bool matrix::Clip(
const double min_value, // minimum value
const double max_value // maximum value
);
bool vector::Clip(
const double min_value, // minimum value
const double max_value // maximum value
);

Parameters
min_value
[in] Minimum value.
max_value
[in] Maximum value.

Return Value

R eturns true on success, false otherwise.

Note
The matrix (or vector) is processed in place. No copies are created.

Example

matrix matrix_a={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
bool res=matrix_a.Clip(4,8);
Print("matrix_a\n",matrix_a);

/*
matrix_a
[[4,4,4]
[4,5,6]
[7,8,8]
[8,8,8]]
*/

© 2000-2025, MetaQuotes Ltd.


1337 Matrix and Vector Methods

Reshape
Change the shape of a matrix without changing its data.
void Reshape(
const ulong rows, // new number or rows
const ulong cols // new number or columns
);

Parameters
rows
[in] New number or rows.
cols
[in] New number or columns.
Note
The matrix is processed in place. No copies are created. Any size can be specified, i.e.,
rows _new*cols _new!=rows _old*cols _old. W hen the matrix buffer is increased, the extra values are
undefined.

Example

matrix matrix_a={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};

Print("matrix_a\n",matrix_a);
matrix_a.Reshape(2,6);
Print("Reshape(2,6)\n",matrix_a);
matrix_a.Reshape(3,5);
Print("Reshape(3,5)\n",matrix_a);
matrix_a.Reshape(2,4);
Print("Reshape(2,4)\n",matrix_a);

/*
matrix_a
[[1,2,3]
[4,5,6]
[7,8,9]
[10,11,12]]
Reshape(2,6)
[[1,2,3,4,5,6]
[7,8,9,10,11,12]]
Reshape(3,5)
[[1,2,3,4,5]
[6,7,8,9,10]
[11,12,0,3,0]]
Reshape(2,4)
[[1,2,3,4]

© 2000-2025, MetaQuotes Ltd.


1338 Matrix and Vector Methods

[5,6,7,8]]
*/

© 2000-2025, MetaQuotes Ltd.


1339 Matrix and Vector Methods

Resize
R eturn a new matrix with a changed shape and size.
bool matrix::Resize(
const ulong rows, // new number or rows
const ulong cols, // new number or columns
const ulong reserve=0 // reserve amount in items
);

bool vector::Resize(
const ulong size, // new size.
const ulong reserve=0 // reserve amount in items.
);

Parameters
rows
[in] New number or rows.
cols
[in] New number or columns.

Return Value

R eturns true on success, false otherwise.

Note
The matrix (or vector) is processed in place. No copies are created. Any size can be specified,
i.e., rows _new*cols _new!=rows _old*cols _old. Unlike Reshape, the matrix is processed row by row.
W hen increasing the number of columns, the values of the extra columns are undefined. W hen
increasing the number of rows, the values of elements in the new rows are undefined. W hen the
number of columns is reduced, each row of the matrix is truncated.

Example

matrix matrix_a={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
Print("matrix_a\n",matrix_a);
matrix_a.Resize(2,6);
Print("Ressize(2,6)\n",matrix_a);
matrix_a.Resize(3,5);
Print("Resize(3,5)\n",matrix_a);
matrix_a.Resize(2,4);
Print("Resize(2,4)\n",matrix_a);

/*
matrix_a
[[1,2,3]

© 2000-2025, MetaQuotes Ltd.


1340 Matrix and Vector Methods

[4,5,6]
[7,8,9]
[10,11,12]]
Ressize(2,6)
[[1,2,3,4,5,6]
[4,5,6,10,11,12]]
Resize(3,5)
[[1,2,3,4,5]
[4,5,6,10,11]
[11,12,3,8,8]]
Resize(2,4)
[[1,2,3,4]
[4,5,6,10]]
*/

© 2000-2025, MetaQuotes Ltd.


1341 Matrix and Vector Methods

Set
S ets the value for a vector element by the specified index.
bool vector::Set(
ulong index, // element index
double value // value
);

Parameters
index
[in] Index of the element the value needs to be set for.
value
[in] Value.

Return Value

R eturns true if successful, otherwise - false.

Note
The S et method does the same thing as assigning a value using s quare brackets, namely:
vector[index]=value. The method has been added to simplify transferring a code from languages

where this type of notation is used. The example below shows both options for filling the vector
with values by the specified index.

Example:

void OnStart()
{
//---
vector v1(10, VectorAssignValues);
Print("v1 = ", v1);

vector v2(10, VectorSetValues);


Print("v2 = ", v2);
}
/* Result
v1 = [1,2,4,8,16,32,64,128,256,512]
v2 = [1,2,4,8,16,32,64,128,256,512]
*/
//+-------------------------------------------------------------------------+
//| Fill a vector with powers of a number through the assignment operation |
//+-------------------------------------------------------------------------+
void VectorAssignValues(vector& v, double initial=1)
{
double value=initial;

© 2000-2025, MetaQuotes Ltd.


1342 Matrix and Vector Methods

for(ulong k=0; k<v.Size(); k++)


{
v[k]=value;
value*=2;
}
}
//+--------------------------------------------------------------------------+
//| Fill a vector with powers of a number using the Set method |
//+--------------------------------------------------------------------------+
void VectorSetValues(vector& v, double initial=1)
{
double value=initial;
for(ulong k=0; k<v.Size(); k++)
{
v.Set(k, value);
value*=2;
}
}

© 2000-2025, MetaQuotes Ltd.


1343 Matrix and Vector Methods

SwapRows
S wap rows in a matrix.
bool matrix::SwapRows(
const ulong row1, // index of first row
const ulong row2 // index of second row
);

Parameters
row1
[in] Index of the first row.
row2
[in] Index of the second row.

Return Value

R eturns true on success, false otherwise.

Example

matrix matrix_a={{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}};
matrix matrix_i=matrix::Identity(4,4);
matrix matrix_a1=matrix_a;
matrix_a1.SwapRows(0,3);
Print("matrix_a1\n",matrix_a1);

matrix matrix_p=matrix_i;
matrix_p.SwapRows(0,3);
matrix matrix_c1=matrix_p.MatMul(matrix_a);
Print("matrix_c1\n",matrix_c1);

/*
matrix_a1
[[13,14,15,16]
[5,6,7,8]
[9,10,11,12]
[1,2,3,4]]
matrix_c1
[[13,14,15,16]
[5,6,7,8]
[9,10,11,12]
[1,2,3,4]]
*/

© 2000-2025, MetaQuotes Ltd.


1344 Matrix and Vector Methods

SwapCols
S wap columns in a matrix.
bool matrix::SwapCols(
const ulong row1, // index of first column
const ulong row2 // index of second column
);

Parameters
col1
[in] Index of the first column.
col2
[in] Index of the second column.

Return Value

R eturns true on success, false otherwise.

Example

matrix matrix_a={{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}};
matrix matrix_i=matrix::Identity(4,4);
matrix matrix_a1=matrix_a;
matrix_a1.SwapCols(0,3);
Print("matrix_a1\n",matrix_a1);

matrix matrix_p=matrix_i;
matrix_p.SwapCols(0,3);
matrix matrix_c1=matrix_a.MatMul(matrix_p);
Print("matrix_c1\n",matrix_c1);

/*
matrix_a1
[[4,2,3,1]
[8,6,7,5]
[12,10,11,9]
[16,14,15,13]]
matrix_c1
[[4,2,3,1]
[8,6,7,5]
[12,10,11,9]
[16,14,15,13]]
*/

© 2000-2025, MetaQuotes Ltd.


1345 Matrix and Vector Methods

Split
S plit a matrix into multiple submatrices.
bool matrix::Split(
const ulong parts, // number of submatrices
const int axis, // axis
matrix& splitted[] // array of resulting submatrices
);

void matrix::Split(
const ulong& parts[], // sizes of submatrices
const int axis, // axis
matrix& splitted[] // array of resulting submatrices
);

Parameters
parts
[in] The number of submatrices to divide the matrix into.
axis
[in] Axis. 0 - horizontal axis, 1 - vertical axis.
splitted
[out] Array of resulting submatrices.

Return Value

R eturns true on success, false otherwise.

Note
If the number of submatrices is specified, then same size submatrices are obtained. It means that
the matrix size (0 - the number of rows, 1 - the number of columns) must be divisible by 'parts '
without a remainder. S ubmatrices of different sizes can be obtained using an array of submatrix
sizes. The elements of the size array are used until the entire matrix is divided. If the array of
sizes has ended, and the matrix has not yet been completely divided, the undivided remainder will
be the last submatrix.

Example

matrix matrix_a={{ 1, 2, 3, 4, 5, 6},


{ 7, 8, 9,10,11,12},
{13,14,15,16,17,18},
{19,20,21,22,23,24},
{25,26,27,28,29,30}};
matrix splitted[];
ulong parts[]={2,2};

© 2000-2025, MetaQuotes Ltd.


1346 Matrix and Vector Methods

bool res=matrix_a.Split(2,0,splitted);
Print(res," ",GetLastError());
ResetLastError();
for(uint i=0; i<splitted.Size(); i++)
Print("splitted ",i,"\n",splitted[i]);

res=matrix_a.Split(2,1,splitted);
Print(res," ",GetLastError());
for(uint i=0; i<splitted.Size(); i++)
Print("splitted ",i,"\n",splitted[i]);

res=matrix_a.Split(parts,0,splitted);
Print(res," ",GetLastError());
for(uint i=0; i<splitted.Size(); i++)
Print("splitted ",i,"\n",splitted[i]);

/*
false 4003
true 0
splitted 0
[[1,2,3]
[7,8,9]
[13,14,15]
[19,20,21]
[25,26,27]]
splitted 1
[[4,5,6]
[10,11,12]
[16,17,18]
[22,23,24]
[28,29,30]]
true 0
splitted 0
[[1,2,3,4,5,6]
[7,8,9,10,11,12]]
splitted 1
[[13,14,15,16,17,18]
[19,20,21,22,23,24]]
splitted 2
[[25,26,27,28,29,30]]
*/

© 2000-2025, MetaQuotes Ltd.


1347 Matrix and Vector Methods

Hsplit
S plit a matrix horizontally into multiple submatrices. S ame as S plit with axis =0
bool matrix::Hsplit(
const ulong parts, // number of submatrices
matrix& splitted[] // array of resulting submatrices
);

void matrix::Hsplit(
const ulong& parts[], // sizes of submatrices
matrix& splitted[] // array of resulting submatrices
);

Parameters
parts
[in] The number of submatrices to divide the matrix into.
splitted
[out] Array of resulting submatrices.

Return Value

R eturns true on success, false otherwise.

Note
If the number of submatrices is specified, then same size submatrices are obtained. It means that
the number of rows must be divisible by 'parts ' without a remainder. S ubmatrices of different sizes
can be obtained using an array of submatrix sizes. The elements of the size array are used until
the entire matrix is divided. If the array of sizes has ended, and the matrix has not yet been
completely divided, the undivided remainder will be the last submatrix.

Example

matrix matrix_a={{ 1, 2, 3, 4, 5, 6},


{ 7, 8, 9,10,11,12},
{13,14,15,16,17,18},
{19,20,21,22,23,24},
{25,26,27,28,29,30}};
matrix splitted[];
ulong parts[]={2,4};

bool res=matrix_a.Hsplit(2,splitted);
Print(res," ",GetLastError());
ResetLastError();
for(uint i=0; i<splitted.Size(); i++)
Print("splitted ",i,"\n",splitted[i]);

© 2000-2025, MetaQuotes Ltd.


1348 Matrix and Vector Methods

res=matrix_a.Hsplit(5,splitted);
Print(res," ",GetLastError());
for(uint i=0; i<splitted.Size(); i++)
Print("splitted ",i,"\n",splitted[i]);

res=matrix_a.Hsplit(parts,splitted);
Print(res," ",GetLastError());
for(uint i=0; i<splitted.Size(); i++)
Print("splitted ",i,"\n",splitted[i]);

/*
false 4003
true 0
splitted 0
[[1,2,3,4,5,6]]
splitted 1
[[7,8,9,10,11,12]]
splitted 2
[[13,14,15,16,17,18]]
splitted 3
[[19,20,21,22,23,24]]
splitted 4
[[25,26,27,28,29,30]]
true 0
splitted 0
[[1,2,3,4,5,6]
[7,8,9,10,11,12]]
splitted 1
[[13,14,15,16,17,18]
[19,20,21,22,23,24]
[25,26,27,28,29,30]]
*/

© 2000-2025, MetaQuotes Ltd.


1349 Matrix and Vector Methods

Vsplit
S plit a matrix vertically into multiple submatrices. S ame as S plit with axis =1
bool matrix::Vsplit(
const ulong parts, // number of submatrices
matrix& splitted[] // array of resulting submatrices
);

void matrix::Vsplit(
const ulong& parts[], // sizes of submatrices
matrix& splitted[] // array of resulting submatrices
);

Parameters
parts
[in] The number of submatrices to divide the matrix into.
splitted
[out] Array of resulting submatrices.

Return Value

R eturns true on success, false otherwise.


Note
If the number of submatrices is specified, then same size submatrices are obtained. It means that
the number of columns must be divisible by 'parts ' without a remainder. S ubmatrices of different
sizes can be obtained using an array of submatrix sizes. The elements of the size array are used
until the entire matrix is divided. If the array of sizes has ended, and the matrix has not yet been
completely divided, the undivided remainder will be the last submatrix.

Example

matrix matrix_a={{ 1, 2, 3, 4, 5, 6},


{ 7, 8, 9,10,11,12},
{13,14,15,16,17,18}};
matrix splitted[];
ulong parts[]={2,3};

matrix_a.Vsplit(2,splitted);
for(uint i=0; i<splitted.Size(); i++)
Print("splitted ",i,"\n",splitted[i]);

matrix_a.Vsplit(3,splitted);
for(uint i=0; i<splitted.Size(); i++)
Print("splitted ",i,"\n",splitted[i]);

© 2000-2025, MetaQuotes Ltd.


1350 Matrix and Vector Methods

matrix_a.Vsplit(parts,splitted);
for(uint i=0; i<splitted.Size(); i++)
Print("splitted ",i,"\n",splitted[i]);

/*
splitted 0
[[1,2,3]
[7,8,9]
[13,14,15]]
splitted 1
[[4,5,6]
[10,11,12]
[16,17,18]]

splitted 0
[[1,2]
[7,8]
[13,14]]
splitted 1
[[3,4]
[9,10]
[15,16]]
splitted 2
[[5,6]
[11,12]
[17,18]]

splitted 0
[[1,2]
[7,8]
[13,14]]
splitted 1
[[3,4,5]
[9,10,11]
[15,16,17]]
splitted 2
[[6]
[12]
[18]]

*/

© 2000-2025, MetaQuotes Ltd.


1351 Matrix and Vector Methods

ArgSort
Indirect sort of a matrix or vector.
vector vector::Sort(
func_name compare_func=NULL, // comparison function
T context // parameter for the custom sort function
);

matrix matrix::Sort(
func_name compare_func=NULL // comparison function
T context // parameter for the custom sort function
);

matrix matrix::Sort(
const int axis, // axis for sorting
func_name compare_func=NULL // comparison function
T context // parameter for the custom sort function
);

Parameters
axis
[in] The axing along which to sort: 0 is horizontal, 1 is vertical.
func_name
[in]Comparator. You can specify one of the values of the ENUM _S ORT_MODE enumeration or your
own comparison function. If no function is specified, ascending sort is used.

A custom comparison function can be of two types :


· int comparator(T x1,T x2)
· int comparator(T x1,T x2,TContext context)
H ereT is the type of matrix or vector, and TContex is the type of the 'context' variable which is
passed as an additional parameter to the S ort method.
context
[in] Additional optional parameter that can be passed to a custom sort function.

Return Value

Vector or matrix with the indexes of sorted elements. For example, the result [4,2,0,1,3] indicates
that there should be an element with index 4 in the zero position, an element with index 2 in the
first position, and so on.

© 2000-2025, MetaQuotes Ltd.


1352 Matrix and Vector Methods

Sort
S ort a matrix or vector in place.
void vector::Sort(
func_name compare_func=NULL, // comparison function
T context // parameter for the custom sort function
);

void matrix::Sort(
func_name compare_func=NULL // comparison function
T context // parameter for the custom sort function
);

void matrix::Sort(
const int axis, // axis for sorting
func_name compare_func=NULL // comparison function
T context // parameter for the custom sort function
);

Parameters
axis
[in] The axing along which to sort: 0 is horizontal, 1 is vertical.
func_name
[in]Comparator. You can specify one of the values of the ENUM _S ORT_MODE enumeration or your
own comparison function. If no function is specified, ascending sort is used.

A custom comparison function can be of two types :


· int comparator(T x1,T x2)
· int comparator(T x1,T x2,TContext context)
H ereT is the type of matrix or vector, and TContex is the type of the 'context' variable which is
passed as an additional parameter to the S ort method.
context
[in] Additional optional parameter that can be passed to a custom sort function.

Return Value

None. S orting is performed in place, i.e. it is applied to the data of the matrix/vector for which the
S ort method is called.

Example

//+------------------------------------------------------------------+
//| Sort function |
//+------------------------------------------------------------------+
int MyDoubleComparator(double x1,double x2,int sort_mode=0)
{

© 2000-2025, MetaQuotes Ltd.


1353 Matrix and Vector Methods

int res=x1<x2 ? -1 : (x1>x2 ? 1 : 0);


return(sort_mode==0 ? res : -res);
}
//+------------------------------------------------------------------+
//| Script start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- fill the vector
vector v(100);
//--- sort ascending
v.Sort(MyDoubleComparator); // an additional parameter with the default value '0' is used here
Print(v);
// sort descending
v.Sort(MyDoubleComparator,1); // here the additional parameter '1' is explicitly specified by th
Print(v);
}

© 2000-2025, MetaQuotes Ltd.


1354 Matrix and Vector Methods

Mathematical operations with matrices and vectors


Mathematical operations, including addition, subtraction, multiplication and division, can be
performed on matrices and vectors element-wise.
Mathematical functions were originally designed to perform relevant operations on scalar values. Most
of the functions can be applied to matrices and vectors. These include MathAbs, MathArccos,
MathArcsin, MathArctan, MathCeil, MathCos, MathExp, MathFloor, MathLog, MathLog10, MathMod,
MathPow, MathRound, MathS in, MathSqrt, MathTan, MathExpm1, MathLog1p, MathArccosh,
MathArcsinh, MathArctanh, MathCosh, MathS inh, and MathTanh. S uch operations imply element-wise
processing of matrices and vectors. Example
//---
matrix a= {{1, 4}, {9, 16}};
Print("matrix a=\n",a);
a=MathSqrt(a);
Print("MatrSqrt(a)=\n",a);
/*
matrix a=
[[1,4]
[9,16]]
MatrSqrt(a)=
[[1,2]
[3,4]]
*/

For MathMod and MathPow, the second element can be either a scalar or a matrix/vector of the
appropriate size.
The following example shows how to calculate the standard deviation by applying math functions to a
vector.
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- use the initializing function to fill the vector
vector r(10, ArrayRandom); // array of random numbers from 0 to 1
//--- calculate the mean value
double avr=r.Mean(); // array mean value
vector d=r-avr; // calculate an array of deviations from the mean
Print("avr(r)=", avr);
Print("r=", r);
Print("d=", d);
vector s2=MathPow(d, 2); // array of squared deviations
double sum=s2.Sum(); // sum of squared deviations
//--- calculate the standard deviation in two different methods
double std=MathSqrt(sum/r.Size());
Print(" std(r)=", std);

© 2000-2025, MetaQuotes Ltd.


1355 Matrix and Vector Methods

Print("r.Std()=", r.Std());
}
/*
avr(r)=0.5300302133243813
r=[0.8346201971495713,0.8031556138798182,0.6696676534318063,0.05386516922513505,0.549119541001617
d=[0.30458998382519,0.2731254005554369,0.1396374401074251,-0.4761650440992462,0.01908932767723626
std(r)=0.2838269732183663
r.Std()=0.2838269732183663
*/
//+------------------------------------------------------------------+
//| Fills a vector with random values |
//+------------------------------------------------------------------+
void ArrayRandom(vector& v)
{
for(ulong i=0; i<v.Size(); i++)
v[i]=double(MathRand())/32767.;
}

© 2000-2025, MetaQuotes Ltd.


1356 Matrix and Vector Methods

Mathematical operations
Mathematical operations, including addition, subtraction, multiplication and division, can be
performed on matrices and vectors element-wise.
Bothmatrices or both vectors must be of the same type and must have the same dimensions. Each
element of the matrix operates on the corresponding element of the second matrix.
You can also use a scalar of the appropriate type (double, float or complex) as the second term
(multiplier, subtrahend or divisor). In this case, each member of the matrix or vector will operate on
the specified scalar.
matrix matrix_a={{0.1,0.2,0.3},{0.4,0.5,0.6}};
matrix matrix_b={{1,2,3},{4,5,6}};

matrix matrix_c1=matrix_a+matrix_b;
matrix matrix_c2=matrix_b-matrix_a;
matrix matrix_c3=matrix_a*matrix_b; // Hadamard product, not to be confused with matrix product
matrix matrix_c4=matrix_b/matrix_a;

matrix_c1=matrix_a+1;
matrix_c2=matrix_b-double_value;
matrix_c3=matrix_a*M_PI;
matrix_c4=matrix_b/0.1;

//--- operations in place are possible


matrix_a+=matrix_b;
matrix_a/=2;

The same operations are available for vectors.

© 2000-2025, MetaQuotes Ltd.


1357 Matrix and Vector Methods

Mathematical functions
The following mathematical functions can be applied to matrices and vectors : MathAbs, MathArccos,
MathArcsin, MathArctan, MathCeil, MathCos, MathExp, MathFloor, MathLog, MathLog10, MathMod,
MathPow, MathRound, MathS in, MathSqrt, MathTan, MathExpm1, MathLog1p, MathArccosh,
MathArcsinh, MathArctanh, MathCosh, MathS inh, MathTanh. S uch operations imply element-wise
processing of matrices and vectors.
For MathMod and MathPow, the second element can be either a scalar or a matrix/vector of the
appropriate size.
matrix<T> mat1(128,128);
matrix<T> mat3(mat1.Rows(),mat1.Cols());
ulong n,size=mat1.Rows()*mat1.Cols();
...
mat2=MathPow(mat1,(T)1.9);
for(n=0; n<size; n++)
{
T res=MathPow(mat1.Flat(n),(T)1.9);
if(res!=mat2.Flat(n))
errors++;
}
mat2=MathPow(mat1,mat3);
for(n=0; n<size; n++)
{
T res=MathPow(mat1.Flat(n),mat3.Flat(n));
if(res!=mat2.Flat(n))
errors++;
}
...
vector<T> vec1(16384);
vector<T> vec3(vec1.Size());
ulong n,size=vec1.Size();
...
vec2=MathPow(vec1,(T)1.9);
for(n=0; n<size; n++)
{
T res=MathPow(vec1[n],(T)1.9);
if(res!=vec2[n])
errors++;
}
vec2=MathPow(vec1,vec3);
for(n=0; n<size; n++)
{
T res=MathPow(vec1[n],vec3[n]);
if(res!=vec2[n])
errors++;
}

© 2000-2025, MetaQuotes Ltd.


1358 Matrix and Vector Methods

Matrix and vector products


Matrix and vector product calculations include:
· matrix multiplication
· vector multiplication
· computing covariance matrix
· computing the cross-correlation of two vectors
· computing the convolution of two vectors
· computing the correlation coefficient

Function Action

MatMul Matrix product of two matrices


GeMM General matrix multiplication (GeMM)
Power R aise a s quare matrix to the integer power
Dot Dot product of two vectors
Kron R eturn Kroneck er
product of two matrices, matrix and vector, vector
and matrix or two vectors
Inner Inner product of two matrices
Outer Compute the outer product of two matrices or two vectors
CorrCoef Compute the Pearson correlation coefficient (linear correlation
coefficient)
Cov Compute the covariance matrix
Correlate Compute the cross-correlation of two vectors
Convolve R eturn the discrete, linear convolution of two vectors

© 2000-2025, MetaQuotes Ltd.


1359 Matrix and Vector Methods

MatMul
The MatMul method, which enables the multiplication of matrices and vectors, has several overloads.
Multiplying a matrix by a matrix: matrix[M][K] * matrix[K][N] = matrix[M][N]
matrix matrix::MatMul(
const matrix& b // second matrix
);

Multiplying a vector by a matrix: horizontal vector[K] * matrix[K][N] = horizontal


vector[N]
vector vector::MatMul(
const matrix& b // matrix
);

Multiplying a matrix by a vector : matrix[M][K] * vertical vector[K] = vertical vector[M]


vector matrix::MatMul(
const vector& b // vector
);

Scalar vector multiplication: horizontal vector * vertical vector = dot value


scalar vector::MatMul(
const vector& b // second vector
);

Parameters
b
[in] Matrix or vector.

Return Value

Matrix, vector, or scalar, depending on the method used.

Note

The matrices should be compatible for multiplication, i.e. the number of columns in the first matrix
should be equal to the number of rows in the second matrix. Matrix multiplication is non-
commutative: the result of multiplying the first matrix by the second one is not equal to the result
of multiplying the second matrix by the first one in the general case.
The matrix product consists of all possible combinations of scalar products of the row vectors of the
first matrix and the column vectors of the second matrix.
In scalar multiplication, vectors must have the same length.
W hen multiplyinga vector and a matrix, the length of the vector must exactly match the number of
columns in the matrix.

© 2000-2025, MetaQuotes Ltd.


1360 Matrix and Vector Methods

Naive matrix multiplication algorithm in MQL5:

matrix MatrixProduct(const matrix& matrix_a, const matrix& matrix_b)


{
matrix matrix_c;

if(matrix_a.Cols()!=matrix_b.Rows())
return(matrix_c);

ulong M=matrix_a.Rows();
ulong K=matrix_a.Cols();
ulong N=matrix_b.Cols();
matrix_c=matrix::Zeros(M,N);

for(ulong m=0; m<M; m++)


for(ulong k=0; k<K; k++)
for(ulong n=0; n<N; n++)
matrix_c[m][n]+=matrix_a[m][k]*matrix_b[k][n];

return(matrix_c);
}

Matrix multiplication example

matrix a={{1, 0, 0},


{0, 1, 0}};
matrix b={{4, 1},
{2, 2},
{1, 3}};
matrix c1=a.MatMul(b);
matrix c2=b.MatMul(a);
Print("c1 = \n", c1);
Print("c2 = \n", c2);
/*
c1 =
[[4,1]
[2,2]]
c2 =
[[4,1,0]
[2,2,0]
[1,3,0]]
*/

An example of multiplying a horizontal vector by a matrix

//+------------------------------------------------------------------+
//| Script program start function |

© 2000-2025, MetaQuotes Ltd.


1361 Matrix and Vector Methods

//+------------------------------------------------------------------+
void OnStart()
{
//--- create a 3x5 matrix
matrix m35;
m35.Init(3, 5, Arange);
//---
vector v3 = {1, 2, 3};
Print("Product of horizontal vector v and matrix m[3,5]");
Print("On the left, vector v3 = ", v3);
Print("On the right, matrix m35 = \n", m35);
Print("v3.MatMul(m35) = horizontal vector v[5] \n", v3.MatMul(m35));

/* Result
Product of horizontal vector v3 and matrix m[3,5]
On the left, vector v3 = [1,2,3]
On the right, matrix m35 =
[[0,1,2,3,4]
[5,6,7,8,9]
[10,11,12,13,14]]
v3.MatMul(m35) = horizontal vector v[5]
[40,46,52,58,64]
*/
}
//+------------------------------------------------------------------+
//| Fill the matrix with increasing values |
//+------------------------------------------------------------------+
void Arange(matrix & m, double start = 0, double step = 1)
{
//---
ulong cols = m.Cols();
ulong rows = m.Rows();
double value = start;
for(ulong r = 0; r < rows; r++)
{
for(ulong c = 0; c < cols; c++)
{
m[r][c] = value;
value += step;
}
}
//---
}

An example of how to multiply a matrix by a vertical vector

//+------------------------------------------------------------------+
//| Script program start function |

© 2000-2025, MetaQuotes Ltd.


1362 Matrix and Vector Methods

//+------------------------------------------------------------------+
void OnStart()
{
//--- create a 3x5 matrix
matrix m35;
m35.Init(3, 5, Arange);
//---
Print("Product of matrix m[3,5] and vertical vector v[5]");
vector v5 = {1,2,3,4,5};
Print("On the left, m35 = \n",m35);
Print("On the right v5 = ",v5);
Print("m35.MatMul(v5) = vertical vector v[3] \n",m35.MatMul(v5));

/* Result
Product of matrix m[3,5] and vertical vector v[5]
On the left, m35 =
[[0,1,2,3,4]
[5,6,7,8,9]
[10,11,12,13,14]]
On the right, v5 = [1,2,3,4,5]
m35.MatMul(v5) = vertical vector v[3]
[40,115,190]
*/
}
//+------------------------------------------------------------------+
//| Fill the matrix with increasing values |
//+------------------------------------------------------------------+
void Arange(matrix & m, double start = 0, double step = 1)
{
//---
ulong cols = m.Cols();
ulong rows = m.Rows();
double value = start;
for(ulong r = 0; r < rows; r++)
{
for(ulong c = 0; c < cols; c++)
{
m[r][c] = value;
value += step;
}
}
//---
}

An example of scalar (dot) product of vectors

void OnStart()
{

© 2000-2025, MetaQuotes Ltd.


1363 Matrix and Vector Methods

//--- scalar product of a horizontal vector and a vertical one


vector a= {1, 2, 3}; // horizontal vector
vector b= {4, 5, 6}; // vertical vector
Print("a = ", a);
Print("b = ", b);
Print("1) a.MatMul(b) = ", a.MatMul(b));
//--- see that the Dot method generates the same result
Print("2) a.Dot(b) = ", a.Dot(b));

/* Result
a = [1,2,3]
b = [4,5,6]
1) a.MatMul(b) = 32.0
2) a.Dot(b) = 32.0
*/
}

See also
Dot, GeMM

© 2000-2025, MetaQuotes Ltd.


1364 Matrix and Vector Methods

GeMM
The GeMM (General Matrix Multiply) method implements the general multiplication of two matrices.
The operation is defined as C ← α A B + β C , where A and B matrices can be optionally transposed.
W ith a normal multiplication of matrices AB (MatMul), the alpha scalar is assumed to be equal to 1 and
beta equal to zero.

The main difference between GeMM and MatMul in terms of efficiency is that MatMul always creates a
new matrix/vector object, while GeMM works with an existing matrix object and does not re-create it.
Therefore, when you use GeMM and pre-allocate memory for the corresponding matrix, then, while
working with the same matrix sizes, there will be no memory reallocations. This can be an important
advantage of GeMM for bulk computing, for example, when running optimizations in a strategy tester
or when training a neural network.
S imilar
to MatMul, GeMM also has 4 overloads. However, the semantics of the fourth overload has
been modified in order to enable the multiplication of a vertical vector with a and horizontal one.
In an existing matrix/vector object, it is not necessary to pre-allocate memory. The memory will be
allocated and filled with zeros at the first GeMM call.
Multiplying a matrix by a matrix: matrix C[M][N] = α * ( matrix A[M][K] * matrix B[K][N])
+ β * matrix C[M][N]
bool matrix::GeMM(
const matrix &A, // first matrix
const matrix &B, // second matrix
double alpha, // alpha multiplier for product AB
double beta, // beta multiplier for matrix C
uint flags // a combination of ENUM_GEMM values (bitwise OR), which determines whether m
);

Multiplying a vector by a matrix: vector C[N] = α * ( vector A[K] * matrix B[K][N]) + β *


vector C[N]
bool vector::GeMM(
const vector &A, // horizontal vector
const matrix &B, // matrix
double alpha, // alpha multiplier for product AB
double beta, // beta multiplier for vector C
uint flags // ENUM_GEMM enumeration value that determines whether matrix A is transposed
);

Multiplying a matrix by a vector : vector C[M] = α * ( matrix A[M][K] * vector B[K] * ) + β *


vector C[M]
bool vector::GeMM(
const matrix &A, // matrix
const vector &B, // vertical vector
double alpha, // alpha multiplier for product AB
double beta, // beta multiplier for vector C
uint flags // ENUM_GEMM enumeration value that determines whether matrix B is transposed
);

© 2000-2025, MetaQuotes Ltd.


1365 Matrix and Vector Methods

Multiplying a vector by a vector: matrix C[M][N] = α * ( vector A[M] * vector B[N] * ) + β *


matrix C[M][N]. This overload returns a matrix, unlik e MatMul where it returns a scalar.
bool matrix::GeMM(
const vector &A, // first vector
const vector &B, // second vector
double alpha, // alpha multiplier for product AB
double beta, // beta for matrix C
uint flags // ENUM_GEMM enumeration value that determines whether matrix C is transposed
);

Parameters
A
[in] Matrix or vector.
B
[in] Matrix or vector.
alpha
[in] Alpha multiplier for the AB product.
beta
[in] Beta multiplier for the resulting C matrix.
flags
[in] The ENUM _GEMM enumeration value that determines whether matrices A, B and C are
transposed.

Return Value

R eturns true on success or false otherwise.

ENUM_GEMM

Enumeration of flags for the GeMM method.

ID Description

TRANS P_A Use transposed matrix A

TRANS P_B Use transposed matrix B

TRANS P_C Use transposed matrix C

Note

Matrices and vectors of float, double and complex types can be used as parameters A and B. The
template variants of the GeMM method are as follows :
bool matrix<T>::GeMM(const matrix<T> &A,const matrix<T> &B,T alpha,T beta,ulong flags);

© 2000-2025, MetaQuotes Ltd.


1366 Matrix and Vector Methods

bool matrix<T>::GeMM(const vector<T> &A,const vector<T> &B,T alpha,T beta,ulong flags);

bool vector<T>::GeMM(const vector<T> &A,const matrix<T> &B,T alpha,T beta,ulong flags);


bool vector<T>::GeMM(const matrix<T> &A,const vector<T> &B,T alpha,T beta,ulong flags);

Basically the general matrix multiplication function is described as :


C[m,n] = α *Sum(A[m,k]*B[k,n]) + β*C[m,n]

with the following sizes : matrix A is M x K, matrix B is K x N and matrix C is M x N.


Thus, the matrices should be compatible for multiplication, i.e. the number of columns in the first
matrix should be equal to the number of rows in the second matrix. Matrix multiplication is non-
commutative: the result of multiplying the first matrix by the second one is not equal to the result of
multiplying the second matrix by the first one in the general case.

Example:

void OnStart()
{
vector vector_a= {1, 2, 3, 4, 5};
vector vector_b= {4, 3, 2, 1};
matrix matrix_c;
//--- calculate GeMM for two vectors
matrix_c.GeMM(vector_a, vector_b, 1, 0);
Print("matrix_c:\n ", matrix_c, "\n");
/*
matrix_c:
[[4,3,2,1]
[8,6,4,2]
[12,9,6,3]
[16,12,8,4]
[20,15,10,5]]
*/
//--- create matrices as vectors
matrix matrix_a(5, 1);
matrix matrix_b(1, 4);
matrix_a.Col(vector_a, 0);
matrix_b.Row(vector_b, 0);
Print("matrix_a:\n ", matrix_a);
Print("matrix_b:\n ", matrix_b);
/*
matrix_a:
[[1]
[2]
[3]
[4]

© 2000-2025, MetaQuotes Ltd.


1367 Matrix and Vector Methods

[5]]
matrix_b:
[[4,3,2,1]]
*/
//-- calculate GeMM for two matrices and get the same result
matrix_c.GeMM(matrix_a, matrix_b, 1, 0);
Print("matrix_c:\n ", matrix_c);
/*
matrix_c:
[[4,3,2,1]
[8,6,4,2]
[12,9,6,3]
[16,12,8,4]
[20,15,10,5]]
*/
}

See also
MatMul

© 2000-2025, MetaQuotes Ltd.


1368 Matrix and Vector Methods

Power
R aise a s quare matrix to the integer power.
matrix matrix::Power(
const int power // power
);

Parameters
power
[in] The exponent can be any integer, positive, negative, or zero.

Return Value

Matrix.

Note

The resulting matrix has the same size as the original matrix. In raised to the power of 0, the
identity matrix is returned. The positive power n means that the original matrix is multiplied n
times by itself. The negative power -n means that the original matrix is first inverted, and then the
inverted matrix is multiplied by itself n times.

A simple algorithm for raising a matrix to a power in MQL5:

bool MatrixPower(matrix& c, const matrix& a, const int power)


{
//--- matrix must be square
if(a.Rows()!=a.Cols())
return(false);
//--- the size of the resulting matrix is exactly the same
ulong rows=a.Rows();
ulong cols=a.Cols();
matrix result(rows,cols);
//--- when raised to zero, return the identity matrix
if(power==0)
result.Identity();
else
{
//--- for a negative degree, first invert the matrix
if(power<0)
{
matrix inverted=a.Inv();
result=inverted;
for(int i=-1; i>power; i--)
result=result.MatMul(inverted);
}

© 2000-2025, MetaQuotes Ltd.


1369 Matrix and Vector Methods

else
{
result=a;
for(int i=1; i<power; i++)
result=result.MatMul(a);
}
}
//---
c=result;
return(true);
}

MQL5 example:

matrix i= {{0, 1}, {-1, 0}};


Print("i:\n", i);

Print("i.Power(3):\n", i.Power(3));

Print("i.Power(0):\n", i.Power(0));

Print("i.Power(-3):\n", i.Power(-3));

/*
i:
[[0,1]
[-1,0]]

i.Power(3):
[[0,-1]
[1,0]]

i.Power(0):
[[1,0]
[0,1]]

i.Power(-3):
[[0, -1]
[1,0]]
*/

Python example:

import numpy as np
from numpy.linalg import matrix_power

# matrix equiv. of the imaginary unit

© 2000-2025, MetaQuotes Ltd.


1370 Matrix and Vector Methods

i = np.array([[0, 1], [-1, 0]])


print("i:\n",i)

# should = -i
print("matrix_power(i, 3) :\n",matrix_power(i, 3) )

print("matrix_power(i, 0):\n",matrix_power(i, 0))

# should = 1/(-i) = i, but w/ f.p. elements


print("matrix_power(i, -3):\n",matrix_power(i, -3))

i:
[[ 0 1]
[-1 0]]

matrix_power(i, 3) :
[[ 0 -1]
[ 1 0]]

matrix_power(i, 0):
[[1 0]
[0 1]]

matrix_power(i, -3):
[[ 0. 1.]
[-1. 0.]]

© 2000-2025, MetaQuotes Ltd.


1371 Matrix and Vector Methods

Dot
Dot product of two vectors.
double vector::Dot(
const vector& b // second vector
);

Parameters
b
[in] Vector.

Return Value

S calar.

Note

The dot product of two matrices is the matrix product matrix::MatMul().

A simple algorithm for the scalar product of vectors in MQL5:

double VectorDot(const vector& vector_a, const vector& vector_b)


{
double dot=0;

if(vector_a.Size()==vector_b.Size())
{
for(ulong i=0; i<vector_a.Size(); i++)
dot+=vector_a[i]*vector_b[i];
}

return(dot);
}

MQL5 example:

for(ulong i=0; i<rows; i++)


{
vector v1=a.Row(i);
for(ulong j=0; j<cols; j++)
{
vector v2=b.Row(j);
result[i][j]=v1.Dot(v2);
}
}

© 2000-2025, MetaQuotes Ltd.


1372 Matrix and Vector Methods

Python example:

import numpy as np

a = [1, 0, 0, 1]
b = [4, 1, 2, 2]
print(np.dot(a, b))

>>> 6

© 2000-2025, MetaQuotes Ltd.


1373 Matrix and Vector Methods

Kron
R eturn Kroneck er product of two matrices, matrix and vector, vector and matrix or two vectors.
matrix matrix::Kron(
const matrix& b // second matrix
);

matrix matrix::Kron(
const vector& b // vector
);

matrix vector::Kron(
const matrix& b // matrix
);

matrix vector::Kron(
const vector& b // second vector
);

Parameters
b
[in] second matrix.

Return Value

Matrix.

Note

The Kronecker product is also referred to as the block matrix multiplication.

A simple algorithm for the Kronecker product for two matrices in MQL5:

matrix MatrixKronecker(const matrix& matrix_a,const matrix& matrix_b)


{
ulong M=matrix_a.Rows();
ulong N=matrix_a.Cols();
ulong P=matrix_b.Rows();
ulong Q=matrix_b.Cols();
matrix matrix_c(M*P,N*Q);

for(ulong m=0; m<M; m++)


for(ulong n=0; n<N; n++)
for(ulong p=0; p<P; p++)
for(ulong q=0; q<Q; q++)

© 2000-2025, MetaQuotes Ltd.


1374 Matrix and Vector Methods

matrix_c[m*P+p][n*Q+q]=matrix_a[m][n] * matrix_b[p][q];

return(matrix_c);
}

MQL5 example:

matrix a={{1,2,3},{4,5,6}};
matrix b=matrix::Identity(2,2);
vector v={1,2};

Print(a.Kron(b));
Print(a.Kron(v));

/*
[[1,0,2,0,3,0]
[0,1,0,2,0,3]
[4,0,5,0,6,0]
[0,4,0,5,0,6]]

[[1,2,2,4,3,6]
[4,8,5,10,6,12]]
*/

Python example:

import numpy as np

A = np.arange(1,7).reshape(2,3)
B = np.identity(2)
V = [1,2]
print(np.kron(A, B))
print("")
print(np.kron(A, V))

[[1. 0. 2. 0. 3. 0.]
[0. 1. 0. 2. 0. 3.]
[4. 0. 5. 0. 6. 0.]
[0. 4. 0. 5. 0. 6.]]

[[ 1 2 2 4 3 6]
[ 4 8 5 10 6 12]]

© 2000-2025, MetaQuotes Ltd.


1375 Matrix and Vector Methods

Inner
Inner product of two matrices.
matrix matrix::Inner(
const matrix& b // second matrix
);

Parameters
b
[in] Matrix.

Return Value

Matrix.
Note

The inner product for two vectors is the dot product of the two vectors vector::Dot().

A simple algorithm for the inner product of two matrices in MQL5:

bool MatrixInner(matrix& c, const matrix& a, const matrix& b)


{
//--- the number of columns must equal
if(a.Cols()!=b.Cols())
return(false);
//--- size of the resulting matrix depends on the number of vectors in each of the matrices
ulong rows=a.Rows();
ulong cols=b.Rows();
matrix result(rows,cols);
//---
for(ulong i=0; i<rows; i++)
{
vector v1=a.Row(i);
for(ulong j=0; j<cols; j++)
{
vector v2=b.Row(j);
result[i][j]=v1.Dot(v2);
}
}
//---
c=result;
return(true);
}

MQL5 example:

© 2000-2025, MetaQuotes Ltd.


1376 Matrix and Vector Methods

matrix a={{0,1,2},{3,4,5}};
matrix b={{0,1,2},{3,4,5},{6,7,8}};
matrix c=a.Inner(b);
Print(c);
matrix a1={{0,1,2}};
matrix c1=a1.Inner(b);
Print(c1);

/*
[[5,14,23]
[14,50,86]]
[[5,14,23]]
*/

Python example:

import numpy as np

A = np.arange(6).reshape(2, 3)
B = np.arange(9).reshape(3, 3)
A1= np.arange(3)
print(np.inner(A, B))
print("");
print(np.inner(A1, B))

import numpy as np

A = np.arange(6).reshape(2, 3)
B = np.arange(9).reshape(3, 3)
A1= np.arange(3)
print(np.inner(A, B))
print("");
print(np.inner(A1, B))

© 2000-2025, MetaQuotes Ltd.


1377 Matrix and Vector Methods

Outer
Compute the outer product of two matrices or two vectors.
matrix matrix::Outer(
const matrix& b // second matrix
);

matrix vector::Outer(
const vector& b // second vector
);

Parameters
b
[in] Matrix.

Return Value

Matrix.

Note

The outer product, like the Kronecker product, is also a block matrix (and vector) multiplication.

A simple algorithm for the outer product of two matrices in MQL5:

matrix MatrixOuter(const matrix& matrix_a, const matrix& matrix_b)


{
//--- size of the resulting matrix depends on the matrix sizes
ulong rows=matrix_a.Rows()*matrix_a.Cols();
ulong cols=matrix_b.Rows()*matrix_b.Cols();
matrix matrix_c(rows,cols);
ulong cols_a=matrix_a.Cols();
ulong cols_b=matrix_b.Cols();
//---
for(ulong i=0; i<rows; i++)
{
ulong row_a=i/cols_a;
ulong col_a=i%cols_a;
for(ulong j=0; j<cols; j++)
{
ulong row_b=j/cols_b;
ulong col_b=j%cols_b;
matrix_c[i][j]=matrix_a[row_a][col_a] * matrix_b[row_b][col_b];
}
}

© 2000-2025, MetaQuotes Ltd.


1378 Matrix and Vector Methods

//---
return(matrix_c);
}

MQL5 example:

vector vector_a={0,1,2,3,4,5};
vector vector_b={0,1,2,3,4,5,6};
Print("vector_a.Outer\n",vector_a.Outer(vector_b));
Print("vector_a.Kron\n",vector_a.Kron(vector_b));

matrix matrix_a={{0,1,2},{3,4,5}};
matrix matrix_b={{0,1,2},{3,4,5},{6,7,8}};
Print("matrix_a.Outer\n",matrix_a.Outer(matrix_b));
Print("matrix_a.Kron\n",matrix_a.Kron(matrix_b));

/*
vector_a.Outer
[[0,0,0,0,0,0,0]
[0,1,2,3,4,5,6]
[0,2,4,6,8,10,12]
[0,3,6,9,12,15,18]
[0,4,8,12,16,20,24]
[0,5,10,15,20,25,30]]
vector_a.Kron
[[0,0,0,0,0,0,0,0,1,2,3,4,5,6,0,2,4,6,8,10,12,0,3,6,9,12,15,18,0,4,8,12,16,20,24,0,5,10,15,20,25
matrix_a.Outer
[[0,0,0,0,0,0,0,0,0]
[0,1,2,3,4,5,6,7,8]
[0,2,4,6,8,10,12,14,16]
[0,3,6,9,12,15,18,21,24]
[0,4,8,12,16,20,24,28,32]
[0,5,10,15,20,25,30,35,40]]
matrix_a.Kron
[[0,0,0,0,1,2,0,2,4]
[0,0,0,3,4,5,6,8,10]
[0,0,0,6,7,8,12,14,16]
[0,3,6,0,4,8,0,5,10]
[9,12,15,12,16,20,15,20,25]
[18,21,24,24,28,32,30,35,40]]
*/

Python example:

import numpy as np

A = np.arange(6)

© 2000-2025, MetaQuotes Ltd.


1379 Matrix and Vector Methods

B = np.arange(7)
print("np.outer")
print(np.outer(A, B))
print("np.kron")
print(np.kron(A, B))

A = np.arange(6).reshape(2, 3)
B = np.arange(9).reshape(3, 3)
print("np.outer")
print(np.outer(A, B))
print("np.kron")

np.outer
[[ 0 0 0 0 0 0 0]
[ 0 1 2 3 4 5 6]
[ 0 2 4 6 8 10 12]
[ 0 3 6 9 12 15 18]
[ 0 4 8 12 16 20 24]
[ 0 5 10 15 20 25 30]]
np.kron
[ 0 0 0 0 0 0 0 0 1 2 3 4 5 6 0 2 4 6 8 10 12 0 3 6
9 12 15 18 0 4 8 12 16 20 24 0 5 10 15 20 25 30]
np.outer
[[ 0 0 0 0 0 0 0 0 0]
[ 0 1 2 3 4 5 6 7 8]
[ 0 2 4 6 8 10 12 14 16]
[ 0 3 6 9 12 15 18 21 24]
[ 0 4 8 12 16 20 24 28 32]
[ 0 5 10 15 20 25 30 35 40]]
np.kron
[[ 0 0 0 0 1 2 0 2 4]
[ 0 0 0 3 4 5 6 8 10]
[ 0 0 0 6 7 8 12 14 16]
[ 0 3 6 0 4 8 0 5 10]
[ 9 12 15 12 16 20 15 20 25]
[18 21 24 24 28 32 30 35 40]]

© 2000-2025, MetaQuotes Ltd.


1380 Matrix and Vector Methods

CorrCoef
Compute the Pearson correlation coefficient (linear correlation coefficient).
matrix matrix::CorrCoef(
const bool rowvar=true // rows or cols vectors of observations
);

scalar vector::CorrCoef(
const vector& b // second vector
);

Return Value

Pearson product-moment correlation coefficients.

Note

The correlation coefficient is in the range [-1, 1].


Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may
not be 1, and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts
are clipped to the interval [-1, 1] in an attempt to improve on that situation but is not much help in
the complex case.

A simple algorithm for calculating the correlation coefficient of two vectors using MQL5:

double VectorCorrelation(const vector& vector_x,const vector& vector_y)


{
ulong n=vector_x.Size()<vector_y.Size() ? vector_x.Size() : vector_y.Size();
if(n<=1)
return(0);

ulong i;
double xmean=0;
double ymean=0;
for(i=0; i<n; i++)
{
if(!MathIsValidNumber(vector_x[i]))
return(0);
if(!MathIsValidNumber(vector_y[i]))
return(0);
xmean+=vector_x[i];
ymean+=vector_y[i];
}
xmean/=(double)n;
ymean/=(double)n;

© 2000-2025, MetaQuotes Ltd.


1381 Matrix and Vector Methods

double s=0;
double xv=0;
double yv=0;
double t1=0;
double t2=0;
//--- calculation
s=0;
for(i=0; i<n; i++)
{
t1=vector_x[i]-xmean;
t2=vector_y[i]-ymean;
xv+=t1*t1;
yv+=t2*t2;
s+=t1*t2;
}
//--- check
if(xv==0 || yv==0)
return(0);
//--- return result
return(s/(MathSqrt(xv)*MathSqrt(yv)));
}

MQL5 example:

vectorf vector_a={1,2,3,4,5};
vectorf vector_b={0,1,0.5,2,2.5};
Print("vectors correlation ",vector_a.CorrCoef(vector_b));
//---
matrixf matrix_a={{1,2,3,4,5},
{0,1,0.5,2,2.5}};
Print("matrix rows correlation\n",matrix_a.CorrCoef());
matrixf matrix_a2=matrix_a.Transpose();
Print("transposed matrix cols correlation\n",matrix_a2.CorrCoef(false));
matrixf matrix_a3={{1.0f, 2.0f, 3.0f, 4.0f, 5.0f},
{0.0f, 1.0f, 0.5f, 2.0f, 2.5f},
{0.1f, 1.0f, 2.0f, 1.0f, 0.3f}};
Print("rows correlation\n",matrix_a3.CorrCoef());
Print("cols correlation\n",matrix_a3.CorrCoef(false));

/*
vectors correlation 0.9149913787841797
matrix rows correlation
[[1,0.91499138]
[0.91499138,1]]
transposed matrix cols correlation
[[1,0.91499138]
[0.91499138,1]]

© 2000-2025, MetaQuotes Ltd.


1382 Matrix and Vector Methods

rows correlation
[[1,0.91499138,0.08474271]
[0.91499138,1,-0.17123166]
[0.08474271,-0.17123166,1]]
cols correlation
[[1,0.99587059,0.85375023,0.91129309,0.83773589]
[0.99587059,1,0.80295509,0.94491106,0.88385159]
[0.85375023,0.80295509,1,0.56362146,0.43088508]
[0.91129309,0.94491106,0.56362146,1,0.98827404]
[0.83773589,0.88385159,0.43088508,0.98827404,1]]
*/

Python example:

import numpy as np
va=[1,2,3,4,5]
vb=[0,1,0.5,2,2.5]
print("vectors correlation")
print(np.corrcoef(va,vb))

ma=np.zeros((2,5))
ma[0,:]=va
ma[1,:]=vb
print("matrix rows correlation")
print(np.corrcoef(ma))
print("transposed matrix cols correlation")
print(np.corrcoef(np.transpose(ma),rowvar=False))
print("")

ma1=[[1,2,3,4,5],[0,1,0.5,2,2.5],[0.1,1,0.2,1,0.3]]
print("rows correlation\n",np.corrcoef(ma1))
print("cols correlation\n",np.corrcoef(ma1,rowvar=False))

transposed matrix cols correlation


[[1. 0.91499142]
[0.91499142 1. ]]

rows correlation
[[1. 0.91499142 0.1424941 ]
[0.91499142 1. 0.39657517]
[0.1424941 0.39657517 1. ]]
cols correlation
[[1. 0.99587059 0.98226063 0.91129318 0.83773586]
[0.99587059 1. 0.99522839 0.94491118 0.88385151]
[0.98226063 0.99522839 1. 0.97234063 0.92527551]
[0.91129318 0.94491118 0.97234063 1. 0.98827406]
[0.83773586 0.88385151 0.92527551 0.98827406 1. ]]

© 2000-2025, MetaQuotes Ltd.


1383 Matrix and Vector Methods

© 2000-2025, MetaQuotes Ltd.


1384 Matrix and Vector Methods

Cov
Compute the covariance matrix.
matrix matrix::Cov(
const bool rowvar=true // rows or cols vectors of observations
);

matrix vector::Cov(
const vector& b // second vector
);

Parameters
b
[in] S econd vector.

Note

Compute the covariance matrix.

A simple algorithm for calculating the covariance matrix of two vectors using MQL5:

bool VectorCovariation(const vector& vector_a,const vector& vector_b,matrix& matrix_c)


{
int i,j;
int m=2;
int n=(int)(vector_a.Size()<vector_b.Size()?vector_a.Size():vector_b.Size());
//--- checks
if(n<=1)
return(false);
for(i=0; i<n; i++)
{
if(!MathIsValidNumber(vector_a[i]))
return(false);
if(!MathIsValidNumber(vector_b[i]))
return(false);
}
//---
matrix matrix_x(2,n);
matrix_x.Row(vector_a,0);
matrix_x.Row(vector_b,1);
vector t=vector::Zeros(m);
//--- calculation
for(i=0; i<m; i++)
for(j=0; j<n; j++)
t[i]+=matrix_x[i][j]/double(n);
for(i=0; i<m; i++)
for(j=0; j<n; j++)

© 2000-2025, MetaQuotes Ltd.


1385 Matrix and Vector Methods

matrix_x[i][j]-=t[i];
//--- syrk C=alpha*A^H*A+beta*C (beta=0 and not considered)
matrix_c=matrix::Zeros(m,m);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
double v=matrix_x[i][j]/(n-1);
for(int i_=i; i_<m; i_++)
matrix_c[i][i_]+=v*matrix_x[i_][j];
}
}
//--- force symmetricity
for(i=0; i<m-1; i++)
for(j=i+1; j<m; j++)
matrix_c[j][i]=matrix_c[i][j];
//---
return(true);
}

MQL5 example:

matrix matrix_a={{3,-2.1},{1.1,-1},{0.12,4.3}};
Print("covariation cols\n",matrix_a.Cov(false));
Print("covariation rows\n",matrix_a.Cov());

vector vector_a=matrix_a.Col(0);
vector vector_b=matrix_a.Col(1);
Print("covariation vectors\n",vector_a.Cov(vector_b));

/*
covariation cols
[[2.144133333333333,-4.286]
[-4.286,11.71]]
covariation rows
[[13.005,5.355,-10.659]
[5.355,2.205,-4.389]
[-10.659,-4.389,8.736199999999998]]
covariation vectors
[[2.144133333333333,-4.286]
[-4.286,11.71]]
*/

Python example:

import numpy as np
matrix_a=np.array([[3,-2.1],[1.1,-1],[0.12,4.3]])

© 2000-2025, MetaQuotes Ltd.


1386 Matrix and Vector Methods

matrix_c=np.cov(matrix_a,rowvar=False)
print("covariation cols\n",matrix_c)
matrix_c2=np.cov(matrix_a)
print("covariation rows\n",matrix_c2)

vector_a=matrix_a[:,0]
vector_b=matrix_a[:,1]
matrix_c3=np.cov(vector_a,vector_b)
print("covariation vectors\n",matrix_c3)

covariation cols
[[ 2.14413333 -4.286 ]
[-4.286 11.71 ]]
covariation rows
[[ 13.005 5.355 -10.659 ]
[ 5.355 2.205 -4.389 ]
[-10.659 -4.389 8.7362]]
covariation vectors
[[ 2.14413333 -4.286 ]
[-4.286 11.71 ]]

© 2000-2025, MetaQuotes Ltd.


1387 Matrix and Vector Methods

Correlate
Compute the cross-correlation of two vectors.
vector vector::Correlate(
const vector& v, // vector
ENUM_VECTOR_CONVOLVE mode // mode
);

Parameters
v
[in] S econd vector.

mode
[in] The 'mode' parameter determines the linear convolution calculation mode. Value from the
ENUM _VECTOR_CONVOL VE enumeration.

Return Value

Cross-correlation of two vectors.


Note

The 'mode' parameter determines the linear convolution calculation mode.

A simple algorithm for calculating the correlation coefficient of two vectors using MQL5:

vector VectorCrossCorrelationFull(const vector& a,const vector& b)


{
int m=(int)a.Size();
int n=(int)b.Size();
int size=m+n-1;
vector c=vector::Zeros(size);

for(int i=0; i<n; i++)


for(int i_=i; i_<i+m; i_++)
c[i_]+=b[n-i-1]*a[i_-i];

return(c);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
vector VectorCrossCorrelationSame(const vector& a,const vector& b)
{
int m=(int)a.Size();
int n=(int)b.Size();
int size=MathMax(m,n);
vector c=vector::Zeros(size);

© 2000-2025, MetaQuotes Ltd.


1388 Matrix and Vector Methods

for(int i=0; i<n; i++)


{
for(int i_=i; i_<i+m; i_++)
{
int k=i_-size/2+1;
if(k>=0 && k<size)
c[k]+=b[n-i-1]*a[i_-i];
}
}

return(c);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
vector VectorCrossCorrelationValid(const vector& a,const vector& b)
{
int m=(int)a.Size();
int n=(int)b.Size();
int size=MathMax(m,n)-MathMin(m,n)+1;
vector c=vector::Zeros(size);

for(int i=0; i<n; i++)


{
for(int i_=i; i_<i+m; i_++)
{
int k=i_-n+1;
if(k>=0 && k<size)
c[k]+=b[n-i-1]*a[i_-i];
}
}

return(c);
}

MQL5 example:

vector a={1,2,3,4,5};
vector b={0,1,0.5};

Print("full\n",a.Correlate(b,VECTOR_CONVOLVE_FULL));
Print("same\n",a.Correlate(b,VECTOR_CONVOLVE_SAME));
Print("valid\n",a.Correlate(b,VECTOR_CONVOLVE_VALID));
Print("full\n",b.Correlate(a,VECTOR_CONVOLVE_FULL));

/*
full

© 2000-2025, MetaQuotes Ltd.


1389 Matrix and Vector Methods

[0.5,2,3.5,5,6.5,5,0]
same
[2,3.5,5,6.5,5]
valid
[3.5,5,6.5]
full
[0,5,6.5,5,3.5,2,0.5]
*/

Python example:

import numpy as np
a=[1,2,3,4,5]
b=[0,1,0.5]

print("full\n",np.correlate(a,b,'full'))
print("same\n",np.correlate(a,b,'same'));
print("valid\n",np.correlate(a,b,'valid'));
print("full\n",np.correlate(b,a,'full'))

full
[0.5 2. 3.5 5. 6.5 5. 0. ]
same
[2. 3.5 5. 6.5 5. ]
valid
[3.5 5. 6.5]
full
[0. 5. 6.5 5. 3.5 2. 0.5]

© 2000-2025, MetaQuotes Ltd.


1390 Matrix and Vector Methods

Convolve
R eturn the discrete, linear convolution of two vectors
vector vector::Convolve(
const vector& v, // vector
ENUM_VECTOR_CONVOLVE mode // mode
);

Parameters
v
[out] S econd vector.

mode
[in] The 'mode' parameter determines the linear convolution calculation mode
ENUM _VECTOR_CONVOL VE.

Return Value

Discrete, linear convolution of two vectors.

A simple algorithm for calculating the convolution of two vectors in MQL5:

vector VectorConvolutionFull(const vector& a,const vector& b)


{
if(a.Size()<b.Size())
return(VectorConvolutionFull(b,a));

int m=(int)a.Size();
int n=(int)b.Size();
int size=m+n-1;
vector c=vector::Zeros(size);

for(int i=0; i<n; i++)


for(int i_=i; i_<i+m; i_++)
c[i_]+=b[i]*a[i_-i];

return(c);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
vector VectorConvolutionSame(const vector& a,const vector& b)
{
if(a.Size()<b.Size())
return(VectorConvolutionSame(b,a));

int m=(int)a.Size();
int n=(int)b.Size();

© 2000-2025, MetaQuotes Ltd.


1391 Matrix and Vector Methods

int size=MathMax(m,n);
vector c=vector::Zeros(size);

for(int i=0; i<n; i++)


{
for(int i_=i; i_<i+m; i_++)
{
int k=i_-size/2+1;
if(k>=0 && k<size)
c[k]+=b[i]*a[i_-i];
}
}

return(c);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
vector VectorConvolutionValid(const vector& a,const vector& b)
{
if(a.Size()<b.Size())
return(VectorConvolutionValid(b,a));

int m=(int)a.Size();
int n=(int)b.Size();
int size=MathMax(m,n)-MathMin(m,n)+1;
vector c=vector::Zeros(size);

for(int i=0; i<n; i++)


{
for(int i_=i; i_<i+m; i_++)
{
int k=i_-n+1;
if(k>=0 && k<size)
c[k]+=b[i]*a[i_-i];
}
}

return(c);
}

MQL5 example:

vector a= {1, 2, 3, 4, 5};


vector b= {0, 1, 0.5};

Print("full\n", a.Convolve(b, VECTOR_CONVOLVE_FULL));


Print("same\n", a.Convolve(b, VECTOR_CONVOLVE_SAME));

© 2000-2025, MetaQuotes Ltd.


1392 Matrix and Vector Methods

Print("valid\n", a.Convolve(b, VECTOR_CONVOLVE_VALID));

/*
full
[0,1,2.5,4,5.5,7,2.5]
same
[1,2.5,4,5.5,7]
valid
[2.5,4,5.5]
*/

Python example:

import numpy as np
a=[1,2,3,4,5]
b=[0,1,0.5]

print("full\n",np.convolve(a,b,'full'))
print("same\n",np.convolve(a,b,'same'));
print("valid\n",np.convolve(a,b,'valid'));

full
[0. 1. 2.5 4. 5.5 7. 2.5]
same
[1. 2.5 4. 5.5 7. ]
valid
[2.5 4. 5.5]

© 2000-2025, MetaQuotes Ltd.


1393 Matrix and Vector Methods

Matrix transformations
Matrix decomposition can be used in the following cases :
· as an intermediate step when solving systems of linear equations
· for matrix inversion
· when calculating determinants
· when finding eigenvalues and eigenvectors of a matrix
· when computing analytic functions of matrices
· when using the least s quares method
· in the numerical solution of differential equations
Different matrix decomposition types are used depending on the problem.

Function Action

Choles ky Computes the Choles ky decomposition


Eig Computes the eigenvalues and right eigenvectors of a s quare matrix
Eig Vals Computes the eigenvalues of a general matrix
LU LU factorization of a matrix as the product of a lower triangular
matrix and an upper triangular matrix
LUP LUP factorization with partial pivoting, which refers to LU
decomposition with row permutations only: PA=LU
QR Compute the qr factorization of a matrix
SVD S ingular Value Decomposition

© 2000-2025, MetaQuotes Ltd.


1394 Matrix and Vector Methods

Cholesky
Compute the Choles ky decomposition.
bool matrix::Cholesky(
matrix& L // matrix
);

Parameters
L key
[out] Lower triangular matrix.

Return Value

R eturns true on success, false otherwise.

Note

R eturn the Choles k y decomposition, L * L.H , of the s quare matrix a, where L is lower-triangular and
.H is the conjugate transpose operator (which is the ordinary transpose if a is real-valued). a must
be Hermitian (symmetric if real-valued) and positive-definite. No checking is performed to verify
whether a is Hermitian or not. In addition, only the lower-triangular and diagonal elements of a are
used. Only L is actually returned.

Example

matrix matrix_a= {{5.7998084, -2.1825367}, {-2.1825367, 9.85910595}};


matrix matrix_l;
Print("matrix_a\n", matrix_a);

matrix_a.Cholesky(matrix_l);
Print("matrix_l\n", matrix_l);
Print("check\n", matrix_l.MatMul(matrix_l.Transpose()));

/*
matrix_a
[[5.7998084,-2.1825367]
[-2.1825367,9.85910595]]
matrix_l
[[2.408279136645086,0]
[-0.9062640068544704,3.006291985133859]]
check
[[5.7998084,-2.1825367]
[-2.1825367,9.85910595]]
*/

© 2000-2025, MetaQuotes Ltd.


1395 Matrix and Vector Methods

Eig
Compute the eigenvalues and right eigenvectors of a s quare matrix.
bool matrix::Eig(
matrix& eigen_vectors, // matrix of eigenvectors
vector& eigen_values // vector of eigenvalues
);

Complex solution of eigenvalues and eigenvectors


bool matrix::Eig(
matrix<complex>& eigen_vectors, // matrix of eigenvectors
vector<complex>& eigen_values // vector of eigenvalues
);

Parameters
eigen_vectors
[out] Matrix of vertical eigenvectors.
eigen_values
[out] Vector of eigenvalues.

Return Value

R eturns true on success, false otherwise.


Note

If a complex solution is encountered when calculating eigenvalues, the calculation is stopped and the
error code is set to 4019 (ERR_M ATH_OVERFLOW ). Use the complex overload of the Eig method to
obtain a complete solution in complex space
If a complex eigenvalue has an imaginary part equal to zero, then it is a real eigenvalue. This can be
seen in the example below.
Example

void OnStart()
{
matrix matrix_a =
{
{-3.474589, 1.106384, -9.091977,-3.925227 },
{-5.522139, 2.366887,-15.162351,-6.357512 },
{ 8.394926,-2.960067, 22.292115, 9.524129 },
{ 7.803242,-2.080287, 19.217706, 8.186645 }
};

matrix eigen_vectors;
vector eigen_values;

bool res=matrix_a.Eig(eigen_vectors, eigen_values);

© 2000-2025, MetaQuotes Ltd.


1396 Matrix and Vector Methods

Print("res=",res," error=",GetLastError());
Print("Eigen vectors:\n",eigen_vectors, "\nEigen Values:\n",eigen_values);

//--- check correctness A * v = lambda * v


int vectors=0;
for(ulong n=0; n<eigen_values.Size(); n++)
{
vector eigen_vector=eigen_vectors.Col(n);
vector vector_d1 =eigen_vector*eigen_values[n];
vector vector_d2 =matrix_a.MatMul(eigen_vector);

ulong errors=vector_d1.Compare(vector_d2,1e-13);
if(errors==0)
vectors++;
}
Print("vectors=",vectors);

//--- complex solution


matrix<complex> eigen_vectors_c;
vector<complex> eigen_values_c;
ResetLastError();
res=matrix_a.Eig(eigen_vectors_c,eigen_values_c);
Print("res=",res," error=",GetLastError());
Print("Eigen vectors:\n",eigen_vectors_c, "\nEigen Values:\n",eigen_values_c);

//--- check correctness A * v = lambda * v


matrixc matrix_c;
matrix_c.Assign(matrix_a);
vectors=0;
for(ulong n=0; n<eigen_values_c.Size(); n++)
{
vectorc eigen_vector_c=eigen_vectors_c.Col(n);
vectorc vector_c1 =eigen_vector_c*eigen_values_c[n];
vectorc vector_c2 =matrix_c.MatMul(eigen_vector_c);

ulong errors=vector_c1.Compare(vector_c2,1e-13);
if(errors==0)
vectors++;
}
Print("vectors=",vectors);
}
/* Result
res=true error=4019
Eigen vectors:
[[0.2649667608713664]
[0.4488818803991876]
[-0.6527335897527492]
[-0.5497604331807768]]
Eigen Values:

© 2000-2025, MetaQuotes Ltd.


1397 Matrix and Vector Methods

[28.94158645962942]
vectors=1
res=true error=0
Eigen vectors:
[[(0.2649667608713664,0),(0.2227392219204762,0.3745470492013296),(0.403285439089771,-0.134514613
[(0.4488818803991876,0),(-0.2613452530342438,-0.3685707727819327),(-0.3968506126372395,0.525700
[(-0.6527335897527492,0),(-0.3418479634708521,-0.3299830378162041),(-0.3553021031180292,-0.0368
[(-0.5497604331807768,0),(0.523227993452828,0.3262508584080381),(0.3512835596143666,0.366630035
Eigen Values:
[(28.94158645962942,0),(0.01022501104810897,0.02954980822331488),(0.01022501104810897,-0.0295498
vectors=3
*/

© 2000-2025, MetaQuotes Ltd.


1398 Matrix and Vector Methods

EigVals
Compute the eigenvalues of a general matrix.
bool matrix::EigVals(
vector& eigen_values // vector of eigenvalues
);

Parameters
eigen_values
[out] Vector of right eigenvalues.

Return Value

R eturns true on success, false otherwise.

Note

The only difference between EigVals and Eig is that EigVals does not calculate eigenvectors, while it
only calculates eigenvalues.

© 2000-2025, MetaQuotes Ltd.


1399 Matrix and Vector Methods

LU
LU factorization of a matrix as the product of a lower triangular matrix and an upper triangular
matrix.
bool matrix::LU(
matrix& L, // lower triangular matrix
matrix& U // upper triangular matrix
);

Parameters
L key
[out] Lower triangular matrix.
U
[out] Upper triangular matrix.

Return Value

R eturns true on success, false otherwise.

Example

matrix matrix_a={{1,2,3,4},
{5,2,6,7},
{8,9,3,10},
{11,12,14,4}};
matrix matrix_l,matrix_u;
//--- LU decomposition
matrix_a.LU(matrix_l,matrix_u);
Print("matrix_l\n",matrix_l);
Print("matrix_u\n",matrix_u);
//--- check if A = L * U
Print("check\n",matrix_l.MatMul(matrix_u));

/*
matrix_l
[[1,0,0,0]
[5,1,0,0]
[8,0.875,1,0]
[11,1.25,0.5904761904761905,1]]
matrix_u
[[1,2,3,4]
[0,-8,-9,-13]
[0,0,-13.125,-10.625]
[0,0,0,-17.47619047619047]]
check
[[1,2,3,4]

© 2000-2025, MetaQuotes Ltd.


1400 Matrix and Vector Methods

[5,2,6,7]
[8,9,3,10]
[11,12,14,4]]
*/

© 2000-2025, MetaQuotes Ltd.


1401 Matrix and Vector Methods

LUP
LUP factorization with partial pivoting, which refers to LU decomposition with row permutations only:
PA=LU.
bool LUP(
matrix& L, // lower triangular matrix
matrix& U, // upper triangular matrix
matrix& P // permutations matrix
);

Parameters
L key
[out] Lower triangular matrix.
U
[out] Upper triangular matrix.
P
[out] Permutations matrix

Return Value

R eturns true on success, false otherwise.

Example

matrix matrix_a={{1,2,3,4},
{5,2,6,7},
{8,9,3,10},
{11,12,14,4}};
matrix matrix_l,matrix_u,matrix_p;
//--- LUP decomposition
matrix_a.LUP(matrix_l,matrix_u,matrix_p);
Print("matrix_l\n",matrix_l);
Print("matrix_u\n",matrix_u);
Print("matrix_p\n",matrix_p);
//--- check if P * A = L * U
Print("P * A\n",matrix_p.MatMul(matrix_a));
Print("L * U\n",matrix_l.MatMul(matrix_u));

/*
matrix_l
[[1,0,0,0]
[0.4545454545454545,1,0,0]
[0.7272727272727273,-0.07894736842105282,1,0]
[0.09090909090909091,-0.2631578947368421,-0.2262773722627738,1]]
matrix_u
[[11,12,14,4]

© 2000-2025, MetaQuotes Ltd.


1402 Matrix and Vector Methods

[0,-3.454545454545454,-0.3636363636363633,5.181818181818182]
[0,0,-7.210526315789473,7.500000000000001]
[0,0,0,6.697080291970803]]
matrix_p
[[0,0,0,1]
[0,1,0,0]
[0,0,1,0]
[1,0,0,0]]
P * A
[[11,12,14,4]
[5,2,6,7]
[8,9,3,10]
[1,2,3,4]]
L * U
[[11,12,14,4]
[5,2,6,7]
[8,9,3.000000000000001,10]
[1,2,3,4]]
*/

© 2000-2025, MetaQuotes Ltd.


1403 Matrix and Vector Methods

QR
Compute the qr factorization of a matrix.
bool QR(
matrix& Q, // matrix with orthonormal columns
matrix& R // upper-triangular matrix
);

Parameters
Q
[out] A matrix with orthonormal columns. W hen mode = 'complete' the result is an
orthogonal/unitary matrix depending on whether or not a is real/complex. The determinant may
be either +/- 1 in that case. In case the number of dimensions in the input array is greater than 2
then a stack of the matrices with above properties is returned.
R key
[out] Upper triangular matrix.

Return Value

R eturns true on success, false otherwise.

Example

//--- A*x = b
matrix A = {{0, 1}, {1, 1}, {1, 1}, {2, 1}};
Print("A \n", A);
vector b = {1, 2, 2, 3};
Print("b \n", b);
//--- A = Q*R
matrix q, r;
A.QR(q, r);
Print("q \n", q);
Print("r \n", r);
matrix qr=q.MatMul(r);
Print("qr \n", qr);
/*
A
[[0,1]
[1,1]
[1,1]
[2,1]]
b
[1,2,2,3]
q
[[0.4082482904638631,-0.8164965809277259,-1.110223024625157e-16,-0.4082482904638631]
[0.4625425214347352,-0.03745747856526496,0.7041241452319315,0.5374574785652647]
[-0.5374574785652648,-0.03745747856526496,0.7041241452319316,-0.4625425214347352]

© 2000-2025, MetaQuotes Ltd.


1404 Matrix and Vector Methods

[-0.5749149571305296,-0.5749149571305299,-0.09175170953613698,0.5749149571305296]]
r
[[-1.224744871391589,-0.2415816237971962]
[-1.22474487139159,-1.466326495188786]
[1.224744871391589,1.316496580927726]
[1.224744871391589,0.2415816237971961]]
qr
[[-1.110223024625157e-16,1]
[1,0.9999999999999999]
[1,1]
[2,1]]
*/

© 2000-2025, MetaQuotes Ltd.


1405 Matrix and Vector Methods

SVD
S ingular Value Decomposition.

bool matrix::SVD(
matrix& U, // unitary matrix
matrix& V, // unitary matrix
vector& singular_values // singular values vector
);

Parameters
U
[out] Unitary matrix of order m, consisting of left singular vectors.
V
[out] Unitary matrix of order n, consisting of right singular vectors.
singular_values
[out] S ingular values

Return Value

R eturns true on success, false otherwise.

Example

matrix a= {{0, 1, 2, 3, 4, 5, 6, 7, 8}};


a=a-4;
Print("matrix a \n", a);
a.Reshape(3, 3);
matrix b=a;
Print("matrix b \n", b);
//--- execute SVD decomposition
matrix U, V;
vector singular_values;
b.SVD(U, V, singular_values);
Print("U \n", U);
Print("V \n", V);
Print("singular_values = ", singular_values);

// check block
//--- U * singular diagonal * V = A
matrix matrix_s;
matrix_s.Diag(singular_values);
Print("matrix_s \n", matrix_s);
matrix matrix_vt=V.Transpose();
Print("matrix_vt \n", matrix_vt);
matrix matrix_usvt=(U.MatMul(matrix_s)).MatMul(matrix_vt);
Print("matrix_usvt \n", matrix_usvt);

© 2000-2025, MetaQuotes Ltd.


1406 Matrix and Vector Methods

ulong errors=(int)b.Compare(matrix_usvt, 1e-9);


double res=(errors==0);
Print("errors=", errors);

//---- another check


matrix U_Ut=U.MatMul(U.Transpose());
Print("U_Ut \n", U_Ut);
Print("Ut_U \n", (U.Transpose()).MatMul(U));

matrix vt_V=matrix_vt.MatMul(V);
Print("vt_V \n", vt_V);
Print("V_vt \n", V.MatMul(matrix_vt));

/*
matrix a
[[-4,-3,-2,-1,0,1,2,3,4]]
matrix b
[[-4,-3,-2]
[-1,0,1]
[2,3,4]]
U
[[-0.7071067811865474,0.5773502691896254,0.408248290463863]
[-6.827109697437648e-17,0.5773502691896253,-0.8164965809277256]
[0.7071067811865472,0.5773502691896255,0.4082482904638627]]
V
[[0.5773502691896258,-0.7071067811865474,-0.408248290463863]
[0.5773502691896258,1.779939029415334e-16,0.8164965809277258]
[0.5773502691896256,0.7071067811865474,-0.408248290463863]]
singular_values = [7.348469228349533,2.449489742783175,3.277709923350408e-17]

matrix_s
[[7.348469228349533,0,0]
[0,2.449489742783175,0]
[0,0,3.277709923350408e-17]]
matrix_vt
[[0.5773502691896258,0.5773502691896258,0.5773502691896256]
[-0.7071067811865474,1.779939029415334e-16,0.7071067811865474]
[-0.408248290463863,0.8164965809277258,-0.408248290463863]]
matrix_usvt
[[-3.999999999999997,-2.999999999999999,-2]
[-0.9999999999999981,-5.977974170712231e-17,0.9999999999999974]
[2,2.999999999999999,3.999999999999996]]
errors=0

U_Ut
[[0.9999999999999993,-1.665334536937735e-16,-1.665334536937735e-16]
[-1.665334536937735e-16,0.9999999999999987,-5.551115123125783e-17]
[-1.665334536937735e-16,-5.551115123125783e-17,0.999999999999999]]

© 2000-2025, MetaQuotes Ltd.


1407 Matrix and Vector Methods

Ut_U
[[0.9999999999999993,-5.551115123125783e-17,-1.110223024625157e-16]
[-5.551115123125783e-17,0.9999999999999987,2.498001805406602e-16]
[-1.110223024625157e-16,2.498001805406602e-16,0.999999999999999]]
vt_V
[[1,-5.551115123125783e-17,0]
[-5.551115123125783e-17,0.9999999999999996,1.110223024625157e-16]
[0,1.110223024625157e-16,0.9999999999999996]]
V_vt
[[0.9999999999999999,1.110223024625157e-16,1.942890293094024e-16]
[1.110223024625157e-16,0.9999999999999998,1.665334536937735e-16]
[1.942890293094024e-16,1.665334536937735e-16,0.9999999999999996]
*/
}

© 2000-2025, MetaQuotes Ltd.


1408 Matrix and Vector Methods

Statistical methods
Methods for computing descriptive statistics of matrices and vectors.

Function Action

ArgMax R eturn the index of the maximum value


ArgMin R eturn the index of the minimum value
Max R eturn the maximum value in a matrix/vector
Min R eturn the minimum value in a matrix/vector
Ptp R eturn the range of values of a matrix/vector or of the given matrix
axis
S um R eturnthe sum of the matrix/vector elements which can also be
performed for the given axis (axes)
Prod R eturnthe product of the matrix/vector elements which can also be
performed for the given axis
CumS um R eturn the cumulative sum of matrix/vector elements, including
those along the given axis
CumProd R eturnthe cumulative product of matrix/vector elements, including
those along the given axis
Percentile R eturnthe specified percentile of values of matrix/vector elements
or elements along the specified axis
Quantile R eturn the specified quantile
of values of matrix/vector elements or
elements along the specified axis
Median Compute the median of the matrix/vector elements
Mean Compute the arithmetic mean of element values
Average Compute the weighted mean of matrix/vector values
S td R eturn the standard deviation of values of matrix/vector elements or
of elements along the given axis
Var Compute the variance of values of matrix/vector elements
LinearRegression Calculate a vector/matrix with calculated linear regression values

© 2000-2025, MetaQuotes Ltd.


1409 Matrix and Vector Methods

ArgMax
R eturn the index of the maximum value.
ulong vector::ArgMax();

ulong matrix::ArgMax();

vector matrix::ArgMax(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Index of the maximum value.

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vector cols_max=matrix_a.ArgMax(0);
vector rows_max=matrix_a.ArgMax(1);
ulong matrix_max=matrix_a.ArgMax();

Print("cols_max=",cols_max);
Print("rows_max=",rows_max);
Print("max index ",matrix_max," max value ",matrix_a.Flat(matrix_max));

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_max=[0,3,1]
rows_max=[0,2,0,1]
max index 5 max value 12.0
*/

© 2000-2025, MetaQuotes Ltd.


1410 Matrix and Vector Methods

ArgMin
R eturn the index of the minimum value.
ulong vector::ArgMin();

ulong matrix::ArgMin();

vector matrix::ArgMin(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Index of the minimum value.

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vector cols_min=matrix_a.ArgMin(0);
vector rows_min=matrix_a.ArgMin(1);
ulong matrix_min=matrix_a.ArgMin();

Print("cols_min=",cols_min);
Print("rows_min=",rows_min);
Print("min index ",matrix_min," min value ",matrix_a.Flat(matrix_min));

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_min=[1,0,0]
rows_min=[2,0,2,0]
min index 3 min value 1.0
*/

© 2000-2025, MetaQuotes Ltd.


1411 Matrix and Vector Methods

Max
R eturn the maximum value in a matrix/vector.
double vector::Max();

double matrix::Max();

vector matrix::Max(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Maximum value in a matrix/vector.

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vector cols_max=matrix_a.Max(0);
vector rows_max=matrix_a.Max(1);
double matrix_max=matrix_a.Max();

Print("cols_max=",cols_max);
Print("rows_max=",rows_max);
Print("max value ",matrix_max);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_max=[10,11,12]
rows_max=[10,12,6,11]
max value 12.0
*/

© 2000-2025, MetaQuotes Ltd.


1412 Matrix and Vector Methods

Min
R eturn the minimum value in a matrix/vector.
double vector::Min();

double matrix::Min();

vector matrix::Min(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Minimum value in a matrix/vector.

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vector cols_min=matrix_a.Min(0);
vector rows_min=matrix_a.Min(1);
double matrix_min=matrix_a.Min();

Print("cols_min=",cols_min);
Print("rows_min=",rows_min);
Print("min value ",matrix_min);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_min=[1,3,2]
rows_min=[2,1,4,7]
min value 1.0
*/

© 2000-2025, MetaQuotes Ltd.


1413 Matrix and Vector Methods

Ptp
R eturn the range of values of a matrix/vector or of the given matrix axis, equivalent to Max() - Min().
Ptp - Peak to peak.
double vector::Ptp();

double matrix::Ptp();

vector matrix::Ptp(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Vector with ranges of values (maximum - minimum) .

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vector cols_ptp=matrix_a.Ptp(0);
vector rows_ptp=matrix_a.Ptp(1);
double matrix_ptp=matrix_a.Ptp();

Print("cols_ptp ",cols_ptp);
Print("rows_ptp ",rows_ptp);
Print("ptp value ",matrix_ptp);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_ptp [9,8,10]
rows_ptp [8,11,2,4]
ptp value 11.0
*/

© 2000-2025, MetaQuotes Ltd.


1414 Matrix and Vector Methods

Sum
R eturn the sum of the matrix/vector elements which can also be performed for the given axis (axes).
double vector::Sum();

double matrix::Sum();

vector matrix::Sum(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

S um of the matrix/vector elements which can also be performed for the given axis (axes).

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vector cols_sum=matrix_a.Sum(0);
vector rows_sum=matrix_a.Sum(1);
double matrix_sum=matrix_a.Sum();

Print("cols_sum=",cols_sum);
Print("rows_sum=",rows_sum);
Print("sum value ",matrix_sum);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_sum=[24,27,27]
rows_sum=[15,21,15,27]
sum value 78.0
*/

© 2000-2025, MetaQuotes Ltd.


1415 Matrix and Vector Methods

Prod
R eturn the product of the matrix/vector elements which can also be performed for the given axis.
double vector::Prod(
const double initial=1 // initial multiplier
);

double matrix::Prod(
const double initial=1 // initial multiplier
);

vector matrix::Prod(
const int axis, // axis
const double initial=1 // initial multiplier
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.
initial=1
[in] Initial multiplier.

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vector cols_prod=matrix_a.Prod(0);
vector rows_prod=matrix_a.Prod(1);
double matrix_prod=matrix_a.Prod();

Print("cols_prod=",cols_prod);
cols_prod=matrix_a.Prod(0,0.1);
Print("cols_prod=",cols_prod);
Print("rows_prod=",rows_prod);
Print("prod value ",matrix_prod);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_prod=[420,1320,864]
cols_prod=[42,132,86.40000000000001]
rows_prod=[60,96,120,693]

© 2000-2025, MetaQuotes Ltd.


1416 Matrix and Vector Methods

prod value 479001600.0


*/

© 2000-2025, MetaQuotes Ltd.


1417 Matrix and Vector Methods

CumSum
R eturn the cumulative sum of matrix/vector elements, including those along the given axis.
vector vector::CumSum();

vector matrix::CumSum();

matrix matrix::CumSum(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Cumulative sum of the elements along the given axis.

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

matrix cols_cumsum=matrix_a.CumSum(0);
matrix rows_cumsum=matrix_a.CumSum(1);
vector cumsum_values=matrix_a.CumSum();

Print("cols_cumsum\n",cols_cumsum);
Print("rows_cumsum\n",rows_cumsum);
Print("cumsum values ",cumsum_values);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_cumsum
[[10,3,2]
[11,11,14]
[17,16,18]
[24,27,27]]
rows_cumsum
[[10,13,15]
[1,9,21]
[6,11,15]

© 2000-2025, MetaQuotes Ltd.


1418 Matrix and Vector Methods

[7,18,27]]
cumsum values [10,13,15,16,24,36,42,47,51,58,69,78]
*/

© 2000-2025, MetaQuotes Ltd.


1419 Matrix and Vector Methods

CumProd
R eturn the cumulative product of matrix/vector elements, including those along the given axis.
vector vector::CumProd();

vector matrix::CumProd();

matrix matrix::CumProd(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis for each column (i.e., over the rows), 1 — vertical axis for each row
(i.e. over the columns)

Return Value

Cumulative product of the elements along the given axis.

Example

matrix matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

matrix cols_cumprod=matrix_a.CumProd(0);
matrix rows_cumprod=matrix_a.CumProd(1);
vector cumprod_values=matrix_a.CumProd();

Print("cols_cumprod\n",cols_cumprod);
Print("rows_cumprod\n",rows_cumprod);
Print("cumprod values ",cumprod_values);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_cumprod
[[10,3,2]
[10,24,24]
[60,120,96]
[420,1320,864]]
rows_cumprod
[[10,30,60]
[1,8,96]

© 2000-2025, MetaQuotes Ltd.


1420 Matrix and Vector Methods

[6,30,120]
[7,77,693]]
cumprod values [10,30,60,60,480,5760,34560,172800,691200,4838400,53222400,479001600]
*/

© 2000-2025, MetaQuotes Ltd.


1421 Matrix and Vector Methods

Percentile
R eturn the specified percentile of values of matrix/vector elements or elements along the specified
axis.
double vector::Percentile(
const int percent //
);

double matrix::Percentile(
const int percent //
);

vector matrix::Percentile(
const int percent, //
const int axis // axis
);

Parameters
percent
[in] Percentiles to compute, which must be between 0 and 100 inclusive.
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Percentile: scalar or vector.


Note

Valid values of the 'percent' parameter are in the range [0, 100]. A linear algorithm is used to
calculate percentiles. The correct calculation of percentiles requires the sequence to be sorted.

Example

matrixf matrix_a={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
Print("matrix_a\n",matrix_a);

vectorf cols_percentile=matrix_a.Percentile(50,0);
vectorf rows_percentile=matrix_a.Percentile(50,1);
float matrix_percentile=matrix_a.Percentile(50);

Print("cols_percentile ",cols_percentile);
Print("rows_percentile ",rows_percentile);
Print("percentile value ",matrix_percentile);

/*

© 2000-2025, MetaQuotes Ltd.


1422 Matrix and Vector Methods

matrix_a
[[1,2,3]
[4,5,6]
[7,8,9]
[10,11,12]]
cols_percentile [5.5,6.5,7.5]
rows_percentile [2,5,8,11]
percentile value 6.5
*/

© 2000-2025, MetaQuotes Ltd.


1423 Matrix and Vector Methods

Quantile
R eturn the specified quantile of values of matrix/vector elements or elements along the specified
axis.
double vector::Quantile(
const double quantile // quantile
);

double matrix::Quantile(
const double quantile // quantile
);

vector matrix::Quantile(
const double quantile, // quantile
const int axis // axis
);

Parameters
quantile
[in] Quantile to compute, which must be between 0 and 1 inclusive.
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Quantile: scalar or vector.


Note

The 'quantile' parameter takes values in the range [0, 1]. A linear algorithm is used to calculate
quantiles. The correct calculation of quantiles requires the sequence to be sorted.

Example

matrixf matrix_a={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
Print("matrix_a\n",matrix_a);

vectorf cols_quantile=matrix_a.Quantile(0.5,0);
vectorf rows_quantile=matrix_a.Quantile(0.5,1);
float matrix_quantile=matrix_a.Quantile(0.5);

Print("cols_quantile ",cols_quantile);
Print("rows_quantile ",rows_quantile);
Print("quantile value ",matrix_quantile);

/*
matrix_a

© 2000-2025, MetaQuotes Ltd.


1424 Matrix and Vector Methods

[[1,2,3]
[4,5,6]
[7,8,9]
[10,11,12]]
cols_quantile [5.5,6.5,7.5]
rows_quantile [2,5,8,11]
quantile value 6.5
*/

© 2000-2025, MetaQuotes Ltd.


1425 Matrix and Vector Methods

Median
Compute the median of the matrix/vector elements.
double vector::Median();

double matrix::Median();

vector matrix::Median(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Median: scalar or vector.

Note

The median is the middle value that separates the highest half of the array/vector elements from
the lowest half of elements. S ame as Quantile(0.5) and Percentile(50). The correct calculation of
median requires the sequence to be sorted.

Example

matrixf matrix_a={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
Print("matrix_a\n",matrix_a);

vectorf cols_median=matrix_a.Median(0);
vectorf rows_median=matrix_a.Median(1);
float matrix_median=matrix_a.Median();

Print("cols_median ",cols_median);
Print("rows_median ",rows_median);
Print("median value ",matrix_median);

/*
matrix_a
[[1,2,3]
[4,5,6]
[7,8,9]
[10,11,12]]
cols_median [5.5,6.5,7.5]

© 2000-2025, MetaQuotes Ltd.


1426 Matrix and Vector Methods

rows_median [2,5,8,11]
median value 6.5
*/

© 2000-2025, MetaQuotes Ltd.


1427 Matrix and Vector Methods

Mean
Compute the arithmetic mean of element values.
double vector::Mean();

double matrix::Mean();

vector matrix::Mean(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Arithmetic mean of element values.

Example

matrixf matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vectorf cols_mean=matrix_a.Mean(0);
vectorf rows_mean=matrix_a.Mean(1);
float matrix_mean=matrix_a.Mean();

Print("cols_mean ",cols_mean);
Print("rows_mean ",rows_mean);
Print("mean value ",matrix_mean);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_mean [6,6.75,6.75]
rows_mean [5,7,5,9]
mean value 6.5
*/

© 2000-2025, MetaQuotes Ltd.


1428 Matrix and Vector Methods

Average
Compute the weighted mean of matrix/vector values.
double vector::Average(
const vector& weigts // weights vector
);

double matrix::Average(
const matrix& weigts // weights matrix
);

vector matrix::Average(
const matrix& weigts, // weights matrix
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

W eighted mean: scalar or vector.

Note

The weight matrix/vector is associated with the main matrix/vector.

Example

matrixf matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
matrixf matrix_w=matrixf::Ones(4,3);
Print("matrix_a\n",matrix_a);

vectorf cols_average=matrix_a.Average(matrix_w,0);
vectorf rows_average=matrix_a.Average(matrix_w,1);
float matrix_average=matrix_a.Average(matrix_w);

Print("cols_average ",cols_average);
Print("rows_average ",rows_average);
Print("average value ",matrix_average);

/*
matrix_a
[[10,3,2]

© 2000-2025, MetaQuotes Ltd.


1429 Matrix and Vector Methods

[1,8,12]
[6,5,4]
[7,11,9]]
cols_average [6,6.75,6.75]
rows_average [5,7,5,9]
average value 6.5
*/ value 6.5

© 2000-2025, MetaQuotes Ltd.


1430 Matrix and Vector Methods

Std
R eturn the standard deviation of values of matrix/vector elements or of elements along the given
axis.
double vector::Std();

double matrix::Std();

vector matrix::Std(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

S tandard_deviation: scalar or vector.

Note

The standard deviation is the s quare root of the average of the s quared deviations from the mean,
i. e., std = s qrt(mean(x)), where x = abs(a - a.mean())**2.
The average s quared deviation is typically calculated as x.sum() / N, where N = len(x).

Example

matrixf matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vectorf cols_std=matrix_a.Std(0);
vectorf rows_std=matrix_a.Std(1);
float matrix_std=matrix_a.Std();

Print("cols_std ",cols_std);
Print("rows_std ",rows_std);
Print("std value ",matrix_std);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]

© 2000-2025, MetaQuotes Ltd.


1431 Matrix and Vector Methods

cols_std [3.2403703,3.0310888,3.9607449]
rows_std [3.5590262,4.5460606,0.81649661,1.6329932]
std value 3.452052593231201
*/

© 2000-2025, MetaQuotes Ltd.


1432 Matrix and Vector Methods

Var
Compute the variance of values of matrix/vector elements.
double vector::Var();

double matrix::Var();

vector matrix::Var(
const int axis // axis
);

Parameters
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

Variance: scalar or vector.

Note

The variance is the average of the s quared deviations from the mean, i.e., var = mean(x), where x
= abs(a - a.mean())**2.

The mean is typically calculated as x.sum() / N, where N = len(x).

Example

matrixf matrix_a={{10,3,2},{1,8,12},{6,5,4},{7,11,9}};
Print("matrix_a\n",matrix_a);

vectorf cols_var=matrix_a.Var(0);
vectorf rows_var=matrix_a.Var(1);
float matrix_var=matrix_a.Var();

Print("cols_var ",cols_var);
Print("rows_var ",rows_var);
Print("var value ",matrix_var);

/*
matrix_a
[[10,3,2]
[1,8,12]
[6,5,4]
[7,11,9]]
cols_var [10.5,9.1875,15.6875]

© 2000-2025, MetaQuotes Ltd.


1433 Matrix and Vector Methods

rows_var [12.666667,20.666666,0.66666669,2.6666667]
var value 11.916666984558105
*/

© 2000-2025, MetaQuotes Ltd.


1434 Matrix and Vector Methods

LinearRegression
Calculate a vector/matrix with calculated linear regression values.
vector vector::LinearRegression();

matrix matrix::LinearRegression(
ENUM_MATRIX_AXIS axis=AXIS_NONE // axis along which regression is calculated
);

Parameters
axis
[in] S pecifying the axis along which the regression is calculated. ENUM _M AT R IX_AXIS enumeration
value (AXIS_HORZ — horizontal axis, AXIS_VERT — vertical axis).

Return Value

Vector or matrix with calculated linear regression values.

Note

Linear regression is calculated using the standard regression equation: y (x) = a * x + b, where a is
the line slope, while b is its Y axis shift.

Example:

#include <Graphics\Graphic.mqh>

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1435 Matrix and Vector Methods

//| Script program start function |


//+------------------------------------------------------------------+
void OnStart()
{
vector vector_a;
vector_a.CopyRates(_Symbol,_Period,COPY_RATES_CLOSE,1,100);
vector vector_r=vector_a.LinearRegression();

//--- switch off chart show


ChartSetInteger(0,CHART_SHOW,false);

//--- arrays for drawing a graph


double x[];
double y1[];
double y2[];
ArrayResize(x,uint(vector_a.Size()));
ArrayResize(y1,uint(vector_a.Size()));
ArrayResize(y2,uint(vector_a.Size()));
for(ulong i=0; i<vector_a.Size(); i++)
{
x[i]=(double)i;
y1[i]=vector_a[i];
y2[i]=vector_r[i];
}

//--- graph title


string title="Linear regression "+_Symbol+","+EnumToString(_Period);

long chart=0;
string name="LinearRegression";

//--- create graph


CGraphic graphic;
graphic.Create(chart,name,0,0,0,GRAPH_WIDTH,GRAPH_HEIGHT);
graphic.BackgroundMain(title);
graphic.BackgroundMainSize(12);

//--- activation function graph


CCurve *curvef=graphic.CurveAdd(x,y1,CURVE_POINTS_AND_LINES);
curvef.Name("vector_a");
curvef.LinesWidth(2);
curvef.LinesSmooth(true);
curvef.LinesSmoothTension(1);
curvef.LinesSmoothStep(10);

//--- derivatives of activation function


CCurve *curved=graphic.CurveAdd(x,y2,CURVE_LINES);
curved.Name("vector_r");
curved.LinesWidth(2);

© 2000-2025, MetaQuotes Ltd.


1436 Matrix and Vector Methods

curved.LinesSmooth(true);
curved.LinesSmoothTension(1);
curved.LinesSmoothStep(10);
graphic.CurvePlotAll();
graphic.Update();

//--- endless loop to recognize pressed keyboard buttons


while(!IsStopped())
{
//--- press escape button to quit program
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
break;
//--- press PdDn to save graph picture
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0)
{
string file_names[];
if(FileSelectDialog("Save Picture",NULL,"All files (*.*)|*.*",FSD_WRITE_FILE,file_names,"L
continue;
ChartScreenShot(0,file_names[0],GRAPH_WIDTH,GRAPH_HEIGHT);
}
Sleep(10);
}

//--- clean up
graphic.Destroy();
ObjectDelete(chart,name);
ChartSetInteger(0,CHART_SHOW,true);
}

ENUM_MATRIX _AX IS

Enumeration for specifying the axis in all statistical functions for matrices.

ID Description

AXIS_NONE The axis is not specified. Calculation is performed over all


matrix elements, as if it were a vector (see the Flat method).
AXIS_H ORZ H orizontal axis

AXIS_VER T Vertical axis

© 2000-2025, MetaQuotes Ltd.


1437 Matrix and Vector Methods

Feature methods
These methods enable the receiving of matrix features, such as :
· number of rows
· number of columns
· norm
· condition number
· determinant
· matrix rank
· trace
· spectrum

Function Action

R ows R eturn the number of rows in a matrix


Cols R eturn the number of columns in a matrix
S ize R eturn the size of vector
Norm R eturn matrix or vector norm
Cond Compute the condition number of a matrix
Det Compute the determinant of a s quare invertible matrix
S Log Det Compute the sign and logarithm of the determinant of an matrix
R ank R eturn matrix rank using the Gaussian method
Trace R eturn the sum along diagonals of the matrix
S pectrum Compute spectrum of a matrix as the set of its eigenvalues from the
product AT*A

© 2000-2025, MetaQuotes Ltd.


1438 Matrix and Vector Methods

Rows
R eturn the number of rows in a matrix.
ulong matrix::Rows()

Return Value

Integer.

Example

matrix m= {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}};


m.Reshape(3, 4);
Print("matrix m \n" , m);
Print("m.Rows()=", m.Rows());
Print("m.Cols()=", m.Cols());

/*
matrix m
[[1,2,3,4]
[5,6,7,8]
[9,10,11,12]]
m.Rows()=3
m.Cols()=4
*/

© 2000-2025, MetaQuotes Ltd.


1439 Matrix and Vector Methods

Cols
R eturn the number of columns in a matrix.
ulong matrix::Cols()

Return Value

Integer.

Example

matrix m= {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}};


m.Reshape(3, 4);
Print("matrix m \n" , m);
Print("m.Cols()=", m.Cols());
Print("m.Rows()=", m.Rows());

/*
matrix m
[[1,2,3,4]
[5,6,7,8]
[9,10,11,12]]
m.Cols()=4
m.Rows()=3
*/

© 2000-2025, MetaQuotes Ltd.


1440 Matrix and Vector Methods

Size
R eturn the size of vector.
ulong vector::Size()

Return Value

Integer.

Example

matrix m={{1,2,3,4,5,6,7,8,9,10,11,12}};
m.Reshape(3,4);
Print("matrix m\n",m);
vector v=m.Row(1);
Print("v.Size()=",v.Size());
Print("v=",v);

/*
matrix m
[[1,2,3,4]
[5,6,7,8]
[9,10,11,12]]
v.Size()=4
v=[5,6,7,8]
*/

© 2000-2025, MetaQuotes Ltd.


1441 Matrix and Vector Methods

Norm
R eturn matrix or vector norm.
double vector::Norm(
const ENUM_VECTOR_NORM norm, // vector norm
const int norm_p=2 // number of p-norm in case of VECTOR_NORM_P
);

double matrix::Norm(
const ENUM_MATRIX_NORM norm // matrix norm
);

Parameters
norm
[in] Norm order

Return Value

Matrix or vector norm.

Note
· VECTOR_NOR M _I NF is the maximum absolute value among vector elements.
· VECTOR_NOR M _MINUS_INF is the minimum absolute value of a vector.
· VECTOR_NOR M _P is the P-norm of the vector. If norm_p=0, then this is the number of non-zero
vector elements. norm_p=1 is the sum of absolute values of vector elements. norm_p=2 is the
s quare root of the sum of s quares of vector element values. The value of the norm_p parameter
can be negative.
· M ATRIX_NORM _FROBENIUS is the s quare root of the sum of the s quares of the matrix element
values. The Frobenius norm and the vector P2-norm are consistent.
· M ATRIX_NORM _S PECTRAL is the maximum value of the matrix spectrum.
· M ATRIX_NORM _NUCLEAR is the sum of the singular values of the matrix.
· M ATRIX_NORM _INF is the maximum vector p1-norm among the vertical vectors of the matrix. The
matrix inf-norm and the vector inf-norm are consistent.
· M ATRIX_NORM _MINUS_INF is the minimum vector p1-norm among the vertical vectors of the
matrix.
· M ATRIX_NORM _P1 is the maximum vector p1-norm among horizontal matrix vectors.
· M ATRIX_NORM _MINUS_P1 is the minimum vector p1-norm among horizontal matrix vectors.
· M ATRIX_NORM _P2 is the highest singular value of the matrix.
· M ATRIX_NORM _MINUS_P2 is the lowest singular value of a matrix.

A simple algorithm for calculating the P-norm of a vector in MQL5:

double VectorNormP(const vector& v,int norm_value)


{
ulong i;

© 2000-2025, MetaQuotes Ltd.


1442 Matrix and Vector Methods

double norm=0.0;
//---
switch(norm_value)
{
case 0 :
for(i=0; i<v.Size(); i++)
if(v[i]!=0)
norm+=1.0;
break;
case 1 :
for(i=0; i<v.Size(); i++)
norm+=MathAbs(v[i]);
break;
case 2 :
for(i=0; i<v.Size(); i++)
norm+=v[i]*v[i];
norm=MathSqrt(norm);
break;
default :
for(i=0; i<v.Size(); i++)
norm+=MathPow(MathAbs(v[i]),norm_value);
norm=MathPow(norm,1.0/norm_value);
}
//---
return(norm);
}

MQL5 example:

matrix a= {{0, 1, 2, 3, 4, 5, 6, 7, 8}};


a=a-4;
Print("matrix a \n", a);
a.Reshape(3, 3);
matrix b=a;
Print("matrix b \n", b);
Print("b.Norm(MATRIX_NORM_P2)=", b.Norm(MATRIX_NORM_FROBENIUS));
Print("b.Norm(MATRIX_NORM_FROBENIUS)=", b.Norm(MATRIX_NORM_FROBENIUS));
Print("b.Norm(MATRIX_NORM_INF)", b.Norm(MATRIX_NORM_INF));
Print("b.Norm(MATRIX_NORM_MINUS_INF)", b.Norm(MATRIX_NORM_MINUS_INF));
Print("b.Norm(MATRIX_NORM_P1)=)", b.Norm(MATRIX_NORM_P1));
Print("b.Norm(MATRIX_NORM_MINUS_P1)=", b.Norm(MATRIX_NORM_MINUS_P1));
Print("b.Norm(MATRIX_NORM_P2)=", b.Norm(MATRIX_NORM_P2));
Print("b.Norm(MATRIX_NORM_MINUS_P2)=", b.Norm(MATRIX_NORM_MINUS_P2));

/*
matrix a
[[-4,-3,-2,-1,0,1,2,3,4]]
matrix b
[[-4,-3,-2]

© 2000-2025, MetaQuotes Ltd.


1443 Matrix and Vector Methods

[-1,0,1]
[2,3,4]]
b.Norm(MATRIX_NORM_P2)=7.745966692414834
b.Norm(MATRIX_NORM_FROBENIUS)=7.745966692414834
b.Norm(MATRIX_NORM_INF)9.0
b.Norm(MATRIX_NORM_MINUS_INF)2.0
b.Norm(MATRIX_NORM_P1)=)7.0
b.Norm(MATRIX_NORM_MINUS_P1)=6.0
b.Norm(MATRIX_NORM_P2)=7.348469228349533
b.Norm(MATRIX_NORM_MINUS_P2)=1.857033188519056e-16
*/

Python example:

import numpy as np
from numpy import linalg as LA
a = np.arange(9) - 4
print("a \n",a)
b = a.reshape((3, 3))
print("b \n",b)
print("LA.norm(b)=",LA.norm(b))
print("LA.norm(b, 'fro')=",LA.norm(b, 'fro'))
print("LA.norm(b, np.inf)=",LA.norm(b, np.inf))
print("LA.norm(b, -np.inf)=",LA.norm(b, -np.inf))
print("LA.norm(b, 1)=",LA.norm(b, 1))
print("LA.norm(b, -1)=",LA.norm(b, -1))
print("LA.norm(b, 2)=",LA.norm(b, 2))
print("LA.norm(b, -2)=",LA.norm(b, -2))

a
[-4 -3 -2 -1 0 1 2 3 4]
b
[[-4 -3 -2]
[-1 0 1]
[ 2 3 4]]
LA.norm(b)= 7.745966692414834
LA.norm(b, 'fro')= 7.745966692414834
LA.norm(b, np.inf)= 9.0
LA.norm(b, -np.inf)= 2.0
LA.norm(b, 1)= 7.0
LA.norm(b, -1)= 6.0
LA.norm(b, 2)= 7.3484692283495345
LA.norm(b, -2)= 1.857033188519056e-16

© 2000-2025, MetaQuotes Ltd.


1444 Matrix and Vector Methods

Cond
Compute the condition number of a matrix.
double matrix::Cond(
const ENUM_MATRIX_NORM norm // matrix norm
);

Parameters
norm
[in] Order of the norm from ENUM _M ATRIX_NORM

Return Value

The condition number of the matrix. May be infinite.

Note

The condition number of x is defined as the norm of x times the norm of the inverse of x [1]. The
norm can be the usual L2-norm (root-of-sum-of-s quares) or one of a number of other matrix norms.
The condition umber is the K value equal to the product of the matrix A norms and its inverse.
Matrices with a high condition number are called ill-conditioned. Those with a low condition number
are called well-conditioned. The inverse matrix is obtained using pseudo-inversion, so as not to be
limited by the condition of s quareness and non-singularity of the matrix.
An exception is the spectral condition number.

A simple algorithm for calculating the spectral condition number in MQL5:

double MatrixCondSpectral(matrix& a)
{
double norm=0.0;
vector v=a.Spectrum();

if(v.Size()>0)
{
double max_norm=v[0];
double min_norm=v[0];
for(ulong i=1; i<v.Size(); i++)
{
double real=MathAbs(v[i]);
if(max_norm<real)
max_norm=real;
if(min_norm>real)
min_norm=real;
}
max_norm=MathSqrt(max_norm);

© 2000-2025, MetaQuotes Ltd.


1445 Matrix and Vector Methods

min_norm=MathSqrt(min_norm);
if(min_norm>0.0)
norm=max_norm/min_norm;
}

return(norm);
}

MQL5 example:

matrix a= {{1, 0, -1}, {0, 1, 0}, { 1, 0, 1}};


Print("a.Cond(MATRIX_NORM_P2)=", a.Cond(MATRIX_NORM_P2));
Print("a.Cond(MATRIX_NORM_FROBENIUS)=", a.Cond(MATRIX_NORM_FROBENIUS));
Print("a.Cond(MATRIX_NORM_INF)=", a.Cond(MATRIX_NORM_INF));
Print("a.Cond(MATRIX_NORM_MINUS_INF)=", a.Cond(MATRIX_NORM_MINUS_INF));
Print("a.Cond(MATRIX_NORM_P1)=)", a.Cond(MATRIX_NORM_P1));
Print("a.Cond(MATRIX_NORM_MINUS_P1)=", a.Cond(MATRIX_NORM_MINUS_P1));
Print("a.Cond(MATRIX_NORM_P2)=", a.Cond(MATRIX_NORM_P2));
Print("a.Cond(MATRIX_NORM_MINUS_P2)=", a.Cond(MATRIX_NORM_MINUS_P2));

/*
matrix a
[[1,0,-1]
[0,1,0]
[1,0,1]]
a.Cond(MATRIX_NORM_P2)=1.414213562373095
a.Cond(MATRIX_NORM_FROBENIUS)=3.162277660168379
a.Cond(MATRIX_NORM_INF)=2.0
a.Cond(MATRIX_NORM_MINUS_INF)=0.9999999999999997
a.Cond(MATRIX_NORM_P1)=)2.0
a.Cond(MATRIX_NORM_MINUS_P1)=0.9999999999999998
a.Cond(MATRIX_NORM_P2)=1.414213562373095
a.Cond(MATRIX_NORM_MINUS_P2)=0.7071067811865472
*/

Python example:

import numpy as np
from numpy import linalg as LA
a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
print("a \n",a)
print("LA.cond(a)=",LA.cond(a))
print("LA.cond(a, 'fro')=",LA.cond(a, 'fro'))
print("LA.cond(a, np.inf)=",LA.cond(a, np.inf))
print("LA.cond(a, -np.inf)=",LA.cond(a, -np.inf))
print("LA.cond(a, 1)=",LA.cond(a, 1))
print("LA.cond(a, -1)=",LA.cond(a, -1))

© 2000-2025, MetaQuotes Ltd.


1446 Matrix and Vector Methods

print("LA.cond(a, 2)=",LA.cond(a, 2))


print("LA.cond(a, -2)=",LA.cond(a, -2))

a
[[ 1 0 -1]
[ 0 1 0]
[ 1 0 1]]
LA.cond(a)= 1.4142135623730951
LA.cond(a, 'fro')= 3.1622776601683795
LA.cond(a, np.inf)= 2.0
LA.cond(a, -np.inf)= 1.0
LA.cond(a, 1)= 2.0
LA.cond(a, -1)= 1.0
LA.cond(a, 2)= 1.4142135623730951
LA.cond(a, -2)= 0.7071067811865475

© 2000-2025, MetaQuotes Ltd.


1447 Matrix and Vector Methods

Det
Compute the determinant of a s quare invertible matrix.
double matrix::Det()

Return Value

Determinant of matrix.

Note

2nd and 3rd order matrix determinants are calculated according to the S arrus rule. d2=a11*a22-
a12*a21; d3=a11*a22*a33+a12*a23*a31+a13*a21*a32-a13*a22*a31-a11*a23*a32-a12*a21*a33
The determinant is calculated by the Gaussian method by reducing the matrix to an upper triangular
form. The determinant of an upper triangular matrix is equal to the product of the main diagonal
elements.
If at least one matrix row or column is zero, the determinant is zero.
If two or more matrix rows or columns are linearly dependent, its determinant is zero.
The determinant of a matrix is equal to the product of its eigenvalues.

MQL5 example:

matrix m={{1,2},{3,4}};
double det=m.Det();
Print("matrix m\n",m);
Print("det(m)=",det);
/*
matrix m
[[1,2]
[3,4]]
det(m)=-2.0
*/

Python example:

import numpy as np

a = np.array([[1, 2], [3, 4]])


print('a \n',a)
print('nnp.linalg.det(a) \n',np.linalg.det(a))

a
[[1 2]
[3 4]]

© 2000-2025, MetaQuotes Ltd.


1448 Matrix and Vector Methods

np.linalg.det(a)
-2.0000000000000004

© 2000-2025, MetaQuotes Ltd.


1449 Matrix and Vector Methods

SLogDet
Compute the sign and logarithm of a matrix determinant.
double matrix::SLogDet(
int& sign // sign
);

Parameters
sign
[out] The sign of the determinant. If the sign is even, the determinant is positive.

Return Value

A number representing the sign of the determinant.

Note

The determinant is calculated by the Gaussian method by reducing the matrix to an upper triangular
form. The determinant of an upper triangular matrix is equal to the product of the main diagonal
elements. The logarithm of a product is equal to the sum of the logarithms. Therefore, in case of an
overflow when calculating the determinant, you can use the S LogDet method.
If the sign is even, the determinant is positive.

Example

a = np.array([[1, 2], [3, 4]])


(sign, logdet) = np.linalg.slogdet(a)
(sign, logdet) (-1, 0.69314718055994529) # may vary sign * np.exp(logdet) -2.0

© 2000-2025, MetaQuotes Ltd.


1450 Matrix and Vector Methods

Rank
R eturn matrix rank using the Gaussian method.
int Rank()

Return Value

R ank of matrix.

Note

The rank of a system of rows (or columns) of a matrix A that has m rows and n columns is the
maximum number of linearly independent rows (or columns). S everal rows (columns) are called
linearly independent if none of them can be expressed linearly in terms of others. The rank of the
row system is always equal to the rank of the column system. This value is called the rank of the
matrix.

MQL5 example:

matrix a=matrix::Eye(4, 4);;


Print("matrix a \n", a);
Print("a.Rank()=", a.Rank());

matrix I=matrix::Eye(4, 4);


I[3, 3] = 0.; // rank deficient matrix
Print("I \n", I);
Print("I.Rank()=", I.Rank());

matrix b=matrix::Ones(1, 4);


Print("b \n", b);
Print("b.Rank()=", b.Rank());;// 1 dimension - rank 1 unless all 0

matrix zeros=matrix::Zeros(4, 1);


Print("zeros \n", zeros);
Print("zeros.Rank()=", zeros.Rank());

/*
matrix a
[[1,0,0,0]
[0,1,0,0]
[0,0,1,0]
[0,0,0,1]]
a.Rank()=4

I
[[1,0,0,0]
[0,1,0,0]

© 2000-2025, MetaQuotes Ltd.


1451 Matrix and Vector Methods

[0,0,1,0]
[0,0,0,0]]
I.Rank()=3

b
[[1,1,1,1]]
b.Rank()=1

zeros
[[0]
[0]
[0]
[0]]
zeros.Rank()=0
*/

Python example:

import numpy as np
from numpy.linalg import matrix_rank
a=(np.eye(4)) # Full rank matrix
print("a \n", a)
print("matrix_rank(a)=",matrix_rank(a))
I=np.eye(4)
I[-1,-1] = 0. # rank deficient matrix
print("I \n",I)
print("matrix_rank(I)=",matrix_rank(I))

b=np.ones((4,))
print("b \n",b)
print("matrix_rank(b)=",matrix_rank(b)) # 1 dimension - rank 1 unless all 0

zeros=np.zeros((4,))
print("zeroes \n",zeros)
print("matrix_rank(zeros)=",matrix_rank(zeros))

a
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
matrix_rank(a)= 4

I
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 0.]]

© 2000-2025, MetaQuotes Ltd.


1452 Matrix and Vector Methods

matrix_rank(I)= 3

b
[1. 1. 1. 1.]
matrix_rank(b)= 1

zeroes
[0. 0. 0. 0.]
matrix_rank(zeros)= 0

© 2000-2025, MetaQuotes Ltd.


1453 Matrix and Vector Methods

Trace
R eturn the sum along diagonals of the matrix.
double matrix::Trace()

Return Value

The sum along the diagonal.

Note

The trace of a matrix is equal to the sum of its eigenvalues.

MQL5 example:

matrix a= {{0, 1, 2, 3, 4, 5, 6, 7, 8}};


a.Reshape(3, 3);
Print("matrix a \n", a);
Print("a.Trace() \n", a.Trace());

/*
matrix a
[[0,1,2]
[3,4,5]
[6,7,8]]
a.Trace()
12.0
*/

Python example:

a = np.arange(9).reshape((3,3))
print('a \n',a)
print('np.trace(a) \n',np.trace(a))

a
[[0 1 2]
[3 4 5]
[6 7 8]]

np.trace(a)
12

© 2000-2025, MetaQuotes Ltd.


1454 Matrix and Vector Methods

Spectrum
Compute spectrum of a matrix as the set of its eigenvalues from the product AT*A.
vector matrix::Spectrum()

Return Value

S pectrum of a matrix as a vector of matrix eigenvalues.

Example

double MatrixCondSpectral(matrix& a)
{
double norm=0.0;
vector v=a.Spectrum();

if(v.Size()>0)
{
double max_norm=v[0];
double min_norm=v[0];
for(ulong i=1; i<v.Size(); i++)
{
double real=MathAbs(v[i]);
if(max_norm<real)
max_norm=real;
if(min_norm>real)
min_norm=real;
}
max_norm=MathSqrt(max_norm);
min_norm=MathSqrt(min_norm);
if(min_norm>0.0)
norm=max_norm/min_norm;
}

return(norm);
}

© 2000-2025, MetaQuotes Ltd.


1455 Matrix and Vector Methods

Matrix methods for solving systems of linear equations


Methods for solving systems of linear equations and calculating the inverse matrix.

Function Action

S olve S olve a linear matrix equation, or system of linear algebraic


equations
LstSq R eturn the least-s quares solution of linear algebraic equations (for
non-s quare or degenerate matrices)
Inv Compute the (multiplicative) inverse of a s quare non-degenerate
matrix by the Jordan-Gauss method
PInv Compute the pseudo-inverse of a matrix by the Moore-Penrose
method

© 2000-2025, MetaQuotes Ltd.


1456 Matrix and Vector Methods

Solve
S olve a linear matrix equation, or system of linear algebraic equations.
vector matrix::Solve(
const vector b // ordinate or 'dependent variable' values
);

Parameters
b
[in] Ordinate or 'dependent variable' values. (Vector of free terms).

Return Value

Vector with solution to the system a * x = b.

Note

If at least one matrix row or column is zero, the system has no solution.
If two or more matrix rows or columns are linearly dependent, the system has no solution.

Example

//--- SLAE solution


vector_x=matrix_a.Solve(vector_b);
//--- check if a * x = b
result_vector=matrix_a.MatMul(vector_x);
errors=vector_b.Compare(result_vector,1e-12);

© 2000-2025, MetaQuotes Ltd.


1457 Matrix and Vector Methods

LstSq
R eturn the least-s quares solution of linear algebraic equations (for non-s quare or degenerate
matrices).
vector matrix::LstSq(
const vector b // ordinate or 'dependent variable' values
);

Parameters
b
[in] Ordinate or 'dependent variable' values. (Vector of free terms)

Return Value

Vector with solution to the system a * x = b. This is true only for systems that have an exact
solution.

Example

matrix a={{3, 2},


{4,-5},
{3, 3}};
vector b={7,40,3};
//---
vector x=a.LstSq(b);
//--- check, must be [5, -4]
Print("x=", x);
//--- check, must be [7, 40, 3]
vector b1=a.MatMul(x);
Print("b1=",b1);

/*
x=[5.000000000000002,-4]
b1=[7.000000000000005,40.00000000000001,3.000000000000005]
*/

© 2000-2025, MetaQuotes Ltd.


1458 Matrix and Vector Methods

Inv
Compute the multiplicative inverse of a s quare invertible matrix by the Jordan-Gauss method.
matrix matrix::Inv()

Return Value

Multiplicative inverse of the matrix.

Note

The product of the original matrix and the inverse matrix is the identity matrix.
If at least one matrix row or column is zero, the inverse matrix cannot be obtained.
If two or more matrix rows or columns are linearly dependent, the inverse matrix cannot be
obtained.

Example

int TestInverse(const int size_m)


{
int i,j,errors=0;
matrix matrix_a(size_m,size_m);
//--- populate the square matrix
MatrixTestFirst(matrix_a);
//--- microseconds will be measured
ulong t1=GetMicrosecondCount();
//--- get the inverse matrix
matrix inverse=matrix_a.Inv();
//--- measure
ulong t2=GetMicrosecondCount();
//--- check the correctness
matrix identity=matrix_a.MatMul(inverse);
//---
for(i=0; i<size_m; i++)
{
for(j=0; j<size_m; j++)
{
double value;
//--- ones must be along the diagonal
if(i==j)
value=1.0;
else
value=0.0;
if(MathClassify(identity[i][j])>FP_ZERO)
errors++;
else

© 2000-2025, MetaQuotes Ltd.


1459 Matrix and Vector Methods

{
if(identity[i][j]!=value)
{
double diff=MathAbs(identity[i][j]-value);
//--- too many multiplications and devisions, so reduce the check accuracy
if(diff>1e-9)
errors++;
}
}
}
}
//---
double elapsed_time=double(t2-t1)/1000.0;
printf("Inversion of matrix %d x %d %s errors=%d time=%.3f ms",size_m,size_m,errors==0?"passe
return(errors);
}

© 2000-2025, MetaQuotes Ltd.


1460 Matrix and Vector Methods

PInv
Compute the pseudo-inverse of a matrix by the Moore-Penrose method.
matrix matrix::PInv()

Return Value

The pseudo-inverse of matrix.

Example

int TestPseudoInverse(const int size_m, const int size_k)


{
matrix matrix_a(size_m,size_k);
matrix matrix_inverted(size_k,size_m);
matrix matrix_temp;
matrix matrix_a2;
//--- fill the matrix
MatrixTestFirst(matrix_a);
//--- invert
matrix_inverted=matrix_a.PInv();
//--- check the correctness
int errors=0;
//--- A * A+ * A = A (A+ is a pseudo-inverse of A)
matrix_temp=matrix_a.MatMul(matrix_inverted);
matrix_a2=matrix_temp.MatMul(matrix_a);
errors=(int)matrix_a.CompareByDigits(matrix_a2,10);

printf("PseudoInversion %s matrix_size %d x %d errors=%d",errors==0?"passed":"failed",size_m,s


//---
return(errors);
}

© 2000-2025, MetaQuotes Ltd.


1461 Matrix and Vector Methods

Machine learning
These methods are used in machine learning.
The neural network activation function determines the output value of a neuron depending on the
weighted sum of inputs. The selection of the activation function has a big impact on the neural
network performance. Different model parts (layers) can use different activation functions.
In addition to all known activation functions, MQL5 also offers their derivatives. Function derivatives
enable an efficient update of model parameters based on the error received in learning.
A neural network aims at finding an algorithm that minimizes the error in learning, for which the loss
function is used. The value of the loss function indicates by how much the value predicted by the
model deviates from the real one. Different loss functions are used depending on the problem. For
example, Mean Squared Error (M SE) is used for regression problems, and Binary Cross-Entropy (BCE) is
used for binary classification purposes.

Function Action

Activation Compute activation function values and write them to the


passed vector/matrix
Derivative Compute activation function derivative values and write
them to the passed vector/matrix
Loss Compute loss function values and write them to the passed
vector/matrix
Loss Gradient Compute a vector or matrix of loss function gradients
R egressionMetric Compute the regression metric as the deviation error from
the regression line constructed on the specified data array
ConfusionMatrix Compute confusion matrix. The method is applied to the
vector of predicted values
ConfusionMatrixMultilabel Compute confusion matrix for each label. The method is
applied to the vector of predicted values
ClassificationMetric Compute the classification metric to evaluate the quality of
the predicted data compared to the true data The method is
applied to the vector of predicted values
ClassificationS core Compute the classification metric to evaluate the quality of
the predicted data compared to the true data
PrecisionRecall Compute values to construct a precision-recall curve.
S imilarly to ClassificationS core, this method is applied to the
vector of true values
R eceiverOperatingCharacteristic Compute values to construct the Receiver Operating
Characteristic (ROC) curve. S imilarly to ClassificationS core,
this method is applied to the vector of true values.

Example

© 2000-2025, MetaQuotes Ltd.


1462 Matrix and Vector Methods

This example demonstrates the training of a model using matrix operations. The model is trained for
the function (a + b + c)^2 / (a^2 + b^2 + c^2). W e input the initial data matrix, in which a, b and c are
contained in different columns. The function result is obtained at the model output.
matrix weights1, weights2, weights3; // matrices of weights
matrix output1, output2, result; // matrices of neural layer outputs
input int layer1 = 200; // the size of the first hidden layer
input int layer2 = 200; // the size of the second hidden layer
input int Epochs = 20000; // the number of training epochs
input double lr = 3e-6; // learning rate
input ENUM_ACTIVATION_FUNCTION ac_func = AF_SWISH; // activation function
//+------------------------------------------------------------------+
//| Script start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int train = 1000; // training sample size
int test = 10; // test sample size
matrix m_data, m_target;
//--- generate a training sample
if(!CreateData(m_data, m_target, train))
return;
//--- train the model
if(!Train(m_data, m_target, Epochs))
return;
//--- generate a test sample
if(!CreateData(m_data, m_target, test))
return;
//--- test the model
Test(m_data, m_target);
}
//+------------------------------------------------------------------+
//| Sample generation method |
//+------------------------------------------------------------------+
bool CreateData(matrix &data, matrix &target, const int count)
{
//--- initialize the initial data and result matrices
if(!data.Init(count, 3) || !target.Init(count, 1))
return false;
//--- fill the initial data matrix with random values
data.Random(-10, 10);
//--- calculate the target values for the training sample
vector X1 = MathPow(data.Col(0) + data.Col(1) + data.Col(1), 2);
vector X2 = MathPow(data.Col(0), 2) + MathPow(data.Col(1), 2) + MathPow(data.Col(2), 2);
if(!target.Col(X1 / X2, 0))
return false;
//--- return result
return true;

© 2000-2025, MetaQuotes Ltd.


1463 Matrix and Vector Methods

}
//+------------------------------------------------------------------+
//| Model training method |
//+------------------------------------------------------------------+
bool Train(matrix &data, matrix &target, const int epochs = 10000)
{
//--- create the model
if(!CreateNet())
return false;
//--- train the model
for(int ep = 0; ep < epochs; ep++)
{
//--- feedforward pass
if(!FeedForward(data))
return false;
PrintFormat("Epoch %d, loss %.5f", ep, result.Loss(target, LOSS_MSE));
//--- backpropagation and update of weight matrix
if(!Backprop(data, target))
return false;
}
//--- return result
return true;
}
//+------------------------------------------------------------------+
//| Model creation method |
//+------------------------------------------------------------------+
bool CreateNet()
{
//--- initialize weight matrices
if(!weights1.Init(4, layer1) || !weights2.Init(layer1 + 1, layer2) || !weights3.Init(layer2 + 1,
return false;
//--- fill the weight matrices with random values
weights1.Random(-0.1, 0.1);
weights2.Random(-0.1, 0.1);
weights3.Random(-0.1, 0.1);
//--- return result
return true;
}
//+------------------------------------------------------------------+
//| Feedforward method |
//+------------------------------------------------------------------+
bool FeedForward(matrix &data)
{
//--- check the initial data size
if(data.Cols() != weights1.Rows() - 1)
return false;
//--- calculate the first neural layer
matrix temp = data;
if(!temp.Resize(temp.Rows(), weights1.Rows()) ||

© 2000-2025, MetaQuotes Ltd.


1464 Matrix and Vector Methods

!temp.Col(vector::Ones(temp.Rows()), weights1.Rows() - 1))


return false;
output1 = temp.MatMul(weights1);
//--- calculate the activation function
if(!output1.Activation(temp, ac_func))
return false;
//--- calculate the second neural layer
if(!temp.Resize(temp.Rows(), weights2.Rows()) ||
!temp.Col(vector::Ones(temp.Rows()), weights2.Rows() - 1))
return false;
output2 = temp.MatMul(weights2);
//--- calculate the activation function
if(!output2.Activation(temp, ac_func))
return false;
//--- calculate the third neural layer
if(!temp.Resize(temp.Rows(), weights3.Rows()) ||
!temp.Col(vector::Ones(temp.Rows()), weights3.Rows() - 1))
return false;
result = temp.MatMul(weights3);
//--- return result
return true;
}
//+------------------------------------------------------------------+
//| Backpropagation method |
//+------------------------------------------------------------------+
bool Backprop(matrix &data, matrix &target)
{
//--- check the size of the matrix of target values
if(target.Rows() != result.Rows() ||
target.Cols() != result.Cols())
return false;
//--- determine the deviation of calculated values from target
matrix loss = (target - result) * 2;
//--- propagate the gradient to the previous layer
matrix gradient = loss.MatMul(weights3.Transpose());
//--- update the wight matrix of the last layer
matrix temp;
if(!output2.Activation(temp, ac_func))
return false;
if(!temp.Resize(temp.Rows(), weights3.Rows()) ||
!temp.Col(vector::Ones(temp.Rows()), weights3.Rows() - 1))
return false;
weights3 = weights3 + temp.Transpose().MatMul(loss) * lr;
//--- adjust the error gradient by the derivative of the activation function
if(!output2.Derivative(temp, ac_func))
return false;
if(!gradient.Resize(gradient.Rows(), gradient.Cols() - 1))
return false;
loss = gradient * temp;

© 2000-2025, MetaQuotes Ltd.


1465 Matrix and Vector Methods

//--- propagate the gradient to a lower layer


gradient = loss.MatMul(weights2.Transpose());
//--- update the weight matrix of the second hidden layer
if(!output1.Activation(temp, ac_func))
return false;
if(!temp.Resize(temp.Rows(), weights2.Rows()) ||
!temp.Col(vector::Ones(temp.Rows()), weights2.Rows() - 1))
return false;
weights2 = weights2 + temp.Transpose().MatMul(loss) * lr;
//--- adjust the error gradient by the derivative of the activation function
if(!output1.Derivative(temp, ac_func))
return false;
if(!gradient.Resize(gradient.Rows(), gradient.Cols() - 1))
return false;
loss = gradient * temp;
//--- update the weight matrix of the first hidden layer
temp = data;
if(!temp.Resize(temp.Rows(), weights1.Rows()) ||
!temp.Col(vector::Ones(temp.Rows()), weights1.Rows() - 1))
return false;
weights1 = weights1 + temp.Transpose().MatMul(loss) * lr;
//--- return result
return true;
}
//+------------------------------------------------------------------+
//| Model testing method |
//+------------------------------------------------------------------+
bool Test(matrix &data, matrix &target)
{
//--- feedfarward on test data
if(!FeedForward(data))
return false;
//--- log the model calculation results and true values
PrintFormat("Test loss %.5f", result.Loss(target, LOSS_MSE));
ulong total = data.Rows();
for(ulong i = 0; i < total; i++)
PrintFormat("(%.2f + %.2f + %.2f)^2 / (%.2f^2 + %.2f^2 + %.2f^2) = Net %.2f, Target %.2f", d
data[i, 0], data[i, 1], data[i, 2], result[i, 0], target[i, 0]);
//--- return result
return true;
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1466 Matrix and Vector Methods

Activation
Compute activation function values and write them to the passed vector/matrix.
bool vector::Activation(
vector& vect_out, // vector to get values
ENUM_ACTIVATION_FUNCTION activation, // activation function
... // additional parameters
);

bool matrix::Activation(
matrix& matrix_out, // matrix to get values
ENUM_ACTIVATION_FUNCTION activation // activation function
);

bool matrix::Activation(
matrix& matrix_out, // matrix to get values
ENUM_ACTIVATION_FUNCTION activation, // activation function
ENUM_MATRIX_AXIS axis, // axis
... // additional parameters
);

Parameters
vect_out/matrix_out
[out] Vector or matrix to get the computed values of the activation function.
activation
[in] Activation function from the ENUM _ACTIVATION_FUNCTION enumeration.
axis
[in] ENUM _M AT R IX_AXIS enumeration value (AXIS_HORZ — horizontal axis, AXIS_VER T — vertical
axis).
...
[in] Additional parameters required for some activation functions. If no parameters are specified,
default values are used.

Return Value

R eturns true if successful, otherwise - false.

Additional Parameters

S ome activation functions accept additional parameters. If no parameters are specified, default
values are used

© 2000-2025, MetaQuotes Ltd.


1467 Matrix and Vector Methods

AF_ELU (Exponential Linear Unit)


double alpha=1.0

Activation function: if(x>=0) f(x) = x


else f(x) = alpha * (exp(x)-1)

AF_LINEAR
double alpha=1.0
double beta=0.0

Activation function: f(x) = alpha*x + beta

AF_LRELU (Leaky REctified Linear Unit)


double alpha=0.3

Activation function: if(x>=0) f(x)=x


else f(x) = alpha*x

AF_RELU (REctified Linear Unit)


double alpha=0.0
double max_value=0.0
double treshold=0.0

Activation function: if(alpha==0) f(x) = max(x,0)


else if(x>max_value) f(x) = x
else f(x) = alpha*(x - treshold)

AF_SWISH
double beta=1.0

Activation function: f(x) = x / (1+exp(-x*beta))

AF_TRELU (Thresholded REctified Linear Unit)


double theta=1.0

Activation function: if(x>theta) f(x) = x


else f(x) = 0

AF_PRELU (Parametric REctified Linear Unit)


double alpha[] - learned array of coeefficients

© 2000-2025, MetaQuotes Ltd.


1468 Matrix and Vector Methods

Activation function: if(x[i]>=0) f(x)[i] = x[i]


else f(x)[i] = alpha[i] * x[i]

Note

In artificial neural networks, the activation function of a neuron determines the output signal, which
is defined by an input signal or a set of input signals. The selection of the activation function has a
big impact on the neural network performance. Different model parts (layers) can use different
activation functions.

Examples of using additional parameters:

vector x={0.1, 0.4, 0.9, 2.0, -5.0, 0.0, -0.1};


vector y;

x.Activation(y,AF_ELU);
Print(y);
x.Activation(y,AF_ELU,2.0);
Print(y);

Print("");
x.Activation(y,AF_LINEAR);
Print(y);
x.Activation(y,AF_LINEAR,2.0);
Print(y);
x.Activation(y,AF_LINEAR,2.0,5.0);
Print(y);

Print("");
x.Activation(y,AF_LRELU);
Print(y);
x.Activation(y,AF_LRELU,1.0);
Print(y);
x.Activation(y,AF_LRELU,0.1);
Print(y);

Print("");
x.Activation(y,AF_RELU);
Print(y);
x.Activation(y,AF_RELU,2.0,0.5);
Print(y);
x.Activation(y,AF_RELU,2.0,0.5,1.0);
Print(y);

Print("");
x.Activation(y,AF_SWISH);
Print(y);

© 2000-2025, MetaQuotes Ltd.


1469 Matrix and Vector Methods

x.Activation(y,AF_SWISH,2.0);
Print(y);

Print("");
x.Activation(y,AF_TRELU);
Print(y);
x.Activation(y,AF_TRELU,0.3);
Print(y);

Print("");
vector a=vector::Full(x.Size(),2.0);
x.Activation(y,AF_PRELU,a);
Print(y);

/* Results
[0.1,0.4,0.9,2,-0.993262053000915,0,-0.095162581964040]
[0.1,0.4,0.9,2,-1.986524106001829,0,-0.190325163928081]

[0.1,0.4,0.9,2,-5,0,-0.1]
[0.2,0.8,1.8,4,-10,0,-0.2]
[5.2,5.8,6.8,9,-5,5,4.8]

[0.1,0.4,0.9,2,-1.5,0,-0.03]
[0.1,0.4,0.9,2,-5,0,-0.1]
[0.1,0.4,0.9,2,-0.5,0,-0.01]

[0.1,0.4,0.9,2,0,0,0]
[0.2,0.8,0.9,2,-10,0,-0.2]
[-1.8,-1.2,0.9,2,-12,-2,-2.2]

[0.052497918747894,0.239475064044981,0.6398545523625035,1.761594155955765,-0.03346425462142428,0
[0.054983399731247,0.275989792451045,0.7723340415895611,1.964027580075817,-0.00022698934351217,0

[0,0,0,2,0,0,0]
[0,0.4,0.9,2,0,0,0]

[0.1,0.4,0.9,2,-10,0,-0.2]
*/

© 2000-2025, MetaQuotes Ltd.


1470 Matrix and Vector Methods

Derivative
Compute activation function derivative values and write them to the passed vector/matrix
bool vector::Derivative(
vector& vect_out, // vector to get values
ENUM_ACTIVATION_FUNCTION activation, // activation function
... // additional parameters
);

bool matrix::Derivative(
matrix& matrix_out, // matrix to get values
ENUM_ACTIVATION_FUNCTION activation, // activation function
);

bool matrix::Derivative(
matrix& matrix_out, // matrix to get values
ENUM_ACTIVATION_FUNCTION activation, // activation function
ENUM_MATRIX_AXIS axis, // axis
... // additional parameters
);

Parameters
vect_out/matrix_out
[out] Vector or matrix to get the computed values of the derivative of the activation function.
activation
[in] Activation function from the ENUM _ACTIVATION_FUNCTION enumeration.
axis
[in] ENUM _M AT R IX_AXIS enumeration value (AXIS_HORZ — horizontal axis, AXIS_VER T — vertical
axis).
...
[in] Additional parameters are the same as that of the activation functions. Only some activation
functions accept additional parameters. If no parameters are specified, default values are used.

Return Value

R eturns true if successful, otherwise - false.

Note

Function derivatives enable an efficient update of model parameters based on the error received in
learning during the error backpropagation.

© 2000-2025, MetaQuotes Ltd.


1471 Matrix and Vector Methods

© 2000-2025, MetaQuotes Ltd.


1472 Matrix and Vector Methods

Loss
Compute the value of the loss function.
double vector::Loss(
const vector& vect_true, // vector of true values
ENUM_LOSS_FUNCTION loss, // loss function
... // additional parameter
);

double matrix::Loss(
const matrix& matrix_true, // matrix of true values
ENUM_LOSS_FUNCTION loss, // loss function
);

double matrix::Loss(
const matrix& matrix_true, // matrix of true values
ENUM_LOSS_FUNCTION loss, // loss function
ENUM_MATRIX_AXIS axis, // axis
... // additional parameter
);

Parameters
vect_true/matrix_true
[in] Vector or matrix of true values.
loss
[in] Loss function from the ENUM _LOSS_FUNCTION enumeration.
axis
[in] ENUM _M AT R IX_AXIS enumeration value (AXIS_HORZ — horizontal axis, AXIS_VER T — vertical
axis).
...
[in] Additional parameter 'delta' can only be used by the H ubert loss function (LOSS_HUBER)

Return Value

double value.

How the 'delta' parameter is used in the Hubert loss function (LOSS_HUBER)
double delta = 1.0;
double error = fabs(y - x);
if(error<delta)
loss = 0.5 * error^2;
else

© 2000-2025, MetaQuotes Ltd.


1473 Matrix and Vector Methods

loss = 0.5 * delta^2 + delta * (error - delta);

Note

Aneural network aims at finding the algorithms that minimize the error on the training sample, for
which the loss function is used.
The value of the loss function indicates by how much the value predicted by the model deviates from
the real one.
Different lossfunctions are used depending on the problem. For example, Mean Squared Error (M SE)
is used for regression problems, and Binary Cross-Entropy (BCE) is used for binary classification
purposes.

Example of calling the Hubert loss function:

vector y_true = {0.0, 1.0, 0.0, 0.0};


vector y_pred = {0.6, 0.4, 0.4, 0.6};
double loss=y_pred.Loss(y_true,LOSS_HUBER);
Print(loss);
double loss2=y_pred.Loss(y_true,LOSS_HUBER,0.5);
Print(loss2);

/* Result
0.155
0.15125
*/

© 2000-2025, MetaQuotes Ltd.


1474 Matrix and Vector Methods

LossGradient
Compute a vector or matrix of loss function gradients.
vector vector::LossGradient(
const vector& vect_true, // vector of true values
ENUM_LOSS_FUNCTION loss, // loss function type
... // additional parameter
);

matrix matrix::LossGradient(
const matrix& matrix_true, // matrix of true values
ENUM_LOSS_FUNCTION loss, // loss function
);

matrix matrix::LossGradient(
const matrix& matrix_true, // matrix of true values
ENUM_LOSS_FUNCTION loss, // loss function
ENUM_MATRIX_AXIS axis, // axis
... // additional parameter
);

Parameters
vect_true/matrix_true
[in] Vector or matrix of true values.
loss
[in] Loss function from the ENUM _LOSS_FUNCTION enumeration.
axis
[in] ENUM _M AT R IX_AXIS enumeration value (AXIS_HORZ — horizontal axis, AXIS_VER T — vertical
axis).
...
[in] Additional parameter 'delta' can only be used by the H ubert loss function (LOSS_HUBER)

Return Value

Vector or matrix of loss function gradient values. The gradient is the partial derivative with respect
to dx (x is the predicted value) of the loss function at a given point.

Note

Gradients are used in neural networks to adjust the weight matrix weights during backpropagation,
when training the model.

© 2000-2025, MetaQuotes Ltd.


1475 Matrix and Vector Methods

Aneural network aims at finding the algorithms that minimize the error on the training sample, for
which the loss function is used.
Different lossfunctions are used depending on the problem. For example, Mean Squared Error (M SE)
is used for regression problems, and Binary Cross-Entropy (BCE) is used for binary classification
purposes.

Example of calculating loss function gradients

matrixf y_true={{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9,10,11,12 }};
matrixf y_pred={{ 1, 2, 3, 4 },
{11,10, 9, 8 },
{ 5, 6, 7,12 }};
matrixf loss_gradient =y_pred.LossGradient(y_true,LOSS_MAE);
matrixf loss_gradienth=y_pred.LossGradient(y_true,LOSS_MAE,AXIS_HORZ);
matrixf loss_gradientv=y_pred.LossGradient(y_true,LOSS_MAE,AXIS_VERT);
Print("loss gradients\n",loss_gradient);
Print("loss gradients on horizontal axis\n",loss_gradienth);
Print("loss gradients on vertical axis\n",loss_gradientv);

/* Result
loss gradients
[[0,0,0,0]
[0.083333336,0.083333336,0.083333336,0]
[-0.083333336,-0.083333336,-0.083333336,0]]
loss gradients on horizontal axis
[[0,0,0,0]
[0.33333334,0.33333334,0.33333334,0]
[-0.33333334,-0.33333334,-0.33333334,0]]
loss gradients on vertical axis
[[0,0,0,0]
[0.25,0.25,0.25,0]
[-0.25,-0.25,-0.25,0]]
*/

© 2000-2025, MetaQuotes Ltd.


1476 Matrix and Vector Methods

RegressionMetric
Compute the regression metric to evaluate the quality of the predicted data compared to the true data
double vector::RegressionMetric(
const vector& vector_true, // vector of true values
ENUM_REGRESSION_METRIC metric // metric type
);

double matrix::RegressionMetric(
const matrix& matrix_true, // matrix of true values
ENUM_REGRESSION_METRIC metric // metric type
);

vector matrix::RegressionMetric(
const matrix& matrix_true, // matrix of true values
ENUM_REGRESSION_METRIC metric, // metric type
int axis // axis
);

Parameters
vector_true/matrix_true
[in] Vector or matrix of true values.
metric
[in] Metric type from the ENUM _REGRESS ION_M ETRIC enumeration.
axis
[in] Axis. 0 — horizontal axis, 1 — vertical axis.

Return Value

The calculated metric which evaluates the quality of the predicted data compared to the true data.

Note
· REGRESS ION_M AE — mean absolute error which represents the absolute differences between
predicted values and corresponding true values
· REGRESS ION_M SE — mean s quare error which represents the s quared differences between
predicted values and corresponding true values
· REGRESS ION_R M SE — s quare root of M SE
· REGRESS ION_R2 - 1 — M SE(regression) / M SE(mean)
· REGRESS ION_M APE — M AE as a percentage
· REGRESS ION_M S PE — M SE as a percentage
· REGRESS ION_R M S L E — R M SE computed on a logarithmic scale

Example:

© 2000-2025, MetaQuotes Ltd.


1477 Matrix and Vector Methods

vector y_true = {3, -0.5, 2, 7};


vector y_pred = {2.5, 0.0, 2, 8};
//---
double mse=y_pred.RegressionMetric(y_true,REGRESSION_MSE);
Print("mse=",mse);
//---
double mae=y_pred.RegressionMetric(y_true,REGRESSION_MAE);
Print("mae=",mae);
//---
double r2=y_pred.RegressionMetric(y_true,REGRESSION_R2);
Print("r2=",r2);

/* Result
mae=0.375
mse=0.5
r2=0.9486081370449679
*/

© 2000-2025, MetaQuotes Ltd.


1478 Matrix and Vector Methods

ConfusionMatrix
Compute confusion matrix. The method is applied to the vector of predicted values.
matrix vector::ConfusionMatrix(
const vector& vect_true // vector of true values
);

matrix vector::ConfusionMatrix(
const vector& vect_true, // vector of true values
uint label // label value
);

Parameters
vect_true
[in] Vector of true values.
label
[in] Label value for calculating the confusion matrix.

Return Value

Confusion matrix. If a label value is not specified, a multi-class confusion matrix is returned, where
each label is matched to each other label individually. If a label value is specified, a 2 x 2 matrix is
returned, in which the specified label is considered positive, while all other labels are negative (ovr,
one vs rest).

Note

Confusion matrix C is such that Cij is equal to the number of observations known to be in group i
and predicted to be in group j. Thus in binary classification, the count of true negatives (TN) is C00,
false negatives (FN) is C10, true positives (TP) is C11 and false positives (FP) is C01.
In other words, the matrix can be graphically represented as follows :

TN FP

FN TP

The sizes of the vector of true values and the vector of predicted values should be the same.

Example:

vector y_true={7,2,1,0,4,1,4,9,5,9,0,6,9,0,1,5,9,7,3,4,8,4,2,7,6,8,4,2,3,6};
vector y_pred={7,2,1,0,4,1,4,9,5,9,0,6,9,0,1,5,9,7,3,4,2,9,4,9,5,9,2,7,7,0};
matrix confusion=y_pred.ConfusionMatrix(y_true);

© 2000-2025, MetaQuotes Ltd.


1479 Matrix and Vector Methods

Print(confusion);
confusion=y_pred.ConfusionMatrix(y_true,0);
Print(confusion);
confusion=y_pred.ConfusionMatrix(y_true,1);
Print(confusion);
confusion=y_pred.ConfusionMatrix(y_true,2);
Print(confusion);

/*
[[3,0,0,0,0,0,0,0,0,0]
[0,3,0,0,0,0,0,0,0,0]
[0,0,1,0,1,0,0,1,0,0]
[0,0,0,1,0,0,0,1,0,0]
[0,0,1,0,3,0,0,0,0,1]
[0,0,0,0,0,2,0,0,0,0]
[1,0,0,0,0,1,1,0,0,0]
[0,0,0,0,0,0,0,2,0,1]
[0,0,1,0,0,0,0,0,0,1]
[0,0,0,0,0,0,0,0,0,4]]
[[26,1]
[0,3]]
[[27,0]
[0,3]]
[[25,2]
[2,1]]
*/

© 2000-2025, MetaQuotes Ltd.


1480 Matrix and Vector Methods

ConfusionMatrixMultilabel
Compute confusion matrix for each label. The method is applied to the vector of predicted values.
uint vector::ConfusionMatrixMultiLabel(
const vector& vect_true, // vector of true values
matrix& confusions[] // array of calculated confusion matrices
);

Parameters
vect_true
[in] Vector of true values.
confusions
[out] An array of 2 x 2 matrices with computed confusion matrices for each label.

Return Value

S ize of the array of calculated confusion matrices. In case of failure, it returns 0

Note

The result array can be dynamic or static. If the array is static, then it must be no less in size than
the number of classes.
The sizes of the vector of true values and the vector of predicted values should be the same.

Example:

vector y_true={7,2,1,0,4,1,4,9,5,9,0,6,9,0,1,5,9,7,3,4,8,4,2,7,6,8,4,2,3,6};
vector y_pred={7,2,1,0,4,1,4,9,5,9,0,6,9,0,1,5,9,7,3,4,2,9,4,9,5,9,2,7,7,0};
matrix label_confusions[12];

uint res=y_pred.ConfusionMatrixMultiLabel(y_true,label_confusions);
Print("res=",res," size=",label_confusions.Size());
for(uint i=0; i<res; i++)
Print(label_confusions[i]);

/*
res=10 size=12
[[26,1]
[0,3]]
[[27,0]
[0,3]]
[[25,2]
[2,1]]

© 2000-2025, MetaQuotes Ltd.


1481 Matrix and Vector Methods

[[28,0]
[1,1]]
[[24,1]
[2,3]]
[[27,1]
[0,2]]
[[27,0]
[2,1]]
[[25,2]
[1,2]]
[[28,0]
[2,0]]
[[23,3]
[0,4]]
*/

© 2000-2025, MetaQuotes Ltd.


1482 Matrix and Vector Methods

ClassificationMetric
Compute the classification metric to evaluate the quality of the predicted data compared to the true
data. The method is applied to the vector of predicted values.
vector vector::ClassificationMetric(
const vector& vect_true, // vector of true values
ENUM_CLASSIFICATION_METRIC metric // metric type
);

vector vector::ClassificationMetric(
const vector& vect_true, // vector of true values
ENUM_CLASSIFICATION_METRIC metric // metric type
ENUM_AVERAGE_MODE mode // averaging mode
);

Parameters
vect_true
[in] Vector of true values.
metric
[in] Metric type from the ENUM _CL ASS IFICATION_M ET R IC enumeration. Values other than
CLASS IFICATION_TOP_K_ACCURACY, CLASS IFICATION_AVERAGE_PRECIS ION and
CLASS IFICATION_ROC_AUC (used in the ClassificationS core method) are applied.
mode
[in] Averaging mode from the ENUM _AVERAGE_MODE enumeration. Used for the
CLASS IFICATION_F1, CLASS IFICATION_JACCARD, CLASS IFICATION_PRECIS ION and
CLASS IFICATION_RECALL metrics.

Return Value

A vector containing the calculated metric. In the case of the AVERAGE_NONE averaging mode, the
vector contains metric values for each class without averaging. (For example, in case of the binary
classification, this would be two metrics for 'false' and 'true' respectively).

Note about averaging modes

AVERAGE_BINARY is only meaningful for binary classification.


AVERAGE_MICR O — calculate metrics globally by counting the total true positives, false negatives
and false positives.
AVERAGE_M ACR O — calculate metrics for each label and find their unweighted mean. This does not
take label imbalance into account.
AVERAGE_WEIGH T ED — calculate metrics for each label and find their average weighted by support
(the number of true instances for each label). This alters ‘macro’ to account for label imbalance; it
can result in an F-score that is not between precision and recall.

© 2000-2025, MetaQuotes Ltd.


1483 Matrix and Vector Methods

Note

In case of binary classification, we can input not only an n x 2 matrix, where the first column
contains probabilities for a negative label, and the second column contains probabilities for a
positive label, but also a matrix consisting of one column with positive probabilities. This is because
binary classification models can return either two probabilities or one probability for a positive label.

Example:

vector y_true={7,2,1,0,4,1,4,9,5,9,0,6,9,0,1,5,9,7,3,4,8,4,2,7,6,8,4,2,3,6};
vector y_pred={7,2,1,0,4,1,4,9,5,9,0,6,9,0,1,5,9,7,3,4,2,9,4,9,5,9,2,7,7,0};

vector accuracy=y_pred.ClassificationMetric(y_true,CLASSIFICATION_ACCURACY);
Print("accuracy=",accuracy);
vector balanced=y_pred.ClassificationMetric(y_true,CLASSIFICATION_BALANCED_ACCURACY);
Print("balanced=",balanced);
Print("");

vector f1_micro=y_pred.ClassificationMetric(y_true,CLASSIFICATION_F1,AVERAGE_MICRO);
Print("f1_micro=",f1_micro);
vector f1_macro=y_pred.ClassificationMetric(y_true,CLASSIFICATION_F1,AVERAGE_MACRO);
Print("f1_macro=",f1_macro);
vector f1_weighted=y_pred.ClassificationMetric(y_true,CLASSIFICATION_F1,AVERAGE_WEIGHTED);
Print("f1_weighted=",f1_weighted);
vector f1_none=y_pred.ClassificationMetric(y_true,CLASSIFICATION_F1,AVERAGE_NONE);
Print("f1_none=",f1_none);
Print("");

vector jaccard_micro=y_pred.ClassificationMetric(y_true,CLASSIFICATION_JACCARD,AVERAGE_MICRO);
Print("jaccard_micro=",jaccard_micro);
vector jaccard_macro=y_pred.ClassificationMetric(y_true,CLASSIFICATION_JACCARD,AVERAGE_MACRO);
Print("jaccard_macro=",jaccard_macro);
vector jaccard_weighted=y_pred.ClassificationMetric(y_true,CLASSIFICATION_JACCARD,AVERAGE_WEIGHT
Print("jaccard_weighted=",jaccard_weighted);
vector jaccard_none=y_pred.ClassificationMetric(y_true,CLASSIFICATION_JACCARD,AVERAGE_NONE);
Print("jaccard_none=",jaccard_none);
Print("");

vector precision_micro=y_pred.ClassificationMetric(y_true,CLASSIFICATION_PRECISION,AVERAGE_MICRO
Print("precision_micro=",precision_micro);
vector precision_macro=y_pred.ClassificationMetric(y_true,CLASSIFICATION_PRECISION,AVERAGE_MACRO
Print("precision_macro=",precision_macro);
vector precision_weighted=y_pred.ClassificationMetric(y_true,CLASSIFICATION_PRECISION,AVERAGE_WE
Print("precision_weighted=",precision_weighted);
vector precision_none=y_pred.ClassificationMetric(y_true,CLASSIFICATION_PRECISION,AVERAGE_NONE);
Print("precision_none=",precision_none);
Print("");

© 2000-2025, MetaQuotes Ltd.


1484 Matrix and Vector Methods

vector recall_micro=y_pred.ClassificationMetric(y_true,CLASSIFICATION_RECALL,AVERAGE_MICRO);
Print("recall_micro=",recall_micro);
vector recall_macro=y_pred.ClassificationMetric(y_true,CLASSIFICATION_RECALL,AVERAGE_MACRO);
Print("recall_macro=",recall_macro);
vector recall_weighted=y_pred.ClassificationMetric(y_true,CLASSIFICATION_RECALL,AVERAGE_WEIGHTED
Print("recall_weighted=",recall_weighted);
vector recall_none=y_pred.ClassificationMetric(y_true,CLASSIFICATION_RECALL,AVERAGE_NONE);
Print("recall_none=",recall_none);
Print("");

//--- binary classification


vector y_pred_bin={0,1,0,1,1,0,0,0,1};
vector y_true_bin={1,0,0,0,1,0,1,1,1};

vector f1_bin=y_pred_bin.ClassificationMetric(y_true_bin,CLASSIFICATION_F1,AVERAGE_BINARY);
Print("f1_bin=",f1_bin);
vector jaccard_bin=y_pred_bin.ClassificationMetric(y_true_bin,CLASSIFICATION_JACCARD,AVERAGE_BIN
Print("jaccard_bin=",jaccard_bin);
vector precision_bin=y_pred_bin.ClassificationMetric(y_true_bin,CLASSIFICATION_PRECISION,AVERAGE
Print("precision_bin=",precision_bin);
vector recall_bin=y_pred_bin.ClassificationMetric(y_true_bin,CLASSIFICATION_RECALL,AVERAGE_BINAR
Print("recall_bin=",recall_bin);

/*
accuracy=[0.6666666666666666]
balanced=[0.6433333333333333]

f1_micro=[0.6666666666666666]
f1_macro=[0.6122510822510823]
f1_weighted=[0.632049062049062]
f1_none=[0.8571428571428571,1,0.3333333333333333,0.6666666666666666,0.6666666666666665,0.8,0.5,0.

jaccard_micro=[0.5]
jaccard_macro=[0.4921428571428572]
jaccard_weighted=[0.5056349206349205]
jaccard_none=[0.75,1,0.2,0.5,0.5,0.6666666666666666,0.3333333333333333,0.4,0,0.5714285714285714]

precision_micro=[0.6666666666666666]
precision_macro=[0.6571428571428571]
precision_weighted=[0.6706349206349207]
precision_none=[0.75,1,0.3333333333333333,1,0.75,0.6666666666666666,1,0.5,0,0.5714285714285714]

recall_micro=[0.6666666666666666]
recall_macro=[0.6433333333333333]
recall_weighted=[0.6666666666666666]
recall_none=[1,1,0.3333333333333333,0.5,0.6,1,0.3333333333333333,0.6666666666666666,0,1]

f1_bin=[0.4444444444444445]

© 2000-2025, MetaQuotes Ltd.


1485 Matrix and Vector Methods

jaccard_bin=[0.2857142857142857]
precision_bin=[0.5]
recall_bin=[0.4]
*/

© 2000-2025, MetaQuotes Ltd.


1486 Matrix and Vector Methods

ClassificationScore
Compute the classification metric to evaluate the quality of the predicted data compared to the true
data.
Unlik eother methods in the Machine Learning section, this one applies to the vector of true values
rather than the vector of predicted values.
vector vector::ClassificationScore(
const matrix& pred_scores, // matrix containing probability distribution for each
ENUM_CLASSIFICATION_METRIC metric // metric type
ENUM_AVERAGE_MODE mode // averaging mode
);

vector vector::ClassificationScore(
const matrix& pred_scores, // matrix containing probability distribution for each
ENUM_CLASSIFICATION_METRIC metric // metric type
int param // additional parameter
);

Parameters
pred_scores
[in] Amatrix containing a set of horizontal vectors with probabilities for each class. The number
of matrix rows should correspond to the size of the vector of true values.
metric
[in] Metric type from the ENUM _CLASS IFICATION_M ETRIC enumeration. The
CLASS IFICATION_TOP_K_ACCURACY, CLASS IFICATION_AVERAGE_PRECIS ION and
CLASS IFICATION_ROC_AUC values are used.
mode
[in] Averaging mode from the ENUM _AVERAGE_MODE enumeration. Used for the
CLASS IFICATION_AVERAGE_PRECIS ION and CLASS IFICATION_ROC_AUC metrics.
param
[in] In case of the CLASS IFICATION_TOP_K_ACCURACY metric, the integer K value should be
specified instead of the averaging mode.

Return Value

A vector containing the calculated metric. In the case of the AVERAGE_NONE averaging mode, the
vector contains metric values for each class without averaging. (For example, in case of the binary
classification, this would be two metrics for 'false' and 'true' respectively).

Note about averaging modes

AVERAGE_BINARY is only meaningful for binary classification.

© 2000-2025, MetaQuotes Ltd.


1487 Matrix and Vector Methods

AVERAGE_MICR O — calculate metrics globally by considering each element of the label indicator
matrix as a label. The label indicator matrix refers to a matrix with a set of probabilities for each
label.
AVERAGE_M ACR O — calculate metrics for each label and find their unweighted mean. This does not
take label imbalance into account.
AVERAGE_WEIGH T ED — calculate metrics for each label and find their average weighted by support
(the number of true instances for each label).
Note

In case of binary classification, we can input not only an n x 2 matrix, where the first column
contains probabilities for a negative label, and the second column contains probabilities for a
positive label, but also a matrix consisting of one column with positive probabilities. This is because
binary classification models can return either two probabilities or one probability for a positive label.

Example:

vector y_true={7,2,1,0,4,1,4,9,5,9,0,6,9,0,1,5,9,7,3,4,8,4,2,7,6,8,4,2,3,6};
//vector y_pred={7,2,1,0,4,1,4,9,5,9,0,6,9,0,1,5,9,7,3,4,2,9,4,9,5,9,2,7,7,0};

//--- label scores 0 1 2 3 4 5 6 7


matrix y_scores={{0.000109, 0.000186, 0.000449, 0.000052, 0.000002, 0.000022, 0.000005, 0.998059
{0.000091, 0.081956, 0.916816, 0.001106, 0.000006, 0.000002, 0.000001, 0.000000
{0.000108, 0.972863, 0.003600, 0.000021, 0.010479, 0.000015, 0.000131, 0.010385
{0.925425, 0.000080, 0.002913, 0.000057, 0.000274, 0.000638, 0.063529, 0.000316
{0.000060, 0.000126, 0.000006, 0.000000, 0.993513, 0.000000, 0.000003, 0.000222
{0.000016, 0.982124, 0.000045, 0.000002, 0.008445, 0.000001, 0.000005, 0.009230
{0.000000, 0.000040, 0.000001, 0.000000, 0.989395, 0.000167, 0.000004, 0.000070
{0.000795, 0.002938, 0.023447, 0.007418, 0.021838, 0.002476, 0.000260, 0.047551
{0.000091, 0.000226, 0.000038, 0.000007, 0.000048, 0.854910, 0.068644, 0.000080
{0.000000, 0.000000, 0.000000, 0.000000, 0.003004, 0.000000, 0.000000, 0.000035
{0.998856, 0.000009, 0.000976, 0.000002, 0.000000, 0.000013, 0.000131, 0.000006
{0.000178, 0.000446, 0.000326, 0.000033, 0.000193, 0.000071, 0.998403, 0.000015
{0.000005, 0.000016, 0.000153, 0.000045, 0.004110, 0.000012, 0.000015, 0.000031
{0.994188, 0.000003, 0.002584, 0.000005, 0.000005, 0.000100, 0.000739, 0.001473
{0.000173, 0.990569, 0.000792, 0.000040, 0.001798, 0.000035, 0.000114, 0.004750
{0.000000, 0.000537, 0.000008, 0.005080, 0.000046, 0.992910, 0.000012, 0.000671
{0.000127, 0.000003, 0.000003, 0.000000, 0.001583, 0.000000, 0.000002, 0.000555
{0.000001, 0.000012, 0.000072, 0.000020, 0.000000, 0.000000, 0.000000, 0.999868
{0.000020, 0.000105, 0.001139, 0.901343, 0.002132, 0.083873, 0.000124, 0.000097
{0.000002, 0.000048, 0.000019, 0.000000, 0.999347, 0.000002, 0.000040, 0.000051
{0.000059, 0.001344, 0.612502, 0.002749, 0.000229, 0.000678, 0.000038, 0.001844
{0.000586, 0.000740, 0.001625, 0.000007, 0.269341, 0.000076, 0.016417, 0.000199
{0.009547, 0.018055, 0.283795, 0.071079, 0.426074, 0.082335, 0.036379, 0.021188
{0.002506, 0.002545, 0.001148, 0.005659, 0.020416, 0.000112, 0.006092, 0.272536
{0.001263, 0.001769, 0.000293, 0.000011, 0.000302, 0.881768, 0.112019, 0.000125
{0.002904, 0.002909, 0.013421, 0.001461, 0.007519, 0.001251, 0.000555, 0.106219
{0.000055, 0.001080, 0.893158, 0.000000, 0.104492, 0.000159, 0.001042, 0.000013

© 2000-2025, MetaQuotes Ltd.


1488 Matrix and Vector Methods

{0.000344, 0.002693, 0.071184, 0.000262, 0.000001, 0.000003, 0.000032, 0.924362


{0.001404, 0.009375, 0.002638, 0.229189, 0.000064, 0.000896, 0.007516, 0.743557
{0.491140, 0.000125, 0.000024, 0.000302, 0.000038, 0.034947, 0.473161, 0.000170

vector top_k=y_true.ClassificationScore(y_scores,CLASSIFICATION_TOP_K_ACCURACY,1);
Print("top 1 accuracy score = ",top_k);
top_k=y_true.ClassificationScore(y_scores,CLASSIFICATION_TOP_K_ACCURACY,2);
Print("top 2 accuracy score = ",top_k);
vector y_true2={0, 1, 2, 2};
matrix y_score2={{0.5, 0.2, 0.2}, // 0 is in top 2
{0.3, 0.4, 0.2}, // 1 is in top 2
{0.2, 0.4, 0.3}, // 2 is in top 2
{0.7, 0.2, 0.1}}; // 2 isn't in top 2
top_k=y_true2.ClassificationScore(y_score2,CLASSIFICATION_TOP_K_ACCURACY,2);
Print("top k = ",top_k);
Print("");

vector ap_micro=y_true.ClassificationScore(y_scores,CLASSIFICATION_AVERAGE_PRECISION,AVERAGE_MIC
Print("average precision score micro = ",ap_micro);
vector ap_macro=y_true.ClassificationScore(y_scores,CLASSIFICATION_AVERAGE_PRECISION,AVERAGE_MAC
Print("average precision score macro = ",ap_macro);
vector ap_weighted=y_true.ClassificationScore(y_scores,CLASSIFICATION_AVERAGE_PRECISION,AVERAGE_
Print("average precision score weighted = ",ap_weighted);
vector ap_none=y_true.ClassificationScore(y_scores,CLASSIFICATION_AVERAGE_PRECISION,AVERAGE_NONE
Print("average precision score none = ",ap_none);
Print("");

vector area_micro=y_true.ClassificationScore(y_scores,CLASSIFICATION_ROC_AUC,AVERAGE_MICRO);
Print("roc auc score micro = ",area_micro);
vector area_macro=y_true.ClassificationScore(y_scores,CLASSIFICATION_ROC_AUC,AVERAGE_MACRO);
Print("roc auc score macro = ",area_macro);
vector area_weighted=y_true.ClassificationScore(y_scores,CLASSIFICATION_ROC_AUC,AVERAGE_WEIGHTED
Print("roc auc score weighted = ",area_weighted);
vector area_none=y_true.ClassificationScore(y_scores,CLASSIFICATION_ROC_AUC,AVERAGE_NONE);
Print("roc auc score none = ",area_none);
Print("");

//--- binary classification


vector y_pred_bin={0,1,0,1,1,0,0,0,1};
vector y_true_bin={1,0,0,0,1,0,1,1,1};
vector y_score_true={0.3,0.7,0.1,0.6,0.9,0.0,0.4,0.2,0.8};
matrix y_score1_bin(y_score_true.Size(),1);
y_score1_bin.Col(y_score_true,0);
matrix y_scores_bin={{0.7, 0.3},
{0.3, 0.7},
{0.9, 0.1},
{0.4, 0.6},
{0.1, 0.9},
{1.0, 0.0},

© 2000-2025, MetaQuotes Ltd.


1489 Matrix and Vector Methods

{0.6, 0.4},
{0.8, 0.2},
{0.2, 0.8}};

vector ap=y_true_bin.ClassificationScore(y_scores_bin,CLASSIFICATION_AVERAGE_PRECISION,AVERAGE_B
Print("average precision score binary = ",ap);
vector ap2=y_true_bin.ClassificationScore(y_score1_bin,CLASSIFICATION_AVERAGE_PRECISION,AVERAGE_
Print("average precision score binary = ",ap2);
vector ap3=y_true_bin.ClassificationScore(y_scores_bin,CLASSIFICATION_AVERAGE_PRECISION,AVERAGE_
Print("average precision score none = ",ap3);
Print("");

vector area=y_true_bin.ClassificationScore(y_scores_bin,CLASSIFICATION_ROC_AUC,AVERAGE_BINARY);
Print("roc auc score binary = ",area);
vector area2=y_true_bin.ClassificationScore(y_score1_bin,CLASSIFICATION_ROC_AUC,AVERAGE_BINARY);
Print("roc auc score binary = ",area2);
vector area3=y_true_bin.ClassificationScore(y_scores_bin,CLASSIFICATION_ROC_AUC,AVERAGE_NONE);
Print("roc auc score none = ",area3);

/*
top 1 accuracy score = [0.6666666666666666]
top 2 accuracy score = [1]
top k = [0.75]

average precision score micro = [0.8513333333333333]


average precision score macro = [0.9326666666666666]
average precision score weighted = [0.9333333333333333]
average precision score none = [1,1,0.7,1,0.9266666666666666,0.8333333333333333,1,0.8666666666666

roc auc score micro = [0.9839506172839506]


roc auc score macro = [0.9892068783068803]
roc auc score weighted = [0.9887354497354497]
roc auc score none = [1,1,0.9506172839506173,1,0.984,0.9821428571428571,1,0.9753086419753086,1,1]

average precision score binary = [0.7961904761904761]


average precision score binary = [0.7961904761904761]
average precision score none = [0.7678571428571428,0.7961904761904761]

roc auc score binary = [0.7]


roc auc score binary = [0.7]
roc auc score none = [0.7,0.7]
*/

© 2000-2025, MetaQuotes Ltd.


1490 Matrix and Vector Methods

PrecisionRecall
Compute values to construct a precision-recall curve. S imilarly to ClassificationS core, this method is
applied to the vector of true values.
bool vector::PrecisionRecall(
const matrix& pred_scores, // matrix containing the probability distribution f
const ENUM_ENUM_AVERAGE_MODE mode // averaging mode
matrix& precision, // calculated precision values for each threshold v
matrix& recall, // calculated recall values for each threshold valu
matrix& thresholds, // threshold values sorted in descending order
);

Parameters
pred_scores
[in] Amatrix containing a set of horizontal vectors with probabilities for each class. The number
of matrix rows must correspond to the size of the vector of true values.
mode
[in] Averaging mode from the ENUM _AVERAGE_MODE enumeration. Only AVERAGE_NONE,
AVERAGE_BINARY and AVERAGE_MICR O are used.

precision
[out] A matrix with calculated precision curve values. If no averaging is applied (AVERAGE_NONE),
the number of rows in the matrix corresponds to the number of model classes. The number of
columns corresponds to the size of the vector of true values (or the number of rows in the
probability distribution matrix pred_score). In the case of microaveraging, the number of rows in
the matrix corresponds to the total number of threshold values, excluding duplicates.
recall
[out] A matrix with calculated recall curve values.
threshold
[out] Threshold matrix obtained by sorting the probability matrix

Note

S ee notes for the ClassificationS core method.

Example

An example of collecting statistics from the mnist.onnx model (99% accuracy).


//--- data for classification metrics
vectorf y_true(images);
vectorf y_pred(images);
matrixf y_scores(images,10);
//--- input-output
matrixf image(28,28);

© 2000-2025, MetaQuotes Ltd.


1491 Matrix and Vector Methods

vectorf result(10);

//--- testing
for(int test=0; test<images; test++)
{
image=test_data[test].image;
if(!OnnxRun(model,ONNX_DEFAULT,image,result))
{
Print("OnnxRun error ",GetLastError());
break;
}
result.Activation(result,AF_SOFTMAX);
//--- collect data
y_true[test]=(float)test_data[test].label;
y_pred[test]=(float)result.ArgMax();
y_scores.Row(result,test);
} }

Accuracy calculation

vectorf accuracy=y_pred.ClassificationMetric(y_true,CLASSIFICATION_ACCURACY);
PrintFormat("accuracy=%f",accuracy[0]);

accuracy=0.989000

An example of plotting precision-recall graphs, where precision values are plotted on the y-axis and
recall values are plotted on the x-axis. Also precision and recall graphs are plotted separately, with
threshold values plotted on the x-axis
if(y_true.PrecisionRecall(y_scores,AVERAGE_MICRO,mat_precision,mat_recall,mat_thres))
{
double precision[],recall[],thres[];
ArrayResize(precision,mat_thres.Cols());
ArrayResize(recall,mat_thres.Cols());
ArrayResize(thres,mat_thres.Cols());

for(uint i=0; i<thres.Size(); i++)


{
precision[i]=mat_precision[0][i];
recall[i]=mat_recall[0][i];
thres[i]=mat_thres[0][i];
}
thres[0]=thres[1]+0.001;

PlotCurve("Precision-Recall curve (micro average)","p-r","",recall,precision);


Plot2Curves("Precision-Recall (micro average)","precision","recall",thres,precision,recall);
}

© 2000-2025, MetaQuotes Ltd.


1492 Matrix and Vector Methods

Resulting curves:

© 2000-2025, MetaQuotes Ltd.


1493 Matrix and Vector Methods

© 2000-2025, MetaQuotes Ltd.


1494 Matrix and Vector Methods

ReceiverOperatingCharacteristic
Compute values to construct the Receiver Operating Characteristic (ROC) curve. S imilarly to
ClassificationS core, this method is applied to the vector of true values.
bool vector::ReceiverOperatingCharacteristic(
const matrix& pred_scores, // matrix containing the probability distribution f
const ENUM_ENUM_AVERAGE_MODE mode // averaging mode
matrix& fpr, // calculated false positive rate values for each t
matrix& tpr, // calculated true positive rate values for each th
matrix& thresholds, // threshold values sorted in descending order
);

Parameters
pred_scores
[in] Amatrix containing a set of horizontal vectors with probabilities for each class. The number
of matrix rows must correspond to the size of the vector of true values.
mode
[in] Averaging mode from the ENUM _AVERAGE_MODE enumeration. Only AVERAGE_NONE,
AVERAGE_BINARY and AVERAGE_MICR O are used.

fpr
[out] A matrix with calculated values of the false positive rate curve. If no averaging is applied
(AVERAGE_NONE), the number of rows in the matrix corresponds to the number of model classes.
The number of columns corresponds to the size of the vector of true values (or the number of rows
in the probability distribution matrix pred_score). In the case of microaveraging, the number of
rows in the matrix corresponds to the total number of threshold values, excluding duplicates.
tpr
[out] A matrix with calculated values of the true positive rate curve.
threshold
[out] Threshold matrix obtained by sorting the probability matrix

Note

S ee notes for the ClassificationS core method.

Example

An example of plotting ROC graphs, where tpr values are plotted on the y-axis and fpr values are
plotted on the x-axis. Also fpr and tpr graphs are plotted separately, with threshold values plotted on
the x-axis
matrixf mat_thres;
matrixf mat_fpr;
matrixf mat_tpr;

© 2000-2025, MetaQuotes Ltd.


1495 Matrix and Vector Methods

if(y_true.ReceiverOperatingCharacteristic(y_scores,AVERAGE_MICRO,mat_fpr,mat_tpr,mat_thres))
{
double fpr[],tpr[],thres[];
ArrayResize(fpr,mat_thres.Cols());
ArrayResize(tpr,mat_thres.Cols());
ArrayResize(thres,mat_thres.Cols());

for(uint i=0; i<fpr.Size(); i++)


{
fpr[i]=mat_fpr[0][i];
tpr[i]=mat_tpr[0][i];
thres[i]=mat_thres[0][i];
}
thres[0]=thres[1]+0.001;

PlotCurve("ROC curve (micro average)","roc","0.5",fpr,tpr);


Plot2Curves("fpr-tpr (micro average)","fpr","tpr",thres,fpr,tpr);
}

Resulting curves:

© 2000-2025, MetaQuotes Ltd.


1496 Matrix and Vector Methods

© 2000-2025, MetaQuotes Ltd.


1497 Matrix and Vector Methods

The graph output code is simple and based on the <Graphics /Graphic.mqh> standard library.
The examples use the data of the mnist.onnx model. The code is presented in the PrecisionRecall
method description.
R OC AUC is close to ideal.

roc auc score micro = [0.99991]

© 2000-2025, MetaQuotes Ltd.


1498 Matrix and Vector Methods

OpenBLAS Methods
OpenBLAS is a high-performance open-source linear algebra library that implements BLAS (Basic Linear
Algebra S ubprograms) and some L APACK functions. OpenBL AS is designed to improve computational
performance, particularly in matrix and vector operations, which are often used in scientific and
engineering tas ks such as machine learning, numerical methods, and simulations.
Key features of OpenBLAS:
· Multithreading support: OpenBLAS can efficiently use multiple processor cores for parallel
computations, significantly accelerating operations on multiprocessor systems.
· Optimization for processor architectures : OpenBLAS includes optimized builds for various processors
such as Intel, AM D, ARM and others. The library automatically detects processor characteristics and
selects the most suitable function implementations.
· Extensive BL AS operation support: OpenBL AS implements core BL AS functions, including vector
operations (e.g., vector addition and dot product), matrix operations (multiplication), and vector-
matrix operations.
· LAPACK compatibility: The library supports LAPACK (Linear Algebra PACKage) functions for more
complex linear algebra operations, such as solving systems of linear equations, calculating matrix
eigenvalues, and others.
· H igh performance: Compared to other BL AS libraries, OpenBL AS often shows better results due to
hand-optimization for specific processor architectures.

Applications

OpenBLAS is widely used in applications involving numerical computations :


· Training neural networks and other machine learning tas ks.
· S cientific computing (e.g. modeling of physical processes).
· Processing and analyzing large amounts of data.
The library is integrated into many popular scientific software packages such as NumPy, S ciPy, and
TensorFlow, which rely on high-performance linear algebra operations.
OpenBLAS is an excellent choice for those seeking an open-source solution for high-performance
computing, particularly when working with large matrices and vectors.

Function Action

S ingularValueDecompositionDC S ingular Value Decomposition, " divide-and-


conquer" algorithm. This algorithm is
considered the fastest among other SVD
algorithms (lapack function GESDD).
S ingularValueDecompositionQR S ingular Value Decomposition, QR
algorithm. This algorithm is considered a
classical SVD algorithm (lapack function
GESVD).

© 2000-2025, MetaQuotes Ltd.


1499 Matrix and Vector Methods

Function Action

S ingularValueDecompositionQR Pivot S ingular Value Decomposition, QR with


pivoting algorithm (lapack function
GESVDQ).

S ingularValueDecompositionBisect S ingular Value Decomposition, bisection


algorithm (lapack function GESVDX).
S ingularValueDecompositionJacobiH igh S ingular Value Decomposition, Jacobi high
level algorithm (lapack function GEJSV).
S ingularValueDecompositionJacobiLow S ingular Value Decomposition, Jacobi low
level algorithm (lapack function GESVJ).
The method computes small singular
values and their singular vectors with
much greater accuracy than other SVD
routines in certain cases.
S ingularValueDecompositionBidiag DC S ingular Value Decomposition, divide-and-
conquer algorithm for bidiagonal matrices
(lapack function BDSVDX).
S ingularValueDecompositionBidiag Bisect S ingular Value Decomposition, bisection
algorithm for bidiagonal matrices (lapack
function BDSVDX).
EigenS olver Compute eigenvalues and eigenvectors of
a regular s quare matrix using the classical
algorithm (lapack function GEEV).
EigenS olver2 Compute generalized eigenvalues and
eigenvectors for a pair of ordinary s quare
matrices (lapack function GGEV).
EigenS olverX Compute eigenvalues and eigenvectors of
a regular s quare matrix in Expert mode,
i.e. with the ability to influence the
computation algorithm and the ability to
obtain accompanying computation data
(lapack function GEEVX).
EigenS olverS hur Compute eigenvalues, upper triangular
matrix in S chur form, and matrix of S chur
vectors (lapack function GEES ). S ee also
S chur decomposition.

EigenS ymmetricDC Compute eigenvalues and eigenvectors of


a symmetric or Hermitian (complex
conjugate) matrix using the divide-and-
conquer algorithm (lapack functions
SYEVD, HEEVD).

EigenS ymmetricQR Compute eigenvalues and eigenvectors of


a symmetric or Hermitian (complex

© 2000-2025, MetaQuotes Ltd.


1500 Matrix and Vector Methods

Function Action

conjugate) matrix using the QR algorithm


(lapack functions SYEV, HEEV).
EigenS ymmetricR obust Compute eigenvalues and eigenvectors of
a symmetric or Hermitian (complex
conjugate) matrix using the Multiple
R elatively R obust R epresentations, M RRR
algorithm (lapack functions SYEVR,
HEEVR ).

EigenS ymmetricBisect Compute eigenvalues and eigenvectors of


a symmetric or Hermitian (complex
conjugate) matrix using the bisection
algorithm (lapack functions SYEVX,
HEEVX).

S ingularS pectrumAnalysis S pectrum A method function for calculating the


relative contributions of spectral
components based on their eigenvalues.
S ingularS pectrumAnalysis Forecast A method function for calculating
reconstructed and predicted data using
spectral components of the input time
series.
S ingularS pectrumAnalysis R econstructComponents A method function for calculating
reconstructed components of the input
time series and their contributions.
S ingularS pectrumAnalysis R econstructS eries A method function for calculating the
reconstructed time series using the first
component_count components.

© 2000-2025, MetaQuotes Ltd.


1501 Matrix and Vector Methods

Singular value decomposition


This section features functions for decomposing a matrix into three components : orthogonal matrices
and a diagonal matrix of singular values. SVD is applied to solve various linear algebra problems such
as data dimensionality reduction, image compression, solving systems of equations, and data analysis
and optimization. The main functions allow you to compute singular values and vectors, reconstruct
matrices, and approximate matrices with reduced rank accuracy.

Function Action

S ingularValueDecompositionDC S ingular Value Decomposition, " divide-and-conquer"


algorithm. This algorithm is considered the fastest
among other SVD algorithms (lapack function
GESDD).

S ingularValueDecompositionQR S ingular Value Decomposition,QR algorithm. This


algorithm is considered a classical SVD algorithm
(lapack function GESVD).
S ingularValueDecompositionQR Pivot S ingular Value Decomposition, QR with pivoting
algorithm (lapack function GESVDQ).
S ingularValueDecompositionBisect S ingular Value Decomposition, bisection algorithm
(lapack function GESVDX).
S ingularValueDecompositionJacobiH igh S ingular Value Decomposition, Jacobi high level
algorithm (lapack function GEJSV).
S ingularValueDecompositionJacobiLow S ingular Value Decomposition, Jacobi low level
algorithm (lapack function GESVJ). The method
computes small singular values and their singular
vectors with much greater accuracy than other SVD
routines in certain cases.
S ingularValueDecompositionBidiag DC S ingular Value Decomposition, divide-and-conquer
algorithm for bidiagonal matrices (lapack function
BDSVDX).

S ingularValueDecompositionBidiag Bisect S ingular Value Decomposition, bisection algorithm


for bidiagonal matrices (lapack function BDSVDX).

© 2000-2025, MetaQuotes Ltd.


1502 Matrix and Vector Methods

SingularValueDecompositionDC
S ingular Value Decomposition, " divide-and-conquer" algorithm. This algorithm is considered the
fastest among other SVD algorithms (lapack function GESDD).
Computing for type matrix<double>
bool matrix::SingularValueDecompositionDC(
ENUM_SVD_Z jobz, // how to computed
vector S, // vector of computed singular values
matrix U, // matrix of computed left vectors U
matrix VT // transposed matrix of right vectors VT
);

Computing for type matrix<float>


bool matrix::SingularValueDecompositionDC(
ENUM_SVD_Z jobz, // how to computed
vectorf S, // vector of computed singular values
matrixf U, // matrix of computed left vectors U
matrixf VT // transposed matrix of right vectors VT
);

Computing for type matrix<complex>


bool matrix::SingularValueDecompositionDC(
ENUM_SVD_Z jobz, // how to computed
vector S, // vector of computed singular values
matrixc U, // matrix of computed left vectors U
matrixc VT // transposed matrix of right vectors VT
);

Parameters
jobz
[in] ENUM _SVD_Z enumeration value which determines the method for computing left and singular
eigenvectors.
S
[out] Vector of singular values.
U
[out] Matrix of left singular vectors.
VT
[out] Matrix of right singular vectors.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

© 2000-2025, MetaQuotes Ltd.


1503 Matrix and Vector Methods

Computation depends on the value of the jobz parameter.


W henjobv is set to SVDZ_N, the left and right vectors are not computed. Only singular values are
computed.
W hen jobv is set to SVDZ_A, the full matrices of the U and VT vectors are computed.
W hen the value is SVDZ_S , truncated matrices of vectors U and VT are computed.

ENUM_SVD_Z

An enumeration defining the way to compute left and right singular vectors.

ID Description

SVDZ_N Columns U or rows VT are not computed


SVDZ_A All M columns of U or all N columns of VT are returned in arrays
U and VT

SVDZ_S The first min(M,N) columns of U or the first min(M,N) columns


of VT are returned in arrays U and VT

See also

S ingularValueDecompositionQR , S ingularValueDecompositionQR Pivot

© 2000-2025, MetaQuotes Ltd.


1504 Matrix and Vector Methods

SingularValueDecompositionQR
S ingular Value Decomposition, QR algorithm. Considered a classical SVD algorithm (lapack function
GESVD).

Computing for type matrix<double>


bool matrix::SingularValueDecompositionQR(
ENUM_SVD_Z jobu, // how to compute left vectors
ENUM_SVD_Z jobv, // how to compute right vectors
vector S, // vector of computed singular values
matrix U, // matrix of computed left vectors U
matrix VT // transposed matrix of right vectors VT
);

Computing for type matrix<float>


bool matrix::SingularValueDecompositionQR(
ENUM_SVD_Z jobu, // how to compute left vectors
ENUM_SVD_Z jobv, // how to compute right vectors
vectorf S, // vector of computed singular values
matrixf U, // matrix of computed left vectors U
matrixf VT // transposed matrix of right vectors VT
);

Computing for type matrix<complex>


bool matrix::SingularValueDecompositionQR(
ENUM_SVD_Z jobu, // how to compute left vectors
ENUM_SVD_Z jobv, // how to compute right vectors
vector S, // vector of computed singular values
matrixc U, // matrix of computed left vectors U
matrixc VT // transposed matrix of right vectors VT
);

Parameters
jobu
[in] ENUM _SVD_Z enumeration value defining how the left singular vectors should be computed.
jobv
[in] ENUM _SVD_Z enumeration value defining how the right singular vectors should be computed.
S
[out] Vector of singular values.
U
[out] Matrix of left singular vectors.
VT
[out] Matrix of right singular vectors.

© 2000-2025, MetaQuotes Ltd.


1505 Matrix and Vector Methods

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

Computation depends on the value of the jobu and jobv parameters.


W hen set to SVDZ_N, the left (jobu) and right (jobv) vectors are not computed. S ingular values are
always computed.
W hen set to SVDZ_A, the full matrices of vectors U (jobu) or VT (jobv) are computed.
W ith the value SVDZ_S , truncated matrices of vectors U (jobu) or VT (jobv) are computed.

ENUM_SVD_Z

An enumeration defining the way to compute left and right singular vectors.

ID Description

SVDZ_N Columns U or rows VT are not computed


SVDZ_A All M columns of U or all N columns of VT are returned in arrays
U and VT

SVDZ_S The first min(M,N) columns of U or the first min(M,N) columns


of VT are returned in arrays U and VT

See also

S ingularValueDecompositionDC, S ingularValueDecompositionQR Pivot

© 2000-2025, MetaQuotes Ltd.


1506 Matrix and Vector Methods

SingularValueDecompositionQRPivot
S ingular Value Decomposition, QR with pivoting algorithm (lapack function GESVDQ).
Computing for type matrix<double>
bool matrix::SingularValueDecompositionQRPivot(
ENUM_SVDQRP_A joba, // computation accuracy level
ENUM_SVDQRP_P jobp, // use row reversal to compute
ENUM_SVDQRP_R jobr, // use triangular matrix R to compute
ENUM_SVDQRP_U jobu, // how to compute left vectors
ENUM_SVDQRP_V jobv, // how to compute right vectors
vector S, // vector of computed singular values
matrix U, // matrix of computed left vectors U
matrix VT // transposed matrix of right vectors VT
);

Computing for type matrix<float>


bool matrix::SingularValueDecompositionQRPivot(
ENUM_SVDQRP_A joba, // computation accuracy level
ENUM_SVDQRP_P jobp, // use row reversal to compute
ENUM_SVDQRP_R jobr, // use triangular matrix R to compute
ENUM_SVDQRP_U jobu, // how to compute left vectors
ENUM_SVDQRP_V jobv, // how to compute right vectors
vectorf S, // vector of computed singular values
matrixf U, // matrix of computed left vectors U
matrixf VT // transposed matrix of right vectors VT
);

Computing for type matrix<complex>


bool matrix::SingularValueDecompositionQRPivot(
ENUM_SVDQRP_A joba, // computation accuracy level
ENUM_SVDQRP_P jobp, // use row reversal to compute
ENUM_SVDQRP_R jobr, // use triangular matrix R to compute
ENUM_SVDQRP_U jobu, // how to compute left vectors
ENUM_SVDQRP_V jobv, // how to compute right vectors
vector S, // vector of computed singular values
matrixc U, // matrix of computed left vectors U
matrixc VT // transposed matrix of right vectors VT
);

Parameters
joba
[in] ENUM _SVDQR P_A enumeration value defining the accuracy level of the SVD computation.
jobp

© 2000-2025, MetaQuotes Ltd.


1507 Matrix and Vector Methods

[in] ENUM _SVDQR P_P enumeration value defining the use of row reversal during the computation
process.
jobr
[in] ENUM _SVDQR P_R enumeration value defining whether to transpose the triangular matrix R
obtained as a result of the initial QR factorization.
jobu
[in] ENUM _SVDQR P_U enumeration value that determines how the left singular vectors should be
computed.
jobv
[in] ENUM _SVDQR P_V enumeration value defining how the right singular vectors should be
computed.
S
[out] Vector of singular values.
U
[out] Matrix of left singular vectors.
VT
[out] Matrix of right singular vectors.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

The number of matrix rows must not be less than the number of columns.
If both left and right singular vectors are computed, jobv must be set to SVDQR PV_R when
jobu=SVDQRPU_R.

ENUM_SVDQRP_A

An enumeration that specifies the level of accuracy of the SVD computation.

ID Description

SVDQR P_A The requested accuracy corresponds to the inverse error


limited by epsilon. This is an aggressive level of truncation.
SVDQR PA_M S imilar
to SVDQRP_A, but the truncation is softer. This is the
average level of truncation.
SVDQR PA_H H igh accuracy is required.

ENUM_SVDQRP_P

An enumeration that specifies whether to use row reversal during calculation.

© 2000-2025, MetaQuotes Ltd.


1508 Matrix and Vector Methods

ID Description

SVDQR PP_P The rows of A are ordered in descending order. Recommended


for numerical reliability.
SVDQR PP_N No row reversal.

ENUM_SVDQRP_R

An enumeration that specifies whether to transpose the triangular matrix R obtained as a result of the
initial QR factorization.

ID Description

SVDQR PR_T After the initial rotated QR factorization, GESVD is applied to


the transpose R**T of the calculated triangular factor R.
SVDQR PR_N The triangular factor R is given as input to GESVD.

ENUM_SVDQRP_U

An enumeration defining how left singular vectors should be computed.

ID Description

SVDQR PU_A All M left singular vectors are computed.


SVDQR PU_S The min(M,N) left singular vectors are computed.
SVDQR PU_R The numerical rank NUM RANK is determined and only the
NUM RANK of the left singular vectors is computed.

SVDQR PU_F N left singular vectors are returned.


SVDQR PU_N Left singular vectors are not computed.

ENUM_SVDQRP_V

An enumeration defining how right singular vectors should be computed.

ID Description

SVDQR PV_A All N right singular vectors are computed.


SVDQR PV_R The numerical rank NUM RANK is defined and only the NUM RANK
of right singular vectors are computed.
SVDQR PV_N R ight singular vectors are not computed.

See also

S ingularValueDecompositionDC, S ingularValueDecompositionQR

© 2000-2025, MetaQuotes Ltd.


1509 Matrix and Vector Methods

SingularValueDecompositionBisect
S ingular Value Decomposition, bisection algorithm (lapack function GESVDX).
Computing for type matrix<double>
bool matrix::SingularValueDecompositionBisect(
ENUM_SVD_VECTORS jobv, // computation accuracy level
ENUM_BLAS_RANGE range, // subset of computable singular values
double lower, // lower limit of the subset
double upper, // upper limit of the subset
vector S, // vector of computed singular values
matrix U, // matrix of computed left vectors U
matrix VT // transposed matrix of right vectors VT
);

Computing for type matrix<float>


bool matrix::SingularValueDecompositionBisect(
ENUM_SVD_VECTORS jobv, // computation accuracy level
ENUM_BLAS_RANGE range, // subset of computable singular values
double lower, // lower limit of the subset
double upper, // upper limit of the subset
vectorf S, // vector of computed singular values
matrixf U, // matrix of computed left vectors U
matrixf VT // ransposed matrix of right vectors VT
);

Computing for type matrix<complex>


bool matrix::SingularValueDecompositionBisect(
ENUM_SVD_VECTORS jobv, // computation accuracy level
ENUM_BLAS_RANGE range, // subset of computable singular values
double lower, // lower limit of the subset
double upper, // upper limit of the subset
vector S, // vector of computed singular values
matrixc U, // matrix of computed left vectors U
matrixc VT // transposed matrix of right vectors VT
);

Parameters
jobv
[in] ENUM _SVD_VECTORS enumeration value which determines the method for computing left and
singular eigenvectors.
range
[in] ENUM _BL AS_RANGE enumeration value that defines a subset of computable singular values
and vectors.
lower

© 2000-2025, MetaQuotes Ltd.


1510 Matrix and Vector Methods

[in] The lower limit of singular values subset; specified depending on the value of the range
parameter.
upper
[in] The upper limit of singular values subset; specified depending on the value of the range
parameter.
S
[out] Vector of singular values.
U
[out] Matrix of left singular vectors.
VT
[out] Matrix of right singular vectors.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

Computation depends on the values of the jobuv and range parameters.


W hen BL ASRANGE_A is set, all singular values are computed, and the lower and upper parameters
are ignored.
W iththe BLASRANGE_V value, only those singular values (and their vectors) that fall within the
range of real values specified by the 'lower' and 'upper' parameters are computed.
W ith the BL ASRANGE_I value, only those singular values (and their vectors) that fall within the range
of integer indices specified by the 'lower' and 'upper' parameters are computed. For example, with
lower=0 and upper=2, only the first three singular values are computed.

ENUM_SVD_VECTORS

An enumeration defining the way to compute left and right singular vectors.

ID Description

SVDVECTORS_N Only singular values are computed, without vectors.


SVDVECTORS_U Left singular vectors are computed.
SVDVECTORS_V R ight singular vectors are computed.
SVDVECTORS_UV Left and right singular vectors are computed.

ENUM_BLAS_RANGE

An enumeration defining a subset of computable singular values and vectors.

© 2000-2025, MetaQuotes Ltd.


1511 Matrix and Vector Methods

ID Description

BL ASRANGE_A All singular or eigenvalues will be found.


BL ASRANGE_V All singular or eigenvalues in the half-open interval (VL,VU] will
be found.
BL ASRANGE_I S ingular or eigenvalues from IL to IU will be found

See also

S ingularValueDecompositionDC, S ingularValueDecompositionQR , S ingularValueDecompositionQR Pivot

© 2000-2025, MetaQuotes Ltd.


1512 Matrix and Vector Methods

SingularValueDecompositionJacobiHigh
S ingular Value Decomposition, Jacobi high level algorithm (lapack function GEJSV).
Computing for type matrix<double>
bool matrix::SingularValueDecompositionJacobiHigh(
ENUM_SVDJH_A joba, // computation accuracy level
ENUM_SVDJH_U jobu, // how to compute left vectors
ENUM_SVDJH_V jobv, // how to compute right vectors
ENUM_SVDJH_R jobr, // define range of computable singular values
ENUM_SVDJH_T jobt, // define whether to transpose when computing a square matrix
ENUM_SVDJH_P jobp, // the possibility of structured perturbations to remove denorma
vector S, // vector of computed singular values
matrix U, // matrix of computed left vectors U
matrix V, // matrix of computed left vectors V
vector work_results // additional computation results
);

Computing for type matrix<float>


bool matrix::SingularValueDecompositionJacobiHigh(
ENUM_SVDJH_A joba, // computation accuracy level
ENUM_SVDJH_U jobu, // how to compute left vectors
ENUM_SVDJH_V jobv, // how to compute right vectors
ENUM_SVDJH_R jobr, // define range of computable singular values
ENUM_SVDJH_T jobt, // define whether to transpose when computing a square matrix
ENUM_SVDJH_P jobp, // the possibility of structured perturbations to remove denorma
vectorf S, // vector of computed singular values
matrixf U, // U matrix of computed left vectors
matrixf V, // V matrix of computed left vectors
vector work_results // additional computation results
);

Computing for type matrix<complex>


bool matrix::SingularValueDecompositionJacobiHigh(
ENUM_SVDJH_A joba, // computation accuracy level
ENUM_SVDJH_U jobu, // how to compute left vectors
ENUM_SVDJH_V jobv, // how to compute right vectors
ENUM_SVDJH_R jobr, // define range of computable singular values
ENUM_SVDJH_T jobt, // define whether to transpose when computing a square matrix
ENUM_SVDJH_P jobp, // the possibility of structured perturbations to remove denorma
vectorc S, // vector of computed singular values
matrixc U, // U matrix of computed left vectors
matrixc V, // V matrix of computed left vectors
vector work_results // additional computation results
);

© 2000-2025, MetaQuotes Ltd.


1513 Matrix and Vector Methods

Parameters
joba
[in] ENUM _SVDJH_A enumeration value determining the accuracy level of the SVD computation.
jobu
[in] ENUM _SVDJH_U enumeration value that determines how the left singular vectors should be
computed.
jobv
[in] ENUM _SVDJH_V enumeration value that determines how the right singular vectors should be
computed.
jobr
[in] ENUM _SVDJH_R enumeration value defining the range of computable values
jobt
[in] ENUM _SVDJH_T enumeration value defining whether to transpose the matrix of it is s quare.
If the matrix is non-s quare, this parameter is ignored.
jobp
[in] ENUM _SVDJH_P enumeration value defining the possibility of structured perturbations to
remove denormalized values.
S
[out] Vector of singular values.
For work (1)/work (2) = one: the singular values of A. During the computation S contains
Euclidean column norms of the iterated matrices in the array a.
For work(1)≠work(2): the singular values of A are (work(1)/work(2)) * S (1:n). This factored form
is used if sigma_max(A) overflows or if small singular values have been saved from underflow by
scaling the input matrix A.
jobr = 'R', some of the singular values may be returned as exact zeros obtained by 'setting to
zero' because they are below the numerical rank threshold or are denormalized numbers.

U
[out] Matrix of left singular vectors.
V
[out] Matrix of right singular vectors.
work_results
[out] Vector consisting of 7 statistics obtained as a result of the computation.
work(1) = scale = work(2)/work(1) is the scaling factor such that scale*sva(1:n) are the
computed singular values of A. S ee the description of S .
work(2) = see the description of work(1).
work(3) = sconda is an estimate for the condition number of column equilibrated A. If joba = 'E'
or 'G', sconda is an estimate of s qrt(||(R**t * R)**(-1)||_1). It is computed using ?pocon. It holds
n**(-1/4) * sconda ≤ ||R**(-1)||_2 ≤ n**(1/4) * sconda, where R is the triangular factor from the

© 2000-2025, MetaQuotes Ltd.


1514 Matrix and Vector Methods

QRF of A. However, if R is truncated and the numerical rank is determined to be strictly smaller
than n, sconda is returned as -1, indicating that the smallest singular values might be lost.
If full SVD is needed, the following two condition numbers are useful for the analysis of the
algorithm. They are provied for a user who is familiar with the details of the method.
work(4) = an estimate of the scaled condition number of the triangular factor in the first QR
factorization.
work(5) = an estimate of the scaled condition number of the triangular factor in the second QR
factorization.
The following two parameters are computed if jobt = 'T '. They are provided for a user who is
familiar with the details of the method.
work(6) = the entropy of A**t*A :: this is the S hannon entropy of diag(A**t*A) / Trace(A**t*A)
taken as point in the probability simplex.
work(7) = the entropy of A*A**t.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

The number of matrix rows must not be less than the number of columns.

ENUM_SVDJH_A

An enumeration that specifies the level of accuracy of the SVD computation.

ID Description

SVDJHA_C Computation as with 'C' with an additional estimate of the


condition number. It provides a realistic error bound.
SVDJHA_E Computation as with SVDJHA_C' with an additional estimate of
the condition number. It provides a realistic error bound.
SVDJHA_F H igher accuracy than the SVDJHA_C option.
SVDJHA_G Computation as with SVDJHA_F with an additional estimate of
the condition number.
SVDJHA_A S mall singular
values are the noise and the matrix is treated as
numerically rank deficient.
SVDJHA_R S imilar as in SVDJHA_A, but more accuracy.

ENUM_SVDJH_U

An enumeration defining how left singular vectors should be computed.

© 2000-2025, MetaQuotes Ltd.


1515 Matrix and Vector Methods

ID Description

SVDJHU_U N columns of U are returned in the array U.


SVDJHU_F Full set of M left singular vectors is returned in the array U.
SVDJHU_N U is not computed.

ENUM_SVDJH_V

An enumeration defining how right singular vectors should be computed.

ID Description

SVDJHV_V N columns of V are returned in the array V


SVDJHV_J N columns of V are returned in the array V, but they are
computed as the product of Jacobi rotations
SVDJHV_N V is not computed

ENUM_SVDJH_R

An enumeration that defines the range of values to be computed.

ID Description

SVDJHR_N Do not kill small columns of c*A.


SVDJHR_R RES T R ICT ED range for sigma(c*A). This option is
recommended.

ENUM_SVDJH_T

An enumeration that specifies whether a matrix should be transposed if it is s quare.

ID Description

SVDJH T _T Transpose if entropy test indicates possibly faster convergence


of Jacobi process.
SVDJH T _N Do not use transposition. Do not speculate.

ENUM_SVDJH_P

An enumeration that specifies the possibility of structured perturbations to remove denormalized


values.

ID Description

SVDJH P_P Introduce perturbation.


SVDJH P_N Do not perturb.

© 2000-2025, MetaQuotes Ltd.


1516 Matrix and Vector Methods

See also

S ingularValueDecompositionDC, S ingularValueDecompositionQR

© 2000-2025, MetaQuotes Ltd.


1517 Matrix and Vector Methods

SingularValueDecompositionJacobiLow
S ingular Value Decomposition, Jacobi low level algorithm (lapack function GESVJ). The method
computes small singular values and their singular vectors with much greater accuracy than other SVD
routines in certain cases.
Computing for type matrix<double>
bool matrix::SingularValueDecompositionJacobiLow(
ENUM_SVDJH_U jobu, // how to compute left vectors
ENUM_SVDJH_V jobv, // how to compute right vectors
double ctol, // threshold for convergence if jobu='C'
ulong mv, // number of first rows of matrix V if jobv='A'
vector S, // vector of computed singular values
matrix U, // matrix of computed left vectors U
matrix V, // matrix of computed left vectors V
vector work_results // additional computation results
);

Computing for type matrix<float>


bool matrix::SingularValueDecompositionJacobiLow(
ENUM_SVDJH_U jobu, // how to compute left vectors
ENUM_SVDJH_V jobv, // how to compute right vectors
double ctol, // threshold for convergence if jobu='C'
ulong mv, // number of first rows of matrix V if jobv='A'
vectorf S, // vector of computed singular values
matrixf U, // U matrix of computed left vectors
matrixf V, // V matrix of computed left vectors
vector work_results // additional computation results
);

Computing for type matrix<complex>


bool matrix::SingularValueDecompositionJacobiLow(
ENUM_SVDJH_U jobu, // how to compute left vectors
ENUM_SVDJH_V jobv, // how to compute right vectors
double ctol, // threshold for convergence if jobu='C'
ulong mv, // number of first rows of matrix V if jobv='A'
vector S, // vector of computed singular values
matrixc U, // U matrix of computed left vectors
matrixc V, // V matrix of computed left vectors
vector work_results // additional computation results
);

Parameters
jobu
[in] ENUM _SVDJL _U enumeration value that determines how the left singular vectors should be
computed.

© 2000-2025, MetaQuotes Ltd.


1518 Matrix and Vector Methods

jobv
[in] ENUM _SVDJL _V enumeration value defining how the right singular vectors should be
computed.
ctol
[in] Convergence threshold if jobu=SVDJLU_C. For other values of 'jobu' the parameter is ignored.
mv
[in] Number of rows of matrix V to be computed if jobv =SVDJLV_A. For other values of 'jobv ' the
parameter is ignored.
S
[out] Vector of singular values.
Depending on the value scale = work(1), where scale is the scaling factor:
if scale = 1, S (1:n) contains the computed singular values of a. During the computation, sva
contains the Euclidean column norms of the iterated matrices in the array a.
if scale ≠ 1, the singular values of a are scale*S (1:n), and this factored representation is due
to the fact that some of the singular values of a might underflow or overflow.
U
[out] Matrix of left singular vectors.
V
[out] Matrix of right singular vectors (non-transposed).
work_results
[out] Vector consisting of 7 statistics obtained as a result of the computation.
work(1) = scale is the scaling factor such that scale*S (1:n) are the computed singular values of
A. S ee the description of S ).

work(2) is the number of the computed nonzero singular value.


work(3) is the number of the computed singular values that are larger than the underflow
threshold.
work(4) is the number of sweeps of Jacobi rotations needed for numerical convergence.
work(5) = max_{i.NE.j} |COS (A(:,i),A(:,j))| in the last sweep. This is useful information in
cases when ?gesvj did not converge, as it can be used to estimate whether the output is still
useful and for post festum analysis.
work(6) is the largest absolute value over all sines of the Jacobi rotation angles in the last
sweep. It can be useful in a post festum analysis.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

The number of matrix rows must not be less than the number of columns.

© 2000-2025, MetaQuotes Ltd.


1519 Matrix and Vector Methods

ENUM_SVDJL_U

An enumeration defining how left singular vectors should be computed.

ID Description

SVDJL U_U The left singular vectors corresponding to the nonzero singular
values are computed and returned in the leading columns of A
SVDJL U_C Analogousto SVDJLU_U, except that user can control the level
of numerical orthogonality of the computed left singular
vectors.
SVDJL U_N The matrix U is not computed.

ENUM_SVDJL_V

An enumeration defining how right singular vectors should be computed.

ID Description

SVDJL V_V The matrix V is computed


SVDJL V_A The Jacobi rotations are applied to the M V-by-N matrix V.
SVDJL V_N The matrix V is not computed.

See also

S ingularValueDecompositionDC, S ingularValueDecompositionQR

© 2000-2025, MetaQuotes Ltd.


1520 Matrix and Vector Methods

SingularValueDecompositionBidiagDC
S ingular Value Decomposition, divide-and-conquer algorithm for bidiagonal matrices (lapack function
BDSVDX).

Computing for type matrix<double>


bool matrix::SingularValueDecompositionBidiagDC(
ENUM_SVDBIDIAG_Z jobz, // how to compute left vectors
ENUM_BLAS_RANGE range, // subset of computed singular values
double lower, // lower limit of the subset
double upper, // upper limit of the subset
vector S, // vector of computed singular values
matrix U, // U matrix of computed left vectors
matrix VT // VT transposed matrix of right vectors
);

Computing for type matrix<float>


bool matrix::SingularValueDecompositionBidiagDC(
ENUM_SVDBIDIAG_Z jobz, // how to compute left vectors
ENUM_BLAS_RANGE range, // subset of computed singular values
double lower, // lower limit of the subset
double upper, // upper limit of the subset
vectorf S, // vector of computed singular values
matrixf U, // U matrix of computed left vectors
matrixf VT // VT transposed matrix of right vectors
);

Parameters
jobz
[in] ENUM _SVDBIDIAG_Z enumeration value that determines how the left singular vectors should
be computed.
range
[in] ENUM _BL AS_RANGE enumeration value that defines a subset of computable singular values
and vectors.
lower
[in] The lower limit of singular values subset; specified depending on the value of the range
parameter.
upper
[in] The upper limit of singular values subset; specified depending on the value of the range
parameter.
S
[out] Vector of singular values.
U
[out] Matrix of left singular vectors.

© 2000-2025, MetaQuotes Ltd.


1521 Matrix and Vector Methods

V
[out] Transposed matrix of right singular vectors.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

Computation depends on the values of the jobz and range parameters.


W hen BL ASRANGE_A is set, all singular values are computed, and the lower and upper parameters
are ignored.
W iththe BLASRANGE_V value, only those singular values (and their vectors) that fall within the
range of real values specified by the 'lower' and 'upper' parameters are computed.
W ith the BL ASRANGE_I value, only those singular values (and their vectors) that fall within the range
of integer indices specified by the 'lower' and 'upper' parameters are computed. For example, with
lower=0 and upper=2, only the first three singular values are computed.
A bidiagonal matrix is a s quare matrix with non-zero main diagonal and one of the sub-diagonals.

Upper bidiagonal matrix

[[x, x, 0, 0, 0],
[0, x, x, 0, 0],
[0, 0, x, x, 0],
[0, 0, 0, x, x],
[0, 0, 0, 0, x]]

Lower bidiagonal matrix

[[x, 0, 0, 0, 0],
[x, x, 0, 0, 0],
[0, x, x, 0, 0],
[0, 0, x, x, 0],
[0, 0, 0, x, x]]

ENUM_SVDBIDIAG_Z

An enumeration defining how left singular vectors should be computed.

ID Description

SVDJOBZ_V Compute singular values and singular vectors.


SVDJOBZ_N Compute singular values only.

ENUM_BLAS_RANGE

© 2000-2025, MetaQuotes Ltd.


1522 Matrix and Vector Methods

An enumeration defining how right singular vectors should be computed.

ID Description

BL ASRANGE_A All singular or eigenvalues will be found.


BL ASRANGE_V All singular or eigenvalues in the half-open interval (VL,VU] will
be found.
BL ASRANGE_I The IL-th through IU-th singular or eigenvalues will be found.

See also

S ingularValueDecompositionDC, S ingularValueDecompositionQR

© 2000-2025, MetaQuotes Ltd.


1523 Matrix and Vector Methods

SingularValueDecompositionBidiagBisect
S ingular Value Decomposition, bisection algorithm for bidiagonal matrices (lapack function BDSVDX).
Computing for type matrix<double>
bool matrix::SingularValueDecompositionBidiagBisect(
ENUM_SVDBIDIAG_Z jobz, // how to compute left vectors
ENUM_BLAS_RANGE range, // subset of computed singular values
double lower, // lower limit of the subset
double upper, // upper limit of the subset
vector S, // vector of computed singular values
matrix U, // U matrix of computed left vectors
matrix VT // VT transposed matrix of right vectors
);

Computing for type matrix<float>


bool matrix::SingularValueDecompositionBidiagBisect(
ENUM_SVDBIDIAG_Z jobz, // how to compute left vectors
ENUM_BLAS_RANGE range, // subset of computed singular values
double lower, // lower limit of the subset
double upper, // upper limit of the subset
vectorf S, // vector of computed singular values
matrixf U, // U matrix of computed left vectors
matrixf VT // VT transposed matrix of right vectors
);

Parameters
jobz
[in] ENUM _SVDBIDIAG_Z enumeration value that determines how the left singular vectors should
be computed.
range
[in] ENUM _BL AS_RANGE enumeration value that defines a subset of computable singular values
and vectors.
lower
[in] The lower limit of singular values subset; specified depending on the value of the range
parameter.
upper
[in] The upper limit of singular values subset; specified depending on the value of the range
parameter.
S
[out] Vector of singular values.
U
[out] Matrix of left singular vectors.

© 2000-2025, MetaQuotes Ltd.


1524 Matrix and Vector Methods

V
[out] Transposed matrix of right singular vectors.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

W hen BL ASRANGE_A is set, all singular values are computed, and the lower and upper parameters
are ignored.
W iththe BLASRANGE_V value, only those singular values (and their vectors) that fall within the
range of real values specified by the 'lower' and 'upper' parameters are computed.
W ith the BL ASRANGE_I value, only those singular values (and their vectors) that fall within the range
of integer indices specified by the 'lower' and 'upper' parameters are computed. For example, with
lower=0 and upper=2, only the first three singular values are computed.
A bidiagonal matrix is a s quare matrix with non-zero main diagonal and one of the sub-diagonals.

Upper bidiagonal matrix

[[x, x, 0, 0, 0],
[0, x, x, 0, 0],
[0, 0, x, x, 0],
[0, 0, 0, x, x],
[0, 0, 0, 0, x]]

Lower bidiagonal matrix

[[x, 0, 0, 0, 0],
[x, x, 0, 0, 0],
[0, x, x, 0, 0],
[0, 0, x, x, 0],
[0, 0, 0, x, x]]

ENUM_SVDBIDIAG_Z

An enumeration defining how left singular vectors should be computed.

ID Description

SVDJOBZ_V Compute singular values and singular vectors.


SVDJOBZ_N Compute singular values only.

ENUM_BLAS_RANGE

An enumeration defining how right singular vectors should be computed.

© 2000-2025, MetaQuotes Ltd.


1525 Matrix and Vector Methods

ID Description

BL ASRANGE_A All singular or eigenvalues will be found.


BL ASRANGE_V All singular or eigenvalues in the half-open interval (VL,VU] will
be found.
BL ASRANGE_I The IL-th through IU-th singular or eigenvalues will be found.

See also

S ingularValueDecompositionDC, S ingularValueDecompositionQR

© 2000-2025, MetaQuotes Ltd.


1526 Matrix and Vector Methods

Eigen Values
The section features functions for computing eigenvalues and eigenvectors. It describes methods for
solving standard linear algebra problems using the LAPACK library algorithms. These functions are
efficient for matrix analysis, diagonalization, system stabilization, and other tas ks.
· EigenSolver : The function is designed to compute the eigenvalues and eigenvectors of an arbitrary
s quare matrix using the classical algorithm represented by the GEEV lapack function. This method is
applied to a wide range of matrices, allowing the decomposition of matrices into their eigenvalues
and eigenvectors.
· EigenSymmetricDC: The function for computing eigenvalues and eigenvectors of symmetric or
H ermitian matrices using the divide-and-conquer algorithm. The lapack functions SYEVD and HEEVD
enable the efficient handling of symmetric or Hermitian matrices, providing faster and more
accurate processing of such matrices.

Function Action

EigenS olver Compute eigenvalues and eigenvectors of a regular


s quare matrix using the classical algorithm (lapack
function GEEV).
EigenS olverX Compute eigenvalues and eigenvectors of a regular
s quare matrix in Expert mode, i.e. with the ability to
influence the computation algorithm and the ability
to obtain accompanying computation data (lapack
function GEEVX).
EigenS olverS hur Compute eigenvalues, upper triangular matrix in
S chur form, and matrix of S chur vectors (lapack
function GEES ). S ee also S chur decomposition.
EigenS olver2 Compute generalized eigenvalues and eigenvectors
for a pair of ordinary s quare matrices (lapack
function GGEV).
EigenS olver2X Compute generalized eigenvalues and eigenvectors
for a pair of regular s quare matrices in Expert mode,
i.e. with the ability to influence the computation
algorithm and the ability to obtain accompanying
computation data (lapack function GGEVX). Both
matrices must be the same size.
EigenS olver2S hur Compute a pair of ordinary s quare matrices of
generalized eigenvalues, generalized eigenvectors,
generalized S chur forms, as well as left and right
S chur vectors (lapack function GGES ).

EigenS olver2Block ed Compute generalized eigenvalues and eigenvectors


for a pair of regular s quare matrices using a block
algorithm (lapack function GGEV3). Both matrices
must be the same size. The method parameters are
exactly the same as EigenS olver2.

© 2000-2025, MetaQuotes Ltd.


1527 Matrix and Vector Methods

Function Action

EigenS olver2S hurBlock ed Compute a pair of regular s quare matrices of


generalized eigenvalues, generalized eigenvectors,
generalized S chur forms, as well as left and right
S chur vectors (lapack function GGES3).

EigenS ymmetricDC Compute eigenvalues and eigenvectors of a


symmetric or Hermitian (complex conjugate) matrix
using the divide-and-conquer algorithm (lapack
functions SYEVD, HEEVD).
EigenS ymmetricQR Compute eigenvalues and eigenvectors of a
symmetric or Hermitian (complex conjugate) matrix
using the QR algorithm (lapack functions SYEV,
HEEV).

EigenS ymmetricR obust Compute eigenvalues and eigenvectors of a


symmetric or Hermitian (complex conjugate) matrix
using the Multiple Relatively Robust Representations,
M RRR algorithm (lapack functions SYEVR, HEEVR).
EigenS ymmetricBisect Compute eigenvalues and eigenvectors of a
symmetric or Hermitian (complex conjugate) matrix
using the bisection algorithm (lapack functions
SYEVX, HEEVX).

© 2000-2025, MetaQuotes Ltd.


1528 Matrix and Vector Methods

General Matrices
Functions for calculating eigenvalues and eigenvectors of a s quare matrix using classical algorithms. It
provides various methods for working with both real and complex matrices, allowing you to solve linear
algebra problems with a choice of methods for calculating eigenvectors.

Function Action

EigenS olver Compute eigenvalues and eigenvectors of a regular


s quare matrix using the classical algorithm (lapack
function GEEV).
EigenS olverX Compute eigenvalues and eigenvectors of a regular
s quare matrix in Expert mode, i.e. with the ability to
influence the computation algorithm and the ability
to obtain accompanying computation data (lapack
function GEEVX).
EigenS olverS hur Compute eigenvalues, upper triangular matrix in
S chur form, and matrix of S chur vectors (lapack
function GEES ). S ee also S chur decomposition.
EigenS olver2 Compute generalized eigenvalues and eigenvectors
for a pair of ordinary s quare matrices (lapack
function GGEV).
EigenS olver2X Compute generalized eigenvalues and eigenvectors
for a pair of regular s quare matrices in Expert mode,
i.e. with the ability to influence the computation
algorithm and the ability to obtain accompanying
computation data (lapack function GGEVX). Both
matrices must be the same size.
EigenS olver2S hur Compute a pair of ordinary s quare matrices of
generalized eigenvalues, generalized eigenvectors,
generalized S chur forms, as well as left and right
S chur vectors (lapack function GGES ).

EigenS olver2Block ed Compute generalized eigenvalues and eigenvectors


for a pair of regular s quare matrices using a block
algorithm (lapack function GGEV3). Both matrices
must be the same size. The method parameters are
exactly the same as EigenS olver2.
EigenS olver2S hurBlock ed Compute a pair of regular s quare matrices of
generalized eigenvalues, generalized eigenvectors,
generalized S chur forms, as well as left and right
S chur vectors (lapack function GGES3).

© 2000-2025, MetaQuotes Ltd.


1529 Matrix and Vector Methods

EigenSolver
Compute eigenvalues and eigenvectors of a regular s quare matrix using the classical algorithm (lapack
function GEEV).
Computing for type matrix<double>
bool matrix::EigenSolver(
ENUM_EIG_VECTORS jobv, // compute left and right eigenvectors
vectorc& eigen_values, // vector of computed eigenvalues
matrix& left_eigenvectors, // matrix of computed left vectors
matrix& right_eigenvectors // matrix of computed right vectors
);

Computing for type matrix<float>


bool matrixf::EigenSolver(
ENUM_EIG_VECTORS jobv, // compute left and right eigenvectors
vectorcf& eigen_values, // vector of computed eigenvalues
matrixf& left_eigenvectors, // matrix of computed left vectors
matrixf& right_eigenvectors // matrix of computed right vectors
);

Computing for type matrix<complex>


bool matrixc::EigenSolver(
ENUM_EIG_VECTORS jobv, // compute left and right vectors
vectorc& eigen_values, // vector of computed eigenvalues
matrixc& left_eigenvectors, // matrix of computed left vectors
matrixc& right_eigenvectors // matrix of computed right vectors
);

Computing for type matrix<complexf>


bool matrixcf::EigenSolver(
ENUM_EIG_VECTORS jobv, // compute left and right vectors
vectorcf& eigen_values, // vector of computed eigenvalues
matrixcf& left_eigenvectors, // matrix of computed left vectors
matrixcf& right_eigenvectors // matrix of computed right vectors
);

Parameters
jobv
[in] ENUM _EIG_VECTORS enumeration value which determines the method for computing left and
right eigenvectors.
EV
[out] Vector of eigenvalues.
left_eigenvectors
[out] Matrix of left eigenvectors.

© 2000-2025, MetaQuotes Ltd.


1530 Matrix and Vector Methods

right_eigenvectors
[out] Matrix of right eigenvectors.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

Computation depends on the value of the jobv parameter.


If EIGVECTORS_N is set, the left and right vectors are not computed. Only eigenvalues are
computed.
W ith EIGVECTORS_L, only left eigenvectors are computed, right eigenvectors are not computed.
W hen EIGVECTORS_R is set, only the right eigenvectors are computed, the left vectors are not
computed.
W ith EIGVECTORS_L R , the left and right eigenvectors are computed, Eigenvalues are always
computed.
R eal(non-complex) matrices can have a complex solution. Therefore, the vector of eigenvalues
must be complex. In case of a complex solution, the error code is set to 4019
(ERR_M ATH_OVERFLOW ). Otherwise, only the real parts of the complex values of the eigenvalue
vector should be used.

ENUM_EIG_VECTORS

An enumeration that specifies whether to calculate eigenvectors.

ID Description

EIGVECTORS_N Only eigenvalues are calculated, without vectors.


EIGVECTORS_L Only left eigenvectors are computed.
EIGVECTORS_R Only right eigenvectors are computed.
EIGVECTORS_L R Left and right eigenvectors are computed, eigenvalues are
always computed.

© 2000-2025, MetaQuotes Ltd.


1531 Matrix and Vector Methods

EigenSolverX
Compute eigenvalues and eigenvectors of a regular s quare matrix in Expert mode, i.e. with the ability
to influence the computation algorithm and the ability to obtain accompanying computation data
(lapack function GEEVX).
Computing for type matrix<double>
bool matrix::EigenSolverX(
ENUM_EIG_BALANCE balance, // input matrix balancing method
ENUM_EIG_VECTORS jobv, // determines computation of right and left eigen
ENUM_EIG_SENSE sense, // determines computation of reciprocal condition
vectorc& eigen_values, // vector of computed eigenvalues
matrix& left_eigenvectors, // matrix of computed left vectors
matrix& right_eigenvectors // matrix of computed right vectors
matrix& shur_matrix, // balanced matrix in Schur form
long& ilo, // subscript of balanced matrix
long& ihi, // superscript of balanced matrix
vector& scale, // details of permutations and scaling when balan
double& ab_norm, // 1-norm of balanced matrix
vector& rconde, // vector of reciprocal condition numbers for eac
vector& rcondv // vector of reciprocal condition numbers for eac
);

Computing for type matrix<float>


bool matrixf::EigenSolverX(
ENUM_EIG_BALANCE balance, // input matrix balancing method
ENUM_EIG_VECTORS jobv, // determines computation of right and left eigen
ENUM_EIG_SENSE sense, // determines computation of reciprocal condition
vectorcf& eigen_values, // vector of computed eigenvalues
matrixf& left_eigenvectors, // matrix of computed left vectors
matrixf& right_eigenvectors // matrix of computed right vectors
matrixf& shur_matrix, // balanced matrix in Schur form
long& ilo, // subscript of balanced matrix
long& ihi, // superscript of balanced matrix
vectorf& scale, // details of permutations and scaling when balan
float& ab_norm, // 1-norm of balanced matrix
vectorf& rconde, // vector of reciprocal condition numbers for eac
vectorf& rcondv // vector of reciprocal condition numbers for eac
);

Computing for type matrix<complex>


bool matrixc::EigenSolverX(
ENUM_EIG_BALANCE balance, // input matrix balancing method
ENUM_EIG_VECTORS jobv, // determines computation of right and left eigen
ENUM_EIG_SENSE sense, // determines computation of reciprocal condition
vectorc& eigen_values, // vector of computed eigenvalues

© 2000-2025, MetaQuotes Ltd.


1532 Matrix and Vector Methods

matrixc& left_eigenvectors, // matrix of computed left vectors


matrixc& right_eigenvectors // matrix of computed right vectors
matrixc& shur_matrix, // balanced matrix in Schur form
long& ilo, // subscript of balanced matrix
long& ihi, // superscript of balanced matrix
vector& scale, // details of permutations and scaling when balan
double& ab_norm, // 1-norm of balanced matrix
vector& rconde, // vector of reciprocal condition numbers for eac
vector& rcondv // vector of reciprocal condition numbers for eac
);

Computing for type matrix<complexf>


bool matrixcf::EigenSolverX(
ENUM_EIG_BALANCE balance, // input matrix balancing method
ENUM_EIG_VECTORS jobv, // determines computation of right and left eigen
ENUM_EIG_SENSE sense, // determines computation of reciprocal condition
vectorcf& eigen_values, // vector of computed eigenvalues
matrixcf& left_eigenvectors, // matrix of computed left vectors
matrixcf& right_eigenvectors // matrix of computed right vectors
matrixcf& shur_matrix, // balanced matrix in Schur form
long& ilo, // subscript of balanced matrix
long& ihi, // superscript of balanced matrix
vectorf& scale, // details of permutations and scaling when balan
float& ab_norm, // 1-norm of balanced matrix
vectorf& rconde, // vector of reciprocal condition numbers for eac
vectorf& rcondv // vector of reciprocal condition numbers for eac
);

Parameters
balance
[in] Valuefrom the ENUM _EIG_BALANCE enumeration which determines the need and method for
balancing the input matrix; it is used to improve the conditioning of the eigenvalues and
eigenvectors.
jobv
[in] ENUM _EIG_VECTORS enumeration value which determines the method for computing left and
right eigenvectors.
sense
[in] Value from the ENUM _EIG_SENSE enumeration determining the need to compute reciprocal
condition numbers.
eigen_values
[out] Vector of eigenvalues.
left_eigenvectors
[out] Matrix of left eigenvectors.
right_eigenvectors

© 2000-2025, MetaQuotes Ltd.


1533 Matrix and Vector Methods

[out] Matrix of right eigenvectors.


shur_matrix
[out] Balanced matrix in S chur form; the matrix is not filled if neither left nor right eigenvectors
are computed.
ilo
[out] S ubscript of the balanced matrix; the matrix is not filled if no balancing is applied.
ihi
[out] S uperscript of the balanced matrix; the matrix is not filled if no balancing is applied.
scale
[out] Vector of details of permutations and scaling when balancing the input matrix.
Details of the permutations and scaling factors applied when balancing A.
If P(j) is the index of the row and column interchanged with row and column j, and D(j) is
the scaling factor applied to row and column j, then
scale(j) = P(j), for j = 1,...,ilo-1
= D(j), for j = ilo,...,ihi
= P(j) for j = ihi+1,..., n.
The order in which the interchanges are made is n to ihi+1, then 1 to ilo-1.
ab_norm
[out] 1-norm of the balanced matrix (the maximum of the sum of absolute values of elements in
any of the matrix columns).
rconde
[out] Vector of reciprocal condition numbers for each eigenvalue; it is computed if the 'sense'
parameter is set to 'E' or 'B'.
rcondv
[out] Vector of reciprocal condition numbers for each eigenvector; it is computed if the 'sense'
parameter is set to 'V' or 'B.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

Input matrix balancing depends on the value of the 'balance' parameter.

ENUM_EIG_BALANCE

An enumeration defining the need to compute eigenvectors.

© 2000-2025, MetaQuotes Ltd.


1534 Matrix and Vector Methods

ID Description

EIGBAL ANCE_N Do not diagonally scale or permute


EIGBAL ANCE_P Perform permutations to make the matrix more nearly upper
triangular. Do not diagonally scale
EIGBAL ANCE_S Diagonally scale the matrix. Do not permute
EIGBAL ANCE_B Both diagonally scale and permute

ENUM_EIG_VECTORS

An enumeration defining the need to compute eigenvectors.

ID Description

EIGVECTORS_N Only eigenvalues are computed, without vectors.


EIGVECTORS_L Only left eigenvectors are computed.
EIGVECTORS_R Only right eigenvectors are computed.
EIGVECTORS_L R Left and right eigenvectors are computed, eigenvalues are
always computed.

ENUM_EIG_SENSE

An enumeration defining the need to compute eigenvectors.

ID Description

EIGSENSE_N None of reciprocal condition numbers are computed


EIGSENSE_E Computed for eigenvalues only
EIGSENSE_V Computed for right eigenvectors only
EIGSENSE_B Computed for eigenvalues and right eigenvectors

© 2000-2025, MetaQuotes Ltd.


1535 Matrix and Vector Methods

EigenSolverShur
Compute eigenvalues, upper triangular matrix in S chur form, and matrix of S chur vectors (lapack
function GEES ). S ee also S chur decomposition.
Computing for type matrix<double>
bool matrix::EigenSolverShur(
ENUM_EIG_VECTORS jobvs, // method to compute Shur vectors
vectorc& eigen_values, // vector of computed eigenvalues
matrix& shur_matrix, // matrix in Schur form
matrix& shur_vectors // matrix of Schur vectors
);

Computing for type matrix<float>


bool matrixf::EigenSolverShur(
ENUM_EIG_VECTORS jobvs, // method to compute Shur vectors
vectorcf& eigen_values, // vector of computed eigenvalues
matrixf& shur_matrix, // matrix in Schur form
matrixf& shur_vectors // matrix of Schur vectors
);

Computing for type matrix<complex>


bool matrixc::EigenSolverShur(
ENUM_EIG_VECTORS jobvs, // method to compute Shur vectors
vectorc& eigen_values, // vector of computed eigenvalues
matrixc& shur_matrix, // matrix in Schur form
matrixc& shur_vectors // matrix of Schur vectors
);

Computing for type matrix<complexf>


bool matrixcf::EigenSolverShur(
ENUM_EIG_VECTORS jobvs, // method to compute Shur vectors
vectorcf& eigen_values, // vector of computed eigenvalues
matrixcf& shur_matrix, // matrix in Schur form
matrixcf& shur_vectors // matrix of Schur vectors
);

Parameters
jobvs
[in] Value from the ENUM _EIG_SHUR enumeration, which defines the method for computing S hur
vectors.
eigen_values
[out] Vector of eigenvalues.
shur_matrix
[out] Upper triangular S chur matrix (S chur form for the input matrix).

© 2000-2025, MetaQuotes Ltd.


1536 Matrix and Vector Methods

shur_vectors
[out] Matrix of S chur vectors ; it is not computed if the jobvs parameter is set to N.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

Computation depends on the jobvs parameter values.


R eal(non-complex) matrices can have a complex solution. Therefore, the input vector of
eigenvalues must be complex. In case of a complex solution, the error code is set to 4019
(ERR_M ATH_OVERFLOW ). Otherwise, only the real parts of the complex values of the eigenvalue
vector should be used.

EigenSolverShur

An enumeration defining the need to compute eigenvectors.

ID Description

EIGSHUR_N S chur vectors are not computed


EIGSHUR_V S chur vectors are computed

© 2000-2025, MetaQuotes Ltd.


1537 Matrix and Vector Methods

EigenSolver2
Compute generalized eigenvalues and eigenvectors for a pair of ordinary s quare matrices (lapack
function GGEV). Both matrices must be the same size.
Computing for type matrix<double>
bool matrix::EigenSolver2(
matrix& B, // second matrix in the pair
ENUM_EIG_VECTORS jobv, // method to compute right and left vectors
vectorc& alpha, // vector of computed eigenvalues
vector& beta, // vector of eigenvalue divisors
matrix& left_eigenvectors, // matrix of computed left vectors
matrix& right_eigenvectors // matrix of computed right vectors
);

Computing for type matrix<float>


bool matrixf::EigenSolver2(
matrix& B, // second matrix in the pair
ENUM_EIG_VECTORS jobv, // method to compute right and left vectors
vectorcf& alpha, // vector of computed eigenvalues
vectorf& beta, // vector of eigenvalue divisors
matrixf& left_eigenvectors, // matrix of computed left vectors
matrixf& right_eigenvectors // matrix of computed right vectors
);

Computing for type matrix<complex>


bool matrixc::EigenSolver2(
matrixc& B, // second matrix in the pair
ENUM_EIG_VECTORS jobv, // method to compute right and left vectors
vectorc& alpha, // vector of computed eigenvalues
vectorc& beta, // vector of eigenvalue divisors
matrixc& left_eigenvectors, // matrix of computed left vectors
matrixc& right_eigenvectors // matrix of computed right vectors
);

Computing for type matrix<complexf>


bool matrixcf::EigenSolver2(
matrixcf& B, // second matrix in the pair
ENUM_EIG_VECTORS jobv, // method to compute right and left vectors
vectorcf& alpha, // vector of computed eigenvalues
vectorcf& beta, // vector of eigenvalue divisors
matrixcf& left_eigenvectors, // matrix of computed left vectors
matrixcf& right_eigenvectors // matrix of computed right vectors
);

Parameters

© 2000-2025, MetaQuotes Ltd.


1538 Matrix and Vector Methods

B
[in] The second matrix in the pair.
jobv
[in] ENUM _EIG_VECTORS enumeration value which determines the method for computing left and
right eigenvectors.
alpha
[out] Vector of eigenvalues.
beta
[out] Vector of eigen value divisors.
left_eigenvectors
[out] Matrix of left eigenvectors.
right_eigenvectors
[out] Matrix of right eigenvectors.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

Computation depends on the value of the jobv parameter.


ENUM_EIG_VECTORS

An enumeration defining the need to compute eigenvectors.

ID Description

EIGVECTORS_N Only eigenvalues are computed, without vectors.


EIGVECTORS_L Only left eigenvectors are computed.
EIGVECTORS_R Only right eigenvectors are computed.
EIGVECTORS_L R Left and right eigenvectors are computed, eigenvalues are
always computed.

A generalized eigenvalue for a pair of matrices (A,B) is a scalar lambda or a ratio alpha/beta =
lambda, such that A - lambda*B is singular. It is usually represented as the pair (alpha,beta), as there
is a reasonable interpretation for beta=0, and even for both being zero.
The right eigenvector v(j) corresponding to the eigenvalue lambda(j) of (A,B) satisfies
A* v(j) = lambda(j) * B * v(j).
The left eigenvector u(j) corresponding to the eigenvalue lambda(j) of (A,B) satisfies
u(j)**H * A = lambda(j) * u(j)**H * B .

© 2000-2025, MetaQuotes Ltd.


1539 Matrix and Vector Methods

where u(j)**H is the conjugate-transpose of u(j).


R eal (non-complex) matrices can have a complex solution. Therefore, the input vector of eigenvalues
must be complex. In case of a complex solution, the error code is set to 4019
(ERR_M ATH_OVERFLOW ). Otherwise, only the real parts of the complex values of the eigenvalue
vector should be used.

© 2000-2025, MetaQuotes Ltd.


1540 Matrix and Vector Methods

EigenSolver2X
Compute generalized eigenvalues and eigenvectors for a pair of regular s quare matrices in Expert
mode, i.e. with the ability to influence the computation algorithm and the ability to obtain
accompanying computation data (lapack function GGEVX). Both matrices must be the same size.
Optionally, it also computes a balancing transformation to improve the conditioning of the eigenvalues
and eigenvectors (ILO, IHI, LS CALE, RS CALE, ABNRM, and BBNRM), reciprocal condition numbers for
the eigenvalues (RCONDE), and reciprocal condition numbers for the right eigenvectors (RCONDV).
Computing for type matrix<double>
bool matrix::EigenSolver2X(
matrix& B, // second matrix in the pair
ENUM_EIG_BALANCE balance, // input matrix balancing method
ENUM_EIG_VECTORS jobv, // determines computation of right and left eigen
ENUM_EIG_SENSE sense, // determines computation of reciprocal condition
vectorc& alpha, // vector of computed eigenvalues
vector& beta, // vector of eigenvalue divisors
matrix& left_eigenvectors, // matrix of computed left vectors
matrix& right_eigenvectors // matrix of computed right vectors
matrix& shur_matrix1, // the first part of the real Schur form of the "
matrix& shur_matrix2, // the second part of the real Schur form of the
long& ilo, // subscript of balanced matrix
long& ihi, // superscript of balanced matrix
vector& lscale, // details of the permutations and scaling factor
vector& rscale, // details of the permutations and scaling factor
double& ab_norm, // one-norm of balanced input matrix
double& bb_norm, // one-norm of balanced second matrix B
vector& rconde, // vector of reciprocal condition numbers for eac
vector& rcondv // vector of reciprocal condition numbers for eac
);

Computing for type matrix<complex>


bool matrixc::EigenSolver2X(
matrixc& B, // second matrix in the pair
ENUM_EIG_BALANCE balance, // input matrix balancing method
ENUM_EIG_VECTORS jobv, // determines computation of right and left eigen
ENUM_EIG_SENSE sense, // determines computation of reciprocal condition
vectorc& alpha, // vector of computed eigenvalues
vectorc& beta, // vector of eigenvalue divisors
matrixc& left_eigenvectors, // matrix of computed left vectors
matrixc& right_eigenvectors // matrix of computed right vectors
matrixc& shur_matrix1, // the first part of the real Schur form of the "
matrixc& shur_matrix2, // the second part of the real Schur form of the
long& ilo, // subscript of balanced matrix
long& ihi, // superscript of balanced matrix
vector& lscale, // details of the permutations and scaling factor

© 2000-2025, MetaQuotes Ltd.


1541 Matrix and Vector Methods

vector& rscale, // details of the permutations and scaling factor


double& ab_norm, // one-norm of balanced input matrix
double& bb_norm, // one-norm of balanced second matrix B
vector& rconde, // vector of reciprocal condition numbers for eac
vector& rcondv // vector of reciprocal condition numbers for eac
);

Parameters
B
[in] The second matrix in the pair.
balance
[in] Valuefrom the ENUM _EIG_BALANCE enumeration which determines the need and method for
balancing the input matrix; it is used to improve the conditioning of the eigenvalues and
eigenvectors.
jobv
[in] Value from the ENUM _EIG_VECTORS enumeration which determines the method for
computing left and right eigenvectors.
sense
[in] Value from the ENUM _EIG_SENSE enumeration which determines the need to compute
reciprocal condition numbers.
eigen_values
[out] Vector of eigenvalues.
left_eigenvectors
[out] Matrix of left eigenvectors.
right_eigenvectors
[out] Matrix of right eigenvectors.
shur_matrix1, shur_matrix2
[out] 2 parts of balanced matrix in S chur form; the matrix is not filled if neither left nor right
eigenvectors are computed.
ilo
[out] S ubscript of the balanced matrix; the matrix is not filled if no balancing is applied.
ihi
[out] S uperscript of the balanced matrix; the matrix is not filled if no balancing is applied.
lscale
[out] Vector contains details of the permutations and scaling factors applied to the left side of A
and B.
If PL(j) is the index of the row interchanged with row j, and DL(j) is the scaling factor applied to
row j, then
lscale(j) = PL(j), for j = 1,..., ilo-1
= DL(j), for j = ilo,...,ihi

© 2000-2025, MetaQuotes Ltd.


1542 Matrix and Vector Methods

= PL(j) for j = ihi+1,..., n.


The order in which the interchanges are made is n to ihi+1, then 1 to ilo-1.
rscale
[out] Vector contains details of the permutations and scaling factors applied to the right side of A
and B.
If PR(j) is the index of the column interchanged with column j, and DR (j) is the scaling factor
applied to column j, then
rscale(j) = PR(j), for j = 1,..., ilo-1
= DR (j), for j = ilo,...,ihi
= PR (j) for j = ihi+1,..., n.
The order in which the interchanges are made is n to ihi+1, then 1 to ilo-1.
ab_norm
[out] One-norm of the balanced input matrix (the maximum of the sum of absolute values of
elements in any of the matrix columns).
bb_norm
[out] One-norm of balanced second matrix B.
rconde
[out] Vector of reciprocal condition numbers for each eigenvalue; it is computed if the 'sense'
parameter is set to 'E' or 'B'.
rcondv
[out] Vector of reciprocal condition numbers for each eigenvector; it is computed if the 'sense'
parameter is set to 'V' or 'B'.

Return Value

The function returns 'true' on success or 'false' if an error occurs.


Note

Input matrices balancing depends on the value of the balance parameter.


ENUM_EIG_BALANCE

An enumeration that specifies whether the matrices should be balanced.

ID Description

EIGBAL ANCE_N Do not diagonally scale or permute.


EIGBAL ANCE_P Perform permutations to make the matrix more nearly upper
triangular. Do not diagonally scale.
EIGBAL ANCE_S Diagonally scale the matrix. Do not permute.
EIGBAL ANCE_B Both diagonally scale and permute.

© 2000-2025, MetaQuotes Ltd.


1543 Matrix and Vector Methods

ENUM_EIG_VECTORS

An enumeration defining the need to compute eigenvectors.

ID Description

EIGVECTORS_N Only eigenvalues are computed, without vectors.


EIGVECTORS_L Only left eigenvectors are computed.
EIGVECTORS_R Only right eigenvectors are computed.
EIGVECTORS_L R Left and right eigenvectors are computed, eigenvalues are
always computed.

ENUM_EIG_SENSE

An enumeration determining the need to compute reciprocal condition numbers.

ID Description

EIGSENSE_N None of reciprocal condition numbers are computed.


EIGSENSE_E Computed for eigenvalues only.
EIGSENSE_V Computed for right eigenvectors only.
EIGSENSE_B Computed for eigenvalues and right eigenvectors.

© 2000-2025, MetaQuotes Ltd.


1544 Matrix and Vector Methods

EigenSolver2Shur
Compute a pair of ordinary s quare matrices of generalized eigenvalues, generalized eigenvectors,
generalized S chur forms, as well as left and right S chur vectors (lapack function GGES ).
Сomputes the generalized eigenv alues , the generalized real/complex S chur form (S,T), optionally, the
left and/or right matrices of Schur vectors (vsl and vsr) for a pair of n-by-n real/complex
z
nonsymmetric matrices (A,B). This gives the generali ed Schur factori ation: z
(A,B) = ( vsl*S *vsrH, vsl*T*vsrH )

Optionally, it also orders the eigenvalues so that a selected cluster of eigenvalues appears in the
leading diagonal blocks of the upper quasi-triangular matrix S and the upper triangular matrix T. The
leading columns of vsl and vsr then form an orthonormal/unitary basis for the corresponding left and
right eigenspaces (deflating subspaces).

Computing for type matrix<double>


bool matrix::EigenSolver2Shur(
matrix& B, // second matrix in the pair
ENUM_EIG_VECTORS jobvs, // method to compute left and right vectors
vector& alpha, // vector of computed eigenvalues
vector& beta, // vector of eigenvalue divisors
matrix& shur_s, // matrix S in Schur form
matrix& shur_t, // matrix T in Schur form
matrix& vsl, // matrix of left Schur vectors vsl
matrix& vsr // matrix of right Schur vectors vsr
);

Computing for type matrix<complex>


bool matrix::EigenSolver2Shur(
matrixc& B, // second matrix in the pair
ENUM_EIG_VECTORS jobvs, // method to compute left and right vectors
vectorc& alpha, // vector of computed eigenvalues
vectorc& beta, // vector of eigenvalue divisors
matrixc& shur_s, // matrix S in Schur form
matrixc& shur_t, // matrix T in Schur form
matrixc& vsl, // matrix of left Schur vectors vsl
matrixc& vsr // matrix of right Schur vectors vsr
);

Parameters
B
[out] The second matrix in the pair.
jobvs
[in] ENUM _EIG_VECTORS enumeration value which determines the method for computing left and
right eigenvectors.
alpha

© 2000-2025, MetaQuotes Ltd.


1545 Matrix and Vector Methods

[out] Vector of eigenvalues.


beta
[out] Vector of eigenvalue divisors.
shur_s
[out] Matrix S , block upper triangular S chur matrix (S chur form for the input matrix).
shur_t
[out] Matrix T, block upper triangular S chur matrix (S chur form for the second matrix in the pair).
vsl
[out] Matrix of left S chur vectors.
vsr
[out] Matrix of right S chur vectors.

Return Value

The function returns 'true' on success or 'false' if an error occurs.


Note

Computation depends on the jobvs parameter values.


The second matrix in the pair must be the same size as the first (input) one.
R eal(non-complex) matrices can have a complex solution. Therefore, the vector of eigenvalues
must be complex. In case of a complex solution, the error code is set to 4019
(ERR_M ATH_OVERFLOW ). Otherwise, only the real parts of the complex values of the eigenvalue
vector should be used.

EigenSolverShur

An enumeration defining the need to compute eigenvectors.

ID Description

EIGVECTORS_N Only eigenvalues are computed, without vectors.


EIGVECTORS_L Only left eigenvectors are computed.
EIGVECTORS_R Only right eigenvectors are computed.
EIGVECTORS_L R Left and right eigenvectors are computed, eigenvalues are
always computed.

© 2000-2025, MetaQuotes Ltd.


1546 Matrix and Vector Methods

EigenSolver2Blocked
Compute generalized eigenvalues and eigenvectors for a pair of regular s quare matrices using a block
algorithm (lapack function GGEV3). Both matrices must be the same size. The method parameters are
exactly the same as EigenS olver2.
Computing for type matrix<double>
bool matrix::EigenSolver2Blocked(
matrix& B, // second matrix in the pair
ENUM_EIG_VECTORS jobv, // method to compute right and left vectors
vectorc& alpha, // vector of computed eigenvalues
vector& beta, // vector of eigenvalue divisors
matrix& left_eigenvectors, // matrix of computed left vectors
matrix& right_eigenvectors // matrix of computed right vectors
);

Computing for type matrix<float>


bool matrixf::EigenSolver2Blocked(
matrix& B, // second matrix in the pair
ENUM_EIG_VECTORS jobv, // method to compute right and left vectors
vectorcf& alpha, // vector of computed eigenvalues
vectorf& beta, // vector of eigenvalue divisors
matrixf& left_eigenvectors, // matrix of computed left vectors
matrixf& right_eigenvectors // matrix of computed right vectors
);

Computing for type matrix<complex>


bool matrix::EigenSolver2Blocked(
matrixc& B, // second matrix in the pair
ENUM_EIG_VECTORS jobv, // method to compute right and left vectors
vectorc& alpha, // vector of computed eigenvalues
vectorc& beta, // vector of eigenvalue divisors
matrixc& left_eigenvectors, // matrix of computed left vectors
matrixc& right_eigenvectors // matrix of computed right vectors
);

Computing for type matrix<complexf>


bool matrixcf::EigenSolver2(
matrixcf& B, // second matrix in the pair
ENUM_EIG_VECTORS jobv, // method to compute right and left vectors
vectorcf& alpha, // vector of computed eigenvalues
vectorcf& beta, // vector of eigenvalue divisors
matrixcf& left_eigenvectors, // matrix of computed left vectors
matrixcf& right_eigenvectors // matrix of computed right vectors
);

Parameters

© 2000-2025, MetaQuotes Ltd.


1547 Matrix and Vector Methods

B
[out] The second matrix in the pair.
jobv
[in] ENUM _EIG_VECTORS enumeration value which determines the method for computing left and
right eigenvectors.
alpha
[out] Vector of eigenvalues.
beta
[out] Vector of eigenvalue divisors.
left_eigenvectors
[out] Matrix of left eigenvectors.
righeft_eigenvectors
[out] Matrix of right eigenvectors.

Return Value

The function returns 'true' on success or 'false' if an error occurs.


Note

Computation depends on the value of the jobv parameter.


A generalized eigenvalue for a pair of matrices (A,B) is a scalar lambda or a ratio alpha/beta =
lambda, such that A - lambda*B is singular. It is usually represented as the pair (alpha,beta), as
there is a reasonable interpretation for beta=0, and even for both being zero.
The right eigenvector v(j) corresponding to the eigenvalue lambda(j) of (A,B) satisfies :
A* v(j) = lambda(j) * B * v(j).
The left eigenvector u(j) corresponding to the eigenvalue lambda(j) of (A,B) satisfies :
u(j)**H * A = lambda(j) * u(j)**H * B .
where u(j)**H is the conjugate-transpose of u(j).
R eal(non-complex) matrices can have a complex solution. Therefore, the input vector of
eigenvalues must be complex. In case of a complex solution, the error code is set to 4019
(ERR_M ATH_OVERFLOW ). Otherwise, only the real parts of the complex values of the eigenvalue
vector should be used.

ENUM_EIG_VECTORS

An enumeration defining the need to compute eigenvectors.

ID Description

EIGVECTORS_N Only eigenvalues are computed, without vectors.

© 2000-2025, MetaQuotes Ltd.


1548 Matrix and Vector Methods

ID Description

EIGVECTORS_L Only left eigenvectors are computed.


EIGVECTORS_R Only right eigenvectors are computed.
EIGVECTORS_L R Left and right eigenvectors are computed, eigenvalues are
always computed.

© 2000-2025, MetaQuotes Ltd.


1549 Matrix and Vector Methods

EigenSolver2ShurBlocked
Compute a pair of regular s quare matrices of generalized eigenvalues, generalized eigenvectors,
generalized S chur forms, as well as left and right S chur vectors (lapack function GGES3).
Сomputes the generalized eigenv alues , the generalized real/complex S chur form (S,T), optionally, the
left and/or right matrices of Schur vectors (VSL and VSR) for a pair of n-by-n real/complex
z
nonsymmetric matrices (A,B). This gives the generali ed Schur factori ation:z
(A,B) = ( vsl*S *vsrH, vsl*T*vsrH )

Optionally, it also orders the eigenvalues so that a selected cluster of eigenvalues appears in the
leading diagonal blocks of the upper quasi-triangular matrix S and the upper triangular matrix T. The
leading columns of vsl and vsr then form an orthonormal/unitary basis for the corresponding left and
right eigenspaces (deflating subspaces).

Computing for type matrix<double>


bool matrix::EigenSolver2ShurBlocked(
matrix& B, // second matrix in the pair
ENUM_EIG_VECTORS jobvs, // method to compute left and right vectors
vectorc& alpha, // vector of computed eigenvalues
vector& beta, // vector of eigenvalue divisors
matrix& shur_s, // matrix S in Schur form
matrix& shur_t, // matrix T in Schur form
matrix& vsl, // matrix of left Schur vectors VSL
matrix& vsr // matrix of right Schur vectors VSR
);

Computing for type matrix<float>


bool matrix::EigenSolver2ShurBlocked(
matrixf& B, // second matrix in the pair
ENUM_EIG_VECTORS jobvs, // method to compute left and right vectors
vectorcf& alpha, // vector of computed eigenvalues
vectorf& beta, // vector of eigenvalue divisors
matrixf& shur_s, // matrix S in Schur form
matrixf& shur_t, // matrix T in Schur form
matrixf& vsl, // matrix of left Schur vectors VSL
matrixf& vsr // matrix of right Schur vectors VSR
);

Computing for type matrix<complex>


bool matrix::EigenSolver2ShurBlocked(
matrixc& B, // second matrix in the pair
ENUM_EIG_VECTORS jobvs, // method to compute left and right vectors
vectorc& alpha, // vector of computed eigenvalues
vectorc& beta, // vector of eigenvalue divisors
matrixc& shur_s, // matrix S in Schur form
matrixc& shur_t, // matrix T in Schur form

© 2000-2025, MetaQuotes Ltd.


1550 Matrix and Vector Methods

matrixc& vsl, // matrix of left Schur vectors VSL


matrixc& vsr // matrix of right Schur vectors VSR
);

Computing for type matrix<complexf>


bool matrix::EigenSolver2ShurBlocked(
matrixcf& B, // second matrix in the pair
ENUM_EIG_VECTORS jobvs, // method to compute left and right vectors
vectorcf& alpha, // vector of computed eigenvalues
vectorcf& beta, // vector of eigenvalue divisors
matrixcf& shur_s, // matrix S in Schur form
matrixcf& shur_t, // matrix T in Schur form
matrixcf& vsl, // matrix of left Schur vectors VSL
matrixcf& vsr // matrix of right Schur vectors VSR
);

Parameters
B
[in] The second matrix in the pair.
jobvs
[in] ENUM _EIG_VECTORS enumeration value which determines the method for computing left and
right eigenvectors.
alpha
[out] Vector of eigenvalues.
beta
[out] Vector of eigenvalue divisors.
shur_s
[out] Matrix S , block upper triangular S chur matrix (S chur form for the input matrix).
shur_t
[out] Matrix T, block upper triangular S chur matrix (S chur form for the second matrix in the pair).
vsl
[out] Matrix of left S chur vectors VS L.
vsr
[out] Matrix of right S chur vectors VSR.

Return Value

The function returns 'true' on success or 'false' if an error occurs.


Note

Computation depends on the jobvs parameter values.

© 2000-2025, MetaQuotes Ltd.


1551 Matrix and Vector Methods

The second matrix in the pair must be the same size as the first (input) one.
R eal(non-complex) matrices can have a complex solution. Therefore, the vector of eigenvalues
must be complex. In case of a complex solution, the error code is set to 4019
(ERR_M ATH_OVERFLOW ). Otherwise, only the real parts of the complex values of the eigenvalue
vector should be used.

EigenSolverShur

An enumeration defining the need to compute eigenvectors.

ID Description

EIGVECTORS_N Only eigenvalues are computed, without vectors.


EIGVECTORS_L Only left eigenvectors are computed.
EIGVECTORS_R Only right eigenvectors are computed.
EIGVECTORS_L R Left and right eigenvectors are computed, eigenvalues are
always computed.

© 2000-2025, MetaQuotes Ltd.


1552 Matrix and Vector Methods

Symmetric Matrices
Functions for computing eigenvalues and eigenvectors of symmetric or Hermitian matrices using the
divide and conquer algorithm, making the process efficient and fast. These methods can be applied to
matrices of different data types, including real and complex numbers.

Function Action

EigenS ymmetricDC Compute eigenvalues and eigenvectors of a


symmetric or Hermitian (complex conjugate) matrix
using the divide-and-conquer algorithm (lapack
functions SYEVD, HEEVD).
EigenS ymmetricQR Compute eigenvalues and eigenvectors of a
symmetric or Hermitian (complex conjugate) matrix
using the QR algorithm (lapack functions SYEV,
HEEV).

EigenS ymmetricR obust Compute eigenvalues and eigenvectors of a


symmetric or Hermitian (complex conjugate) matrix
using the Multiple Relatively Robust Representations,
M RRR algorithm (lapack functions SYEVR, HEEVR).
EigenS ymmetricBisect Compute eigenvalues and eigenvectors of a
symmetric or Hermitian (complex conjugate) matrix
using the bisection algorithm (lapack functions
SYEVX, HEEVX).

© 2000-2025, MetaQuotes Ltd.


1553 Matrix and Vector Methods

EigenSymmetricDC
Compute eigenvalues and eigenvectors of a symmetric or Hermitian (complex conjugated) matrix
using the divide-and-conquer algorithm (lapack functions SYEVD, HEEVD).
Computing for type matrix<double>
bool matrix::EigenSymmetricDC(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
vector& eigen_values, // vector of computed eigenvalues
matrix& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<float>


bool matrixf::EigenSymmetricDC(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
vectorf& eigen_values, // vector of computed eigenvalues
matrixf& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<complex>


bool matrixc::EigenSymmetricDC(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
vector& eigen_values, // vector of computed eigenvalues
matrixc& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<complexf>


bool matrixcf::EigenSymmetricDC(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
vectorf& eigen_values, // vector of computed eigenvalues
matrixcf& eigen_vectors // matrix of computed eigenvectors
);

Parameters
jobv
[in] ENUM _EIG_VAL UES enumeration value which determines the method for computing
eigenvectors.
eigen_values
[out] Vector of eigenvalues.
eigen_vectors
[out] Matrix of eigenvectors.

Return Value

R eturn true if successful, otherwise false in case of an error.

© 2000-2025, MetaQuotes Ltd.


1554 Matrix and Vector Methods

Note

Computation depends on the value of the jobv parameter.


W hen jobv = EIGVAL UES_V, eigenvectors and eigenvalues are calculated.
If EIGVALUES_N is set, eigenvectors are not calculated. Only eigenvalues are computed.
The input can be a symmetric (Hermitian), upper triangular or lower triangular matrix. Triangular
matrices are assumed to be symmetric (Hermitian conjugated).

ENUM_EIG_VALUES

An enumeration that specifies whether to calculate eigenvectors.

ID Description

EIGVAL UES_V Eigenvectors and eigenvalues are calculated.


EIGVAL UES_N Only eigenvalues are calculated, without vectors.

© 2000-2025, MetaQuotes Ltd.


1555 Matrix and Vector Methods

EigenSymmetricQR
Compute eigenvalues and eigenvectors of a symmetric or Hermitian (complex conjugated) matrix
using the QR algorithm (lapack functions SYEV, HEEV).
Computing for type matrix<double>
bool matrix::EigenSymmetricQR(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
vector& eigen_values, // vector of computed eigenvalues
matrix& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<float>


bool matrixf::EigenSymmetricQR(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
vectorf& eigen_values, // vector of computed eigenvalues
matrixf& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<complex>


bool matrixc::EigenSymmetricQR(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
vector& eigen_values, // vector of computed eigenvalues
matrixc& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<complexf>


bool matrixcf::EigenSymmetricQR(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
vectorf& eigen_values, // vector of computed eigenvalues
matrixcf& eigen_vectors // matrix of computed eigenvectors
);

Parameters
jobv
[in] ENUM _EIG_VAL UES enumeration value which determines the method for computing
eigenvectors.
eigen_values
[out] Vector of eigenvalues.
eigen_vectors
[out] Matrix of eigenvectors.

Return Value

R eturn true if successful, otherwise false in case of an error.

© 2000-2025, MetaQuotes Ltd.


1556 Matrix and Vector Methods

Note

Computation depends on the value of the jobv parameter.


W hen jobv = EIGVAL UES_V, eigenvectors and eigenvalues are calculated.
If EIGVALUES_N is set, eigenvectors are not calculated. Only eigenvalues are computed.
The input can be a symmetric (Hermitian), upper triangular or lower triangular matrix. Triangular
matrices are assumed to be symmetric (Hermitian conjugated).

ENUM_EIG_VALUES

An enumeration defining the need to compute eigenvectors.

ID Description

EIGVAL UES_V Eigenvectors and eigenvalues are calculated.


EIGVAL UES_N Only eigenvalues are computed, without vectors.

© 2000-2025, MetaQuotes Ltd.


1557 Matrix and Vector Methods

EigenSymmetricRobust
Compute eigenvalues and eigenvectors of a symmetric or Hermitian (complex conjugated) matrix
using the Multiple Relatively Robust Representations, M RRR algorithm (lapack functions SYEVR,
HEEVR ).

Computing for type matrix<double>


bool matrix::EigenSymmetricRobust(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
ENUM_BLAS_RANGE range, // subset of eigenvalues to compute
double lower, // lower bound of the subset
double upper, // Upper bound of the subset
double abstol, // absolute error tolerance
vector& eigen_values, // vector of computed eigenvectors
matrix& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<float>


bool matrixf::EigenSymmetricRobust(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
ENUM_BLAS_RANGE range, // subset of eigenvalues to compute
float lower, // lower bound of the subset
float upper, // upper bound of the subset
float abstol, // absolute error tolerance
vectorf& eigen_values, // vector of computed eigenvectors
matrixf& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<complex>


bool matrixc::EigenSymmetricRobust(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
ENUM_BLAS_RANGE range, // subset of eigenvalues to compute
double lower, // lower bound of the subset
double upper, // Upper bound of the subset
double abstol, // absolute error tolerance
vector& eigen_values, // vector of computed eigenvectors
matrixc& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<complexf>


bool matrixcf::EigenSymmetricRobust(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
ENUM_BLAS_RANGE range, // subset of eigenvalues to compute
float lower, // lower bound of the subset
float upper, // Upper bound of the subset
float abstol, // absolute error tolerance

© 2000-2025, MetaQuotes Ltd.


1558 Matrix and Vector Methods

vectorf& eigen_values, // vector of computed eigenvectors


matrixcf& eigen_vectors // matrix of computed eigenvectors
);

Parameters
jobv
[in] ENUM _EIG_VAL UES enumeration value which determines the method for computing
eigenvectors.
range
[in] ENUM _BL AS_RANGE enumeration value that defines a subset of computable eigenvalues and
vectors.
lower
[in]The lower bound of eigenvalues subset; it is specified depending on the value of the 'range'
parameter.
upper
[in]The upper bound of eigenvalues subset; it is specified depending on the value of the 'range'
parameter.
abstol
[in] Absolute error tolerance.
The absolute error tolerance to which each eigenvalue/eigenvector is required.
If jobv = 'V', the eigenvalues and eigenvectors output have residual norms bounded by abstol,
and the dot products between different eigenvectors are bounded by abstol.
If abstol < n *eps *|T|, then n *eps *|T| is used instead, where eps is the machine precision,
and |T| is the 1-norm of the matrix T. The eigenvalues are computed to an accuracy of eps *|
T| irrespective of abstol.
If high relative precision is important, 'abstol' should be set to a safe minimum value X such
that 1.0/X does not overflow.
eigen_values
[out] Vector of eigenvalues.
eigen_vectors
[out] Matrix of eigenvectors.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

Computation depends on the values of the jobv and range parameters.


W hen BL ASRANGE_A is set, all eigenvalues are computed, and the lower and upper parameters are
ignored.
W ith the BLASRANGE_V value, only those eigenvalues (and their vectors) are computed, which fall
within the range of real values specified by the 'lower' and 'upper' parameters.

© 2000-2025, MetaQuotes Ltd.


1559 Matrix and Vector Methods

W ith the BLASRANGE_I value, only those eigenvalues (and their vectors) are computed, which fall
within the range of integer indices specified by the 'lower' and 'upper' parameters. For example, with
lower=0 and upper=2, only the first three eigenvalues are computed.
The input can be a symmetric (Hermitian), upper triangular or lower triangular matrix. Triangular
matrices are assumed to be symmetric (Hermitian conjugated).

ENUM_EIG_VALUES

An enumeration defining the need to compute eigenvectors.

ID Description

EIGVAL UES_V Eigenvectors and eigenvalues are calculated.


EIGVAL UES_N Only eigenvalues are computed, without vectors.

ENUM_BLAS_RANGE

An enumeration defining how right singular vectors should be computed.

ID Description

BL ASRANGE_A All singular or eigenvalues will be found.


BL ASRANGE_V All singular or eigenvalues in the half-open interval (VL,VU] will
be found.
BL ASRANGE_I The IL-th through IU-th singular or eigenvalues will be found.

© 2000-2025, MetaQuotes Ltd.


1560 Matrix and Vector Methods

EigenSymmetricBisect
Compute eigenvalues and eigenvectors of a symmetric or Hermitian (complex conjugated) matrix
using the bisection algorithm (lapack functions SYEVX, HEEVX).
Computing for type matrix<double>
bool matrix::EigenSymmetricBisect(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
ENUM_BLAS_RANGE range, // subset of eigenvalues to compute
double lower, // lower bound of the subset
double upper, // Upper bound of the subset
double abstol, // absolute error tolerance
vector& eigen_values, // vector of computed eigenvectors
matrix& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<float>


bool matrixf::EigenSymmetricBisect(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
ENUM_BLAS_RANGE range, // subset of eigenvalues to compute
float lower, // lower bound of the subset
float upper, // upper bound of the subset
float abstol, // absolute error tolerance
vectorf& eigen_values, // vector of computed eigenvectors
matrixf& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<complex>


bool matrixc::EigenSymmetricBisect(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
ENUM_BLAS_RANGE range, // subset of eigenvalues to compute
double lower, // lower bound of the subset
double upper, // Upper bound of the subset
double abstol, // absolute error tolerance
vector& eigen_values, // vector of computed eigenvectors
matrixc& eigen_vectors // matrix of computed eigenvectors
);

Computing for type matrix<complexf>


bool matrixcf::EigenSymmetricBisect(
ENUM_EIG_VALUES jobv, // compute eigenvectors or not
ENUM_BLAS_RANGE range, // subset of eigenvalues to compute
float lower, // lower bound of the subset
float upper, // Upper bound of the subset
float abstol, // absolute error tolerance
vectorf& eigen_values, // vector of computed eigenvectors

© 2000-2025, MetaQuotes Ltd.


1561 Matrix and Vector Methods

matrixcf& eigen_vectors // matrix of computed eigenvectors


);

Parameters
jobv
[in] ENUM _EIG_VAL UES enumeration value which determines the method for computing
eigenvectors.
range
[in] ENUM _BL AS_RANGE enumeration value that defines a subset of computable eigenvalues and
vectors.
lower
[in]The lower bound of eigenvalues subset; it is specified depending on the value of the 'range'
parameter.
upper
[in]The upper bound of eigenvalues subset; it is specified depending on the value of the 'range'
parameter.
abstol
[in] Absolute error tolerance.
The absolute error tolerance to which each eigenvalue/eigenvector is required.
If jobv = 'V', the eigenvalues and eigenvectors output have residual norms bounded by abstol,
and the dot products between different eigenvectors are bounded by abstol.
If abstol < n *eps *|T|, then n *eps *|T| is used instead, where eps is the machine precision,
and |T| is the 1-norm of the matrix T. The eigenvalues are computed to an accuracy of eps *|
T| irrespective of abstol.
If high relative precision is important, 'abstol' should be set to a safe minimum value X such
that 1.0/X does not overflow.
eigen_values
[out] Vector of eigenvalues.
V
[out] Matrix of eigenvectors.

Return Value

R eturn true if successful, otherwise false in case of an error.


Note

Computation depends on the values of the jobv and range parameters.


W hen BL ASRANGE_A is set, all eigenvalues are computed, and the lower and upper parameters are
ignored.
W ith the BLASRANGE_V value, only those eigenvalues (and their vectors) are computed, which fall
within the range of real values specified by the 'lower' and 'upper' parameters.

© 2000-2025, MetaQuotes Ltd.


1562 Matrix and Vector Methods

W ith the BLASRANGE_I value, only those eigenvalues (and their vectors) are computed, which fall
within the range of integer indices specified by the 'lower' and 'upper' parameters. For example, with
lower=0 and upper=2, only the first three eigenvalues are computed.
The input can be a symmetric (Hermitian), upper triangular or lower triangular matrix. Triangular
matrices are assumed to be symmetric (Hermitian conjugated).

ENUM_EIG_VALUES

An enumeration defining the need to compute eigenvectors.

ID Description

EIGVAL UES_V Eigenvectors and eigenvalues are calculated.


EIGVAL UES_N Only eigenvalues are computed, without vectors.

ENUM_BLAS_RANGE

An enumeration defining how right singular vectors should be computed.

ID Description

BL ASRANGE_A All singular or eigenvalues will be found.


BL ASRANGE_V All singular or eigenvalues in the half-open interval (VL,VU] will
be found.
BL ASRANGE_I The IL-th through IU-th singular or eigenvalues will be found.

© 2000-2025, MetaQuotes Ltd.


1563 Matrix and Vector Methods

Singular Spectrum Analysis


The section contains functions for decomposing a matrix into three components : orthogonal matrices
and a diagonal matrix of singular values. SVD is applied to solve various linear algebra problems such
as data dimensionality reduction, image compression, solving systems of equations, as well as data
analysis and optimization. The main functions allow calculating singular values and vectors,
reconstruct matrices, as well as approximate them with reduced rank accuracy.

Function Action

S ingularS pectrumAnalysis S pectrum A method function for calculating the


relative contributions of spectral
components based on their eigenvalues.
S ingularS pectrumAnalysis Forecast A method function for calculating
reconstructed and predicted data using
spectral components of the input time
series.
S ingularS pectrumAnalysis R econstructComponents A method function for calculating
reconstructed components of the input
time series and their contributions.
S ingularS pectrumAnalysis R econstructS eries A method function for calculating the
reconstructed time series using the first
component_count components.

© 2000-2025, MetaQuotes Ltd.


1564 Matrix and Vector Methods

SingularSpectrumAnalysisSpectrum
A method function for calculating the relative contributions of spectral components based on their
eigenvalues.
Calculations for vector <double> type
bool vector::SingularSpectrumAnalysisSpectrum(
ulong window_length, // window size for constructing the trajectory matrix
vector& spectrum // vector of component contributions to the input series (SSA spectr
);

Calculations for vector <complex> type


bool vector::SingularSpectrumAnalysisSpectrum(
ulong window_length, // window size for constructing the trajectory matrix
vectorс& spectrum // vector of component contributions to the input series (SSA spectr
);

Parameters
window_length
[in] W indow size forconstructing the trajectory matrix, the number of components the input time
series should be decomposed into.
spectrum
[out] Vector of component contributions to the input series - eigenvalues of the covariance matrix
of the input time series.

Return Value

The function returns 'true' on success or 'false' if an error occurs.


Note

The window_length parameter value should be less than the size of the input time series. To
construct a full-fledged trajectory matrix, the optimal size is considered to be approximately equal
to half the size of the input time series.

© 2000-2025, MetaQuotes Ltd.


1565 Matrix and Vector Methods

SingularSpectrumAnalysisForecast
A method function for calculating reconstructed and predicted data using spectral components of the
input time series.
Calculations for vector <double> type
bool vector::SingularSpectrumAnalysisForecast(
ulong window_length, // window size for constructing the trajectory matrix
ulong component_count, // number of components used for forecasting
ulong forecast_horizon, // number of points to forecast
vector& forecast // vector consisting of reconstructed and predicted values
);

Calculations for vector <complex> type


bool vector::SingularSpectrumAnalysisForecast(
ulong window_length, // window size for constructing the trajectory matrix
ulong component_count, // number of components used for forecasting
ulong forecast_horizon, // number of points to forecast
vectorс& forecast // vector consisting of reconstructed and predicted values
);

Parameters
window_length
[in] W indow size forconstructing the trajectory matrix, the number of components the input time
series should be decomposed into.
component_count
[in] Number of components used for forecasting.
forecast_horizon
[in] Number of points to forecast.
forecast
[out] Combining points reconstructed by component_count plus forecast_horizon points predicted
using the first component_count components. Thus, the forecast vector has the size of
(T+forecast_horizon), where T is the input series length.

Return Value

The function returns 'true' on success or 'false' if an error occurs.


Note

The window_length parameter value should be less than the size of the input time series. To
construct a full-fledged trajectory matrix, the optimal size is considered to be approximately equal
to half the size of the input time series.

© 2000-2025, MetaQuotes Ltd.


1566 Matrix and Vector Methods

SingularSpectrumAnalysisReconstructComponents
A method function for calculating reconstructed components of the input time series and their
contributions.
Calculations for vector <double> and matrix<double> types
bool vector::SingularSpectrumAnalysisReconstructComponents(
ulong window_length, // window size for constructing the trajectory matrix
matrix& components, // matrix of reconstructed components
vector& contributions // vector of component contributions to the input series
);

Calculations for vector <complex> and matrix<complex> types


bool vector::SingularSpectrumAnalysisReconstructComponents(
ulong window_length, // window size for constructing the trajectory matrix
matrixc& components, // matrix of reconstructed components
vectorc& contributions // vector of component contributions to the input series
);

Parameters
window_length
[in] W indow size forconstructing the trajectory matrix, the number of components the input time
series should be decomposed into.
components
[out] A matrix of reconstructed components, where each column describes a separate component.
contributions
[out] Vector of component contributions to the input series (eigenvalues of the covariance matrix
of the input time series).

Return Value

The function returns 'true' on success or 'false' if an error occurs.


Note

The window_length parameter value should be less than the size of the input time series. To
construct a full-fledged trajectory matrix, the optimal size is considered to be approximately equal
to half the size of the input time series.

© 2000-2025, MetaQuotes Ltd.


1567 Matrix and Vector Methods

SingularSpectrumAnalysisReconstructSeries
A method function for calculating the reconstructed time series using the first component_count

components.
Calculations for vector <double> type
bool vector::SingularSpectrumAnalysisReconstructSeries(
ulong window_length, // window size for constructing the trajectory matrix
ulong component_count, // number of components used for reconstruction
vector& reconstructed // reconstructed time series
);

Calculations for vector <complex> type


bool vector::SingularSpectrumAnalysisReconstructSeries(
ulong window_length, // window size for constructing the trajectory matrix
ulong component_count, // number of components used for reconstruction
vectorс& reconstructed // reconstructed time series
);

Parameters
window_length
[in] W indow size forconstructing the trajectory matrix, the number of components the input time
series should be decomposed into.
component_count
[out] Number of components used for time series reconstruction.
reconstructed
[out] Vector containing the reconstructed output series.

Return Value

The function returns 'true' on success or 'false' if an error occurs.


Note

The window_length parameter value should be less than the size of the input time series. To
construct a full-fledged trajectory matrix, the optimal size is considered to be approximately equal
to half the size of the input time series.

© 2000-2025, MetaQuotes Ltd.


1568 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

CharToS tring Converting a symbol code into a one-character string


DoubleToS tring Converting a numeric value to a text line with a specified accuracy
EnumToS tring Converting an enumeration value of any type to string
NormalizeDouble R ounding of a floating point number to a specified accuracy
S tringToDouble Converting a string containing a symbol representation of number
into number of double type
S tringToInteger Converting a string containing a symbol representation of number
into number of long type
S tringToTime Converting a string containing time or date in " yyyy.mm.dd
[hh:mi]" format into datetime type

TimeToS tring Converting a value containing time in seconds elapsed since


01.01.1970 into a string of " yyyy.mm.dd hh:mi" format

IntegerToS tring Converting int into a string of preset length


S hortToS tring Converting symbol code (unicode) into one-symbol string
S hortArrayToS tring Copying array part into a string
S tringToS hortArray S ymbol-wise copying a string to a selected part of array of ushort
type
CharArrayToS tring Converting symbol code (ansi) into one-symbol array
S tringToCharArray S ymbol-wise copying a string converted from Unicode to ANS I, to a
selected place of array of uchar type
CharArrayToS truct Copy uchar type array to POD structure
S tructToCharArray Copy POD structure to uchar type array
ColorToARGB Converting color type to uint type to receive ARGB representation
of the color.
ColorToS tring Converting color value into string as "R,G,B"
S tringToColor Converting "R ,G,B" string or string with color name into color type
value
S tring Format Converting number into string according to preset format

© 2000-2025, MetaQuotes Ltd.


1569 Conversion Functions

See also
Use of a Codepage

© 2000-2025, MetaQuotes Ltd.


1570 Conversion Functions

CharToString
Converting a symbol code into a one-character string.
string CharToString(
uchar char_code // numeric code of symbol
);

Parameters
char_code
[in] Code of ANS I symbol.

Return Value

S tring with a ANS I symbol.

Example:

string ExtStrArray[224];

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- in the loop from the symbol code 32 (space) to 255(UCHAR_MAX),
//--- fill the array with symbol codes converted to a string in accordance with the current code pa
for(int i=32; i<=UCHAR_MAX; i++)
ExtStrArray[i-32]=CharToString((uchar)i);

//--- print the header and the symbol table in the journal
Print("Table of symbols:");
ArrayPrint(ExtStrArray,_Digits," | ");
/*
result:
Table of symbols:
[ 0] " " | "!" | """ | "#" | "$" | "%" | "&" | "'" | "(" | ")" | "*" | "+" | "," | "-" | "." |
[ 25] "9" | ":" | ";" | "<" | "=" | ">" | "?" | "@" | "A" | "B" | "C" | "D" | "E" | "F" | "G" |
[ 50] "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" | "[" | "\" | "]" | "^" | "_" | "`" |
[ 75] "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" |
[100] "„" | "…" | "†" | "‡" | "€" | "‰" | "Љ" | "‹" | "Њ" | "Ќ" | "Ћ" | "Џ" | "ђ" | "‘" | "’" |
[125] "ќ" | "ћ" | "џ" | " " | "Ў" | "ў" | "Ј" | "¤" | "Ґ" | "¦" | "§" | "Ё" | "©" | "Є" | "«" |
[150] "¶" | "·" | "ё" | "№" | "є" | "»" | "ј" | "Ѕ" | "ѕ" | "ї" | "А" | "Б" | "В" | "Г" | "Д" |
[175] "П" | "Р" | "С" | "Т" | "У" | "Ф" | "Х" | "Ц" | "Ч" | "Ш" | "Щ" | "Ъ" | "Ы" | "Ь" | "Э" |
[200] "и" | "й" | "к" | "л" | "м" | "н" | "о" | "п" | "р" | "с" | "т" | "у" | "ф" | "х" | "ц" |
*/
}

See also

© 2000-2025, MetaQuotes Ltd.


1571 Conversion Functions

S tringToCharArray, S hortToS tring, S tring GetCharacter

© 2000-2025, MetaQuotes Ltd.


1572 Conversion Functions

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 symbols
uint codepage=CP_ACP // code page
);

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.
codepage=CP_ACP
[in]The value of the code page. There is a number of built-in constants for the most used code
pages.

Return Value

S tring.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- create an array with symbol codes
uchar array[]= { 84, 104, 105, 115, 32, 105, 115, 32, 97, 32,
116, 101, 115, 116, 32, 111, 102, 32, 116, 104,
101, 32, 67, 104, 97, 114, 65, 114, 114, 97,
121, 84, 111, 83, 116, 114, 105, 110, 103, 40,
41, 32, 102, 117, 110, 99, 116, 105, 111, 110
};
//--- print an array of codes converted into a string in the journal
Print(CharArrayToString(array));

//--- create an array with symbol codes and terminal zero


uchar array_z[]= { 84, 104, 105, 115, 32, 105, 115, 32, 97, 32,

© 2000-2025, MetaQuotes Ltd.


1573 Conversion Functions

116, 101, 115, 116, 0, 32, 111, 102, 32, 116,


104, 101, 32, 67, 104, 97, 114, 65, 114, 114,
97, 121, 84, 111, 83, 116, 114, 105, 110, 103,
40, 41, 32, 102, 117, 110, 99, 116, 105, 111, 110
};
//--- print the second array of codes with terminal zero in the journal
PrintFormat("%s ...", CharArrayToString(array_z));

/*
result:
This is a test of the CharArrayToString() function
This is a test ...
*/
}

See also
S tringToCharArray, S hortArrayToS tring, Use of a Codepage

© 2000-2025, MetaQuotes Ltd.


1574 Conversion Functions

CharArrayToStruct
Copy uchar type array to POD structure.
bool CharArrayToStruct(
void& struct_object, // structure
const uchar& char_array[], // array
uint start_pos=0 // starting position in the array
);

Parameters
struct_object
[in] R eference to any type of POD structure (containing only simple data types).
char_array[]
[in] uchar type array.
start_pos=0
[in] Position in the array, data copying starts from.

Return Value

R eturns true if successful, otherwise false.

Example:

#define DATA_TOTAL 4

MqlRates ExtDataRates[DATA_TOTAL];
uchar ExtCharArray[];

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- copy the data of the last four bars into the uchar array
ResetLastError();
for(int i=0; i<DATA_TOTAL; i++)
{
if(!CopyRatesToCharArray(i, ExtCharArray))
return;
}

//--- copy all available data into the MqlRates structure array in a loop by the amount of data fro
for(int i=0; i<DATA_TOTAL; i++)
{
ResetLastError();
if(!CharArrayToStruct(ExtDataRates[i], ExtCharArray, sizeof(MqlRates)*i))

© 2000-2025, MetaQuotes Ltd.


1575 Conversion Functions

{
Print("CharArrayToStruct() failed. Error code: ", GetLastError());
return;
}
//--- upon successful copying of data from the uchar array to the MqlRates structure,
//--- print the data, copied into the structure, to the journal
MqlRatesPrint(ExtDataRates[i]);
}

/*
result:
MqlRates data:
Time = 2024.02.21 09:00;
Open = 1.08116;
High = 1.08141;
Low = 1.08062;
Close = 1.08124;
Tick volume = 5344;
Spread = 1;
Real volume = 0

MqlRates data:
Time = 2024.02.21 08:00;
Open = 1.08149;
High = 1.08153;
Low = 1.08073;
Close = 1.08114;
Tick volume = 3607;
Spread = 2;
Real volume = 0

MqlRates data:
Time = 2024.02.21 07:00;
Open = 1.08143;
High = 1.08165;
Low = 1.08122;
Close = 1.08150;
Tick volume = 2083;
Spread = 0;
Real volume = 0

MqlRates data:
Time = 2024.02.21 06:00;
Open = 1.08178;
High = 1.08190;
Low = 1.08132;
Close = 1.08142;
Tick volume = 1733;
Spread = 0;

© 2000-2025, MetaQuotes Ltd.


1576 Conversion Functions

Real volume = 0
*/
}
//+------------------------------------------------------------------+
//| Copy bar data to the uchar array |
//| by the specified index via the MqlRates structure |
//+------------------------------------------------------------------+
bool CopyRatesToCharArray(const int index, uchar &data_array[])
{
MqlRates rates[1];
uint start=sizeof(MqlRates);

ResetLastError();
if(CopyRates(Symbol(), PERIOD_CURRENT, index, 1, rates)!=1)
{
Print("CopyRates() failed. Error code: ", GetLastError());
return(false);
}
if(!StructToCharArray(rates[0], data_array, start*index))
{
Print("StructToCharArray() failed. Error code: ", GetLastError());
return(false);
}

return(true);
}
//+------------------------------------------------------------------+
//| Print the fields of the MqlRates structure in the journal |
//+------------------------------------------------------------------+
void MqlRatesPrint(MqlRates &rates)
{
//--- create the output string
string text=StringFormat(" Time = %s;\n"
" Open = %.*f;\n"
" High = %.*f;\n"
" Low = %.*f;\n"
" Close = %.*f;\n"
" Tick volume = %I64u;\n"
" Spread = %d;\n"
" Real volume = %I64u",
TimeToString(rates.time),
_Digits, rates.open,
_Digits, rates.high,
_Digits, rates.low,
_Digits, rates.close,
rates.tick_volume,
rates.spread,
rates.real_volume);
//--- print the header and the output string in the journal

© 2000-2025, MetaQuotes Ltd.


1577 Conversion Functions

Print("MqlRates data:\n", text, "\n");


}

See also
S tringToCharArray, S hortArrayToS tring, S tructToCharArray, Use of a Codepage, FileReadS truct,
Unions (union), MathS wap

© 2000-2025, MetaQuotes Ltd.


1578 Conversion Functions

StructToCharArray
Copy POD structure to uchar type array.
bool StructToCharArray(
const void& struct_object, // structure
uchar& char_array[], // array
uint start_pos=0 // starting position in the array
);

Parameters
struct_object
[in] R eference to any type of POD structure (containing only simple data types).
char_array[]
[in] uchar type array.
start_pos=0
[in] Position in the array, starting from which the copied data are added.

Return Value

R eturns true if successful, otherwise false.


Note

W hen copying, the dynamic array automatically expands (ArrayResize) if there is not enough space.
If the array cannot be expanded up to the required value, the function returns an error.

Example:

uchar ExtCharArray[];
MqlRates ExtRates[1];

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- copy the data of one current bar into the MqlRates structure
if(CopyRates(Symbol(), PERIOD_CURRENT, 0, 1, ExtRates)!=1)
{
Print("CopyRates() failed. Error code: ", GetLastError());
return;
}

//--- print the data received in the MqlRates structure in the journal
Print("Data in the structure immediately after receiving it:");
MqlRatesPrint(ExtRates[0]);

© 2000-2025, MetaQuotes Ltd.


1579 Conversion Functions

//--- copy the structure to the uchar type array


ResetLastError();
if(!StructToCharArray(ExtRates[0], ExtCharArray))
{
Print("StructToCharArray() failed. Error code: ", GetLastError());
return;
}

//--- clear the structure


ZeroMemory(ExtRates[0]);
//--- print the data in the structure after clearing
Print("\nData in the structure after ZeroMemory():");
MqlRatesPrint(ExtRates[0]);

//--- now copy the data from the uchar array to the MqlRates structure
if(!CharArrayToStruct(ExtRates[0], ExtCharArray))
{
Print("CharArrayToStruct() failed. Error code: ", GetLastError());
return;
}
//--- print the data in the MqlRates structure after copying it from the uchar array
Print("\nData in the MqlRates structure after copying it from a uchar array:");
MqlRatesPrint(ExtRates[0]);

/*
result:

Data in the structure immediately after receiving it:


MqlRates data:
Time = 2024.02.21 07:00;
Open = 1.08143;
High = 1.08158;
Low = 1.08122;
Close = 1.08137;
Tick volume = 1341;
Spread = 4;
Real volume = 0

Data in the structure after ZeroMemory():


MqlRates data:
Time = 0;
Open = 0.00000;
High = 0.00000;
Low = 0.00000;
Close = 0.00000;
Tick volume = 0;
Spread = 0;
Real volume = 0

© 2000-2025, MetaQuotes Ltd.


1580 Conversion Functions

Data in the MqlRates structure after copying it from a uchar array:


MqlRates data:
Time = 2024.02.21 07:00;
Open = 1.08143;
High = 1.08158;
Low = 1.08122;
Close = 1.08137;
Tick volume = 1341;
Spread = 4;
Real volume = 0
*/
}
//+------------------------------------------------------------------+
//| Print the fields of the MqlRates structure in the journal |
//+------------------------------------------------------------------+
void MqlRatesPrint(MqlRates &rates)
{
//--- create the output string
string text=StringFormat(" Time = %s;\n"
" Open = %.*f;\n"
" High = %.*f;\n"
" Low = %.*f;\n"
" Close = %.*f;\n"
" Tick volume = %I64u;\n"
" Spread = %d;\n"
" Real volume = %I64u",
TimeToString(rates.time),
_Digits, rates.open,
_Digits, rates.high,
_Digits, rates.low,
_Digits, rates.close,
rates.tick_volume,
rates.spread,
rates.real_volume);
//--- print the header and the output string in the journal
Print("MqlRates data:\n", text);
}

See also
S tringToCharArray, S hortArrayToS tring,CharArrayToS truct, Use of a Codepage, FileW riteS truct,
Unions (union), MathS wap

© 2000-2025, MetaQuotes Ltd.


1581 Conversion Functions

ColorToARGB
The function converts color type into uint type to get ARGB representation of the color. ARGB color
format is used to generate a graphical resource, text display, as well as for CCanvas standard library
class.
uint ColorToARGB(
color clr, // converted color in color format
uchar alpha=255 // alpha channel managing color transparency
);

Parameters
clr
[in] Color value in color type variable.
alpha
[in] The value of the alpha channel used to receive the color in ARGB format. The value may be
set from 0 (a color of a foreground pixel does not change the display of an underlying one) up to
255 (a color of an underlying pixel is completely replaced by the foreground pixel's one). Color
transparency in percentage terms is calculated as (1-alpha/255)*100%. In other words, the lesser
value of the alpha channel leads to more transparent color.

Return Value

Presenting the color in ARGB format where Alfa, Red, Green, Blue (alpha channel, red, green, blue)
values are set in series in four uint type bytes.
Note

RGB is a basic and commonly used format for pixel color description on a screen in computer
graphics. Names of basic colors are used to set red, green and blue color components. Each
component is described by one byte specifying the color saturation in the range of 0 to 255 (0x00 to
0XFF in hexadecimal format). S ince the white color contains all colors, it is described as 0x FFFFFF,
that is, each one of three components is presented by the maximum value of 0xFF.
H owever, some tas ks require to specify the color transparency to describe the look of an image in
case it is covered by the color with some degree of transparency. The concept of alpha channel is
introduced for such cases. It is implemented as an additional component of RGB format. ARGB
format structure is shown below.

ARGB values are typically expressed using hexadecimal format with each pair of digits representing
the values of Alpha, Red, Green and Blue channels, respectively. For example, 80FFFF00 color
represents 50.2% opaque yellow. Initially, 0x80 sets 50.2% alpha value, as it is 50.2% of 0xFF value.
Then, the first FF pair defines the highest value of the red component; the next FF pair is like the
previous but for the green component; the final 00 pair represents the lowest value the blue
component can have (absence of blue). Combination of green and red colors yields yellow one. If the

© 2000-2025, MetaQuotes Ltd.


1582 Conversion Functions

alpha channel is not used, the entry can be reduced down to 6 RRGGBB digits, this is why the alpha
channel values are stored in the top bits of uint integer type.
Depending on the context, hexadecimal digits can be written with '0x' or '#' prefix, for example,
80FFFF00, 0x 80FFFF00 or #80FFFF00.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set transparency
uchar alpha=0x55; // 0x55 means 55/255=21.6 % of transparency
//--- derive conversion to ARGB for clrBlue color
PrintFormat("0x%.8X - clrBlue",clrBlue);
PrintFormat("0x%.8X - clrBlue ARGB with alpha=0x55 (transparency 21.6%%)",ColorToARGB(clrBlue,al
//--- derive conversion to ARGB for clrGreen color
PrintFormat("0x%.8X - clrGreen",clrGreen);
PrintFormat("0x%.8X - clrGreen ARGB with alpha=0x55 (transparency 21.6%%)",ColorToARGB(clrGreen,
//--- derive conversion to ARGB for clrRed color
PrintFormat("0x%.8X - clrRed",clrRed);
PrintFormat("0x%.8X - clrRed ARGB with alpha=0x55 (transparency 21.6%%)",ColorToARGB(clrRed,alph
}

See also
R esources, R esourceCreate(), TextOut(), color type, char, short, int and long types

© 2000-2025, MetaQuotes Ltd.


1583 Conversion Functions

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] R eturn color name if it is identical to one of predefined color constants.

Return Value

S tringpresentation 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);

See also
S tringToColor, ColorToARGB

© 2000-2025, MetaQuotes Ltd.


1584 Conversion Functions

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 number of digits after the point will be obtained. If the digits value is
in the range between -1 and -16, a string representation of a number in the scientific format with
the specified number of digits after the decimal point will be obtained. In all other cases the string
value will contain 8 digits after the decimal point.

Return Value

S tring 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, S tringToDouble

© 2000-2025, MetaQuotes Ltd.


1585 Conversion Functions

EnumToString
Converting an enumeration value of any type to a text form.
string EnumToString(
any_enum value // any type enumeration value
);

Parameters
value
[in] Any type enumeration value.

Return Value

A string with a text representation of the enumeration. To get the error message call the
GetLastError() function.
Note

The function can set the following error values in the _LastError variable:
· ERR_I NT ERNAL _ERR OR – error of the execution environment
· ERR_NOT _ENOUGH_M EMORY – not enough memory to complete the operation
· ERR_I NVALI D_PARAM ET ER – can't allow the name of the enumeration value

Example:

enum interval // enumeration of named constants


{
month=1, // one-month interval
two_months, // two months
quarter, // three months - a quarter
halfyear=6, // half a year
year=12, // a year - 12 months
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set the time interval equal to one month
interval period=month;
Print(EnumToString(period)+"="+IntegerToString(period));

//--- set the time interval equal to a quarter (three months)


period=quarter;
Print(EnumToString(period)+"="+IntegerToString(period));

//--- set the time interval equal to one year (12 months)
period=year;

© 2000-2025, MetaQuotes Ltd.


1586 Conversion Functions

Print(EnumToString(period)+"="+IntegerToString(period));

//--- check how the order type is shown


ENUM_ORDER_TYPE type=ORDER_TYPE_BUY;
Print(EnumToString(type)+"="+IntegerToString(type));

//--- check how incorrect values are shown


type=WRONG_VALUE;
Print(EnumToString(type)+"="+IntegerToString(type));

// Result:
// month=1
// quarter=3
// year=12
// ORDER_TYPE_BUY=0
// ENUM_ORDER_TYPE::-1=-1
}

See also
Enumerations, Input variables

© 2000-2025, MetaQuotes Ltd.


1587 Conversion Functions

IntegerToString
This function converts 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] S tring 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.

Return Value

S tring.

Example:

#define DATA_TOTAL 1001

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- display rows with the index multiple of 100 in the loop by DATA_TOTAL
//--- the string displays the index value in the four-character format
//--- if the string length is less than 4 characters, then the value of the loop index
//--- in the string is preceded by leading zeros
for(int i=0; i<DATA_TOTAL; i++)
{
if(i%100==0)
Print("Converted index value: ",IntegerToString(i,4,'0'));
}
/*
result:
Converted index value: 0000
Converted index value: 0100
Converted index value: 0200

© 2000-2025, MetaQuotes Ltd.


1588 Conversion Functions

Converted index value: 0300


Converted index value: 0400
Converted index value: 0500
Converted index value: 0600
Converted index value: 0700
Converted index value: 0800
Converted index value: 0900
Converted index value: 1000
*/
}

See also
S tringToInteger

© 2000-2025, MetaQuotes Ltd.


1589 Conversion Functions

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] S ymbol 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.

Return Value

S tring.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- print 18 characters in a loop, starting with the character with the Unicode number of U+23E9
for(int i=0; i<18; i++)
{
ushort code=0x23E9+(ushort)i;
PrintFormat("Unicode number U+%hX: %s",code,ShortToString(code));
}
/*
result:
Unicode number U+23E9: ⏩
Unicode number U+23EA: ⏪
Unicode number U+23EB: ⏫
Unicode number U+23EC: ⏬
Unicode number U+23ED: ⏭
Unicode number U+23EE: ⏮
Unicode number U+23EF: ⏯
Unicode number U+23F0: ⏰
Unicode number U+23F1: ⏱
Unicode number U+23F2: ⏲
Unicode number U+23F3: ⏳
Unicode number U+23F4: ⏴
Unicode number U+23F5: ⏵
Unicode number U+23F6: ⏶
Unicode number U+23F7: ⏷
Unicode number U+23F8: ⏸

© 2000-2025, MetaQuotes Ltd.


1590 Conversion Functions

Unicode number U+23F9: ⏹


Unicode number U+23FA: ⏺
*/
}

See also
S tringToCharArray, CharToS tring, S tringGetCharacter

© 2000-2025, MetaQuotes Ltd.


1591 Conversion Functions

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.

Return Value

S tring.

Example:

#define ROW_SIZE 16

ushort ExtShortArray[]={0x2190,0x2191,0x2192,0x2193,0x2194,0x2195,0x2196,0x2197,0x2198,0x2199,0x219
0x21A0,0x21A1,0x21A2,0x21A3,0x21A4,0x21A5,0x21A6,0x21A7,0x21A8,0x21A9,0x21A
0x21B0,0x21B1,0x21B2,0x21B3,0x21B4,0x21B5,0x21B6,0x21B7,0x21B8,0x21B9,0x21B
0x21C0,0x21C1,0x21C2,0x21C3,0x21C4,0x21C5,0x21C6,0x21C7,0x21C8,0x21C9,0x21C
0x21D0,0x21D1,0x21D2,0x21D3,0x21D4,0x21D5,0x21D6,0x21D7,0x21D8,0x21D9,0x21D
0x21E0,0x21E1,0x21E2,0x21E3,0x21E4,0x21E5,0x21E6,0x21E7,0x21E8,0x21E9,0x21E
0x21F0,0x21F1,0x21F2,0x21F3,0x21F4,0x21F5,0x21F6,0x21F7,0x21F8,0x21F9,0x21F

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- calculate the number of strings in the symbol table of 7x16
int total=(int)ExtShortArray.Size()/ROW_SIZE;
//--- in a loop by the table rows, display 7 sets of arrows, 16 pieces in each row in Unicode chara
for(int i=0; i<total; i++)
{
int row=i*ROW_SIZE;
PrintFormat("Arrow set %u: %s",i+1,ShortArrayToString(ExtShortArray,row,ROW_SIZE));

© 2000-2025, MetaQuotes Ltd.


1592 Conversion Functions

}
/*
result:
Arrow set 1: ←↑→↓↔↕↖ ↗ ↘ ↙ ↚ ↛ ↜ ↝ ↞ ↟
Arrow set 2: ↠↡↢↣↤↥↦↧↨↩↪↫↬↭↮↯
Arrow set 3: ↰↱↲↳↴↵↶↷↸↹↺↻↼↽↾↿
Arrow set 4: ⇀⇁⇂⇃⇄⇅⇆⇇⇈⇉⇊⇋⇌⇍⇎⇏
Arrow set 5: ⇐ ⇑⇒ ⇓⇔ ⇕⇖ ⇗ ⇘ ⇙ ⇚ ⇛ ⇜ ⇝ ⇞⇟
Arrow set 6: ⇠⇡⇢⇣⇤⇥⇦⇧⇨⇩⇪⇫⇬⇭⇮⇯
Arrow set 7: ⇰⇱⇲⇳⇴⇵⇶⇷⇸⇹⇺⇻⇼⇽⇾⇿
*/
}

See also
S tringToS hortArray, CharArrayToS tring, Use of a Codepage

© 2000-2025, MetaQuotes Ltd.


1593 Conversion Functions

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:
TIM E_DATE gets result as " yyyy.mm.dd" ,
TIM E_MINUTES gets result as " hh:mi" ,
TIM E_SECONDS gets results as " hh:mi:ss " .

Return Value

S tring.

Example:

datetime ExtBarTimeOpen;

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- set the timer to one second
EventSetTimer(1);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Comment("");
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,

© 2000-2025, MetaQuotes Ltd.


1594 Conversion Functions

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 current bar opening time
ExtBarTimeOpen=time[rates_total-1];
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Timer function |
//+------------------------------------------------------------------+
void OnTimer()
{
//--- set the previous bar opening time
static datetime bar_open_time=ExtBarTimeOpen;
//--- count the number of seconds passed since the bar opened
static int seconds=int(TimeCurrent()-ExtBarTimeOpen);
//--- if the previous opening time is not equal to the current one, then this is a new bar
//--- write the new opening time as the previous one and set the seconds to zero
if(bar_open_time!=ExtBarTimeOpen)
{
bar_open_time=ExtBarTimeOpen;
seconds=0;
}
//--- increase and adjust the number of seconds passed since the bar opened
seconds++;
if(seconds>PeriodSeconds(PERIOD_CURRENT))
seconds=0;
//--- bar opening time as yyyy.mm.dd hh:mi
string bar_time_open=TimeToString(ExtBarTimeOpen);
//--- current time as yyyy.mm.dd hh:mi:ss
string time_current=TimeToString(TimeCurrent(),TIME_DATE|TIME_MINUTES|TIME_SECONDS);
//--- number of seconds left until a new bar opens
int sec_left=PeriodSeconds(PERIOD_CURRENT)-seconds;
//--- amount of time remaining until the current bar closes as hh:mm:ss
string time_left=TimeToString(sec_left,TIME_MINUTES|TIME_SECONDS);
//--- create the output string
string txt=StringFormat("Opening time of the current bar: %s\n"+
"Time Current: %s\n"+
"Seconds have passed since the bar opened: %d\n"+
"Approximately seconds left before bar closes: %d\n"+
"Time remaining until bar closes: %s",bar_time_open,time_current,seconds

© 2000-2025, MetaQuotes Ltd.


1595 Conversion Functions

//--- display the bar open time and the current time,
//--- the number of seconds passed since the current bar opened and remaining until it closes and
//--- the time remaining until the current bar closes in the comment
Comment(txt);
/*
result on M1:
Opening time of the current bar: 2024.02.22 18:06
Time Current: 2024.02.22 18:06:24
Seconds have passed since the bar opened: 25
Approximately seconds left before bar closes: 35
Time remaining until bar closes: 00:00:35

result on M5:
Opening time of the current bar: 2024.02.22 18:05
Time Current: 2024.02.22 18:07:28
Seconds have passed since the bar opened: 149
Approximately seconds left before bar closes: 151
Time remaining until bar closes: 00:02:31

result on H1:
Opening time of the current bar: 2024.02.22 18:00
Time Current: 2024.02.22 18:08:13
Seconds have passed since the bar opened: 494
Approximately seconds left before bar closes: 3106
Time remaining until bar closes: 00:51:46

result on D1:
Opening time of the current bar: 2024.02.22 00:00
Time Current: 2024.02.22 18:11:01
Seconds have passed since the bar opened: 65462
Approximately seconds left before bar closes: 20938
Time remaining until bar closes: 05:48:58
*/
}

See also
S tringToTime, TimeToS truct

© 2000-2025, MetaQuotes Ltd.


1596 Conversion Functions

NormalizeDouble
R ounding 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).

Return Value

Value of double type with preset accuracy.


Note

Calculated values of S topLoss, TakeProfit, and values of open prices for pending orders must be
normalized with the accuracy, the value of which can be obtained by Digits().
Please note that when output to Journal using the Print() function, a normalized number may contain
a greater number of decimal places than you expect. For example, for:
double a=76.671; // A normalized number with three decimal places
Print("Print(76.671)=",a); // Output as is
Print("DoubleToString(a,8)=",DoubleToString(a,8)); // Output with a preset accuracy

you will have the following in the terminal:


DoubleToS tring(a,8)=76.67100000

Print(76.671)=76.67100000000001

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

© 2000-2025, MetaQuotes Ltd.


1597 Conversion Functions

/*
Result:
pi= 3.1415926535897931
NormalizeDouble(pi,3)= 3.1419999999999999
NormalizeDouble(pi,8)= 3.1415926499999998
NormalizeDouble(pi,0)= 3.0000000000000000
*/

See also
DoubleToS tring, R eal types (double, float), Typecasting

© 2000-2025, MetaQuotes Ltd.


1598 Conversion Functions

StringToCharArray
S ymbol-wise copies a string converted from Unicode to ANS I, to a selected place of array of uchar
type. It returns the number of copied elements.
int StringToCharArray(
string text_string, // source string
uchar& array[], // array
int start=0, // starting position in the array
int count=-1 // number of symbols
uint codepage=CP_ACP // code page
);

Parameters
text_string
[in] S tring 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. Terminal 0 will also be copied to the
recipient array, in this case the size of a dynamic array can be increased if necessary to the size of
the string. If the size of the dynamic array exceeds the length of the string, the size of the array
will not be reduced.
codepage=CP_ACP
[in] The value of the code page. For the most-used code pages provide appropriate constants.

Return Value

Number of copied elements.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- string to convert
string text = "This is a test of the StringToCharArray() function";

//--- convert the input string into a uchar array in accordance with the set code page
uchar char_array[];

© 2000-2025, MetaQuotes Ltd.


1599 Conversion Functions

int copied=StringToCharArray(text, char_array);


PrintFormat("String length: %u\nNumber of characters copied (with terminal 0): %d\nArray of char
StringLen(text), copied, text);
//--- print the resulting array to the journal
ArrayPrint(char_array, 0, " | ");
/*
result:
String length: 50
Number of characters copied (with terminal 0): 51
Array of characters for the string 'This is a test of the StringToCharArray() function':
[ 0] 84 | 104 | 105 | 115 | 32 | 105 | 115 | 32 | 97 | 32 | 116 | 101 | 115 | 116 | 32 | 1
[17] 32 | 116 | 104 | 101 | 32 | 83 | 116 | 114 | 105 | 110 | 103 | 84 | 111 | 67 | 104 |
[34] 65 | 114 | 114 | 97 | 121 | 40 | 41 | 32 | 102 | 117 | 110 | 99 | 116 | 105 | 111 | 1
*/
}

See also
CharArrayToS tring, S tringToS hortArray, Use of a Codepage

© 2000-2025, MetaQuotes Ltd.


1600 Conversion Functions

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] S tring representation of a color of "R,G,B" type or name of one of predefined W eb-colors.

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

See also
ColorToS tring, ColorToARGB

© 2000-2025, MetaQuotes Ltd.


1601 Conversion Functions

StringToDouble
The function converts string containing a symbol representation of number into number of double
type.
double StringToDouble(
string value // string
);

Parameters
value
[in] S tring containing a symbol representation of a number.

Return Value

Value of double type.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- string to convert
string str = "12345.54321";
//--- convert the input string as a real number into a double type variable
double converted=StringToDouble(str);
//--- display the resulting number accurate to 8 decimal places in the journal
PrintFormat("The string '%s' is converted to the real number %.8f", str, converted);
/*
result:
The string '12345.54321' is converted to the real number 12345.54321000
*/
}

See also
NormalizeDouble, R eal types (double, float), Typecasting

© 2000-2025, MetaQuotes Ltd.


1602 Conversion Functions

StringToInteger
The function converts string containing a symbol representation of number into number of long
(integer) type.
long StringToInteger(
string value // string
);

Parameters
value
[in] S tring containing a number.

Return Value

Value of long type.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- string to convert
string str = "12345.54321";
//--- convert the input string as a number into a long type variable
long converted=StringToInteger(str);
//--- display the obtained number in the journal with the fractional part cut off
PrintFormat("The string '%s' is converted to the integer number %I64d", str, converted);
/*
result:
The string '12345.54321' is converted to the integer number 12345
*/
}

See also
IntegerToS tring, Real types (double, float), Typecasting

© 2000-2025, MetaQuotes Ltd.


1603 Conversion Functions

StringToShortArray
The function symbol-wise copies a string into a specified place of an array of ushort type. It returns
the number of copied elements.
int 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] S tring 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.Terminal 0 will also be copied to the
recipient array, in this case the size of a dynamic array can be increased if necessary to the size of
the string. If the size of the dynamic array exceeds the length of the string, the size of the array
will not be reduced.

Return Value

Number of copied elements.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- string with chars to convert
string text = "Chars: ❤♫☎✈✣ ☏ ☀✉☆ ☁♕ ♠®✧ ❆ ♣ ";
ushort short_array[];
//--- find the position of the ":" character in the input string and extract the substring starting
int pos=StringFind(text, ":");
string str=(pos<0 ? text : StringSubstr(text, pos+1));
//--- remove spaces, carriage movement and tabulation characters from the left and right of the res
StringTrimLeft(str);
StringTrimRight(str);

© 2000-2025, MetaQuotes Ltd.


1604 Conversion Functions

//--- copy the resulting string into the ushort array and print the resulting array to the journal
int copied=StringToShortArray(str, short_array);
PrintFormat("String of characters length: %u\n"
"Number of characters copied (with terminal 0): %d\n"
"Array of chars for the string '%s':",
StringLen(str), copied, str);
ArrayPrint(short_array, 0, " | ");
/*
result:
String of characters length: 16
Number of characters copied (with terminal 0): 17
Array of chars for the string '❤♫☎✈✣ ☏ ☀✉☆ ☁♕ ♠®✧ ❆ ♣':
10084 | 9835 | 9742 | 9992 | 10019 | 9743 | 9728 | 9993 | 9734 | 9729 | 9813 | 9824 |
*/
}

See also
S hortArrayToS tring, S tringToCharArray, Use of a Codepage

© 2000-2025, MetaQuotes Ltd.


1605 Conversion Functions

StringToTime
Transforms the string containing time and/or date in the " yyyy.mm.dd [hh:mi]" format into the
datetime type number.
datetime StringToTime(
const string time_string // date string
);

Parameters
time_string
[in] S tring in one of the specified formats :
· " yyyy.mm.dd [hh:mi]"

· " yyyy.mm.dd [hh:mi:ss ]"

· " yyyymmdd [hh:mi:ss ]"

· " yyyymmdd [hhmiss ]"

· " yyyy/mm/dd [hh:mi:ss ]"

· " yyyy-mm-dd [hh:mi:ss ]"

Return Value

datetime type value containing the number of seconds elapsed since 01.01.1970.
Note

Any sequence of space and tabulation characters between date and time is considered to be a single
space to avoid additional processing of the time_string before calling S tringToTime().

Example:

//--- input parameters


input group "The date can be entered in any of the formats:"
input group "yyyy.mm.dd [hh:mi], yyyy.mm.dd [hh:mi:ss]"
input group "yyyymmdd [hh:mi:ss], yyyymmdd [hhmiss]"
input group "yyyy/mm/dd [hh:mi:ss], yyyy-mm-dd [hh:mi:ss]"
input string InpDateStr; // Please enter the date here as a string

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- convert the time entered in the inputs as a string into a datetime value
datetime time=StringToTime(InpDateStr);
//--- display the entered string and the obtained time in the journal
PrintFormat("Date entered as a string in the form '%s' is converted to datetime in the form '%s'

© 2000-2025, MetaQuotes Ltd.


1606 Conversion Functions

InpDateStr, TimeToString(time, TIME_DATE|TIME_MINUTES|TIME_SECONDS));


//--- create a vertical line on the received date-time and shift the chart to this location
if(CreateVLine(time))
ChartNavigateToTime(time);
/*
result:
Date entered as a string in the form '' is converted to datetime in the form '1970.01.01 00:00:0
Date entered as a string in the form '2024' is converted to datetime in the form '2024.02.24 20:
Date entered as a string in the form '202400' is converted to datetime in the form '2024.02.24 2
Date entered as a string in the form '20240000' is converted to datetime in the form '2024.02.24
Date entered as a string in the form '2024022410' is converted to datetime in the form '2030.09.
Date entered as a string in the form '20240224 10' is converted to datetime in the form '2024.02
Date entered as a string in the form '20240224 01' is converted to datetime in the form '2024.02
Date entered as a string in the form '20240224 0030' is converted to datetime in the form '2024.
Date entered as a string in the form '20240224 0100' is converted to datetime in the form '2024.
*/
}
//+------------------------------------------------------------------+
//| Create a vertical line object |
//+------------------------------------------------------------------+
bool CreateVLine(const datetime line_time)
{
ResetLastError();

string name=MQLInfoString(MQL_PROGRAM_NAME)+"_VLINE";
if(!ObjectCreate(0, name, OBJ_VLINE, 0, line_time, 0))
{
Print("ObjectCreate() failed. Error code: ", GetLastError());
return(false);
}
ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT);
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, true);

return(true);
}
//+------------------------------------------------------------------+
//| Shift the chart to the specified bar opening time |
//+------------------------------------------------------------------+
bool ChartNavigateToTime(const datetime time)
{
ChartSetInteger(0, CHART_AUTOSCROLL, false);
ResetLastError();

int bar=iBarShift(_Symbol, PERIOD_CURRENT, time);


if(bar<0)
{
PrintFormat("%s: iBarShift() failed. Error code: %d", __FUNCTION__, GetLastError());
return(false);
}

© 2000-2025, MetaQuotes Ltd.


1607 Conversion Functions

long first=0;
if(!ChartGetInteger(0, CHART_FIRST_VISIBLE_BAR, 0, first))
{
PrintFormat("%s: ChartGetInteger() failed. Error code: %d", __FUNCTION__, GetLastError());
return(false);
}

return(ChartNavigate(0, CHART_CURRENT_POS, (int)first-bar));


}

See also
TimeToS tring, TimeToS truct

© 2000-2025, MetaQuotes Ltd.


1608 Conversion Functions

StringFormat
The function formats obtained parameters and returns a string.
string StringFormat(
string format, // string with format description
... ... // parameters
);

Parameters
format
[in] S tring containing method of formatting. Formatting rules are the same as for the PrintFormat
function.
...
[in] Parameters, separated by a comma.

Return Value

S tring.

Example:

© 2000-2025, MetaQuotes Ltd.


1609 Conversion Functions

void OnStart()
{
//--- string variables
string output_string;
string temp_string;
string format_string;
//--- prepare the specification header
temp_string=StringFormat("Contract specification for %s:\n",_Symbol);
StringAdd(output_string,temp_string);
//--- int value output
int digits=(int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
temp_string=StringFormat(" SYMBOL_DIGITS = %d (number of digits after the decimal point)\n",
digits);
StringAdd(output_string,temp_string);
//--- double value output with variable number of digits after the decimal point
double point_value=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
format_string=StringFormat(" SYMBOL_POINT = %%.%df (point value)\n",
digits);
temp_string=StringFormat(format_string,point_value);
StringAdd(output_string,temp_string);
//--- int value output
int spread=(int)SymbolInfoInteger(_Symbol,SYMBOL_SPREAD);
temp_string=StringFormat(" SYMBOL_SPREAD = %d (current spread in points)\n",
spread);
StringAdd(output_string,temp_string);
//--- int value output
int min_stop=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
temp_string=StringFormat(" SYMBOL_TRADE_STOPS_LEVEL = %d (minimal indention in points for Stop
min_stop);
StringAdd(output_string,temp_string);
//--- double value output without the fractional part
double contract_size=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE);
temp_string=StringFormat(" SYMBOL_TRADE_CONTRACT_SIZE = %.f (contract size)\n",
contract_size);
StringAdd(output_string,temp_string);
//--- double value output with default accuracy
double tick_size=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
temp_string=StringFormat(" SYMBOL_TRADE_TICK_SIZE = %f (minimal price change)\n",
tick_size);
StringAdd(output_string,temp_string);
//--- determining the swap calculation mode
int swap_mode=(int)SymbolInfoInteger(_Symbol,SYMBOL_SWAP_MODE);
string str_swap_mode;
switch(swap_mode)
{
case SYMBOL_SWAP_MODE_DISABLED: str_swap_mode="SYMBOL_SWAP_MODE_DISABLED (no swaps)"; break;
case SYMBOL_SWAP_MODE_POINTS: str_swap_mode="SYMBOL_SWAP_MODE_POINTS (in points)"; break;
case SYMBOL_SWAP_MODE_CURRENCY_SYMBOL: str_swap_mode="SYMBOL_SWAP_MODE_CURRENCY_SYMBOL (in mo
case SYMBOL_SWAP_MODE_CURRENCY_MARGIN: str_swap_mode="SYMBOL_SWAP_MODE_CURRENCY_MARGIN (in mo
case SYMBOL_SWAP_MODE_CURRENCY_DEPOSIT: str_swap_mode="SYMBOL_SWAP_MODE_CURRENCY_DEPOSIT (in
case SYMBOL_SWAP_MODE_INTEREST_CURRENT: str_swap_mode="SYMBOL_SWAP_MODE_INTEREST_CURRENT (as
case SYMBOL_SWAP_MODE_INTEREST_OPEN: str_swap_mode="SYMBOL_SWAP_MODE_INTEREST_OPEN (as the sp
case SYMBOL_SWAP_MODE_REOPEN_CURRENT: str_swap_mode="SYMBOL_SWAP_MODE_REOPEN_CURRENT (by reop
case SYMBOL_SWAP_MODE_REOPEN_BID: str_swap_mode="SYMBOL_SWAP_MODE_REOPEN_BID (by reopening po
}
//--- string value output
temp_string=StringFormat(" SYMBOL_SWAP_MODE = %s\n",
str_swap_mode);
StringAdd(output_string,temp_string);
//--- double value output with default accuracy
double swap_long=SymbolInfoDouble(_Symbol,SYMBOL_SWAP_LONG);

© 2000-2025, MetaQuotes Ltd.


1610 Conversion Functions

temp_string=StringFormat(" SYMBOL_SWAP_LONG = %f (long swap value)\n",


swap_long);
StringAdd(output_string,temp_string);
//--- double value output with default accuracy
double swap_short=SymbolInfoDouble(_Symbol,SYMBOL_SWAP_SHORT);
temp_string=StringFormat(" SYMBOL_SWAP_SHORT = %f (short swap value)\n",
swap_short);
StringAdd(output_string,temp_string);
//--- determining the trading mode
int trade_mode=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_MODE);
string str_trade_mode;
switch(trade_mode)
{
case SYMBOL_TRADE_MODE_DISABLED: str_trade_mode="SYMBOL_TRADE_MODE_DISABLED (trade is disable
case SYMBOL_TRADE_MODE_LONGONLY: str_trade_mode="SYMBOL_TRADE_MODE_LONGONLY (only long positi
case SYMBOL_TRADE_MODE_SHORTONLY: str_trade_mode="SYMBOL_TRADE_MODE_SHORTONLY (only short pos
case SYMBOL_TRADE_MODE_CLOSEONLY: str_trade_mode="SYMBOL_TRADE_MODE_CLOSEONLY (only position
case SYMBOL_TRADE_MODE_FULL: str_trade_mode="SYMBOL_TRADE_MODE_FULL (no trade restrictions)";
}
//--- string value output
temp_string=StringFormat(" SYMBOL_TRADE_MODE = %s\n",
str_trade_mode);
StringAdd(output_string,temp_string);
//--- double value output in a compact format
double volume_min=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
temp_string=StringFormat(" SYMBOL_VOLUME_MIN = %g (minimal volume for a deal)\n",volume_min);
StringAdd(output_string,temp_string);
//--- double value output in a compact format
double volume_step=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
temp_string=StringFormat(" SYMBOL_VOLUME_STEP = %g (minimal volume change step)\n",volume_step
StringAdd(output_string,temp_string);
//--- double value output in a compact format
double volume_max=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
temp_string=StringFormat(" SYMBOL_VOLUME_MAX = %g (maximal volume for a deal)\n",volume_max);
StringAdd(output_string,temp_string);
//--- determining the contract price calculation mode
int calc_mode=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_CALC_MODE);
string str_calc_mode;
switch(calc_mode)
{
case SYMBOL_CALC_MODE_FOREX:str_calc_mode="SYMBOL_CALC_MODE_FOREX (Forex)";break;
case SYMBOL_CALC_MODE_FUTURES:str_calc_mode="SYMBOL_CALC_MODE_FUTURES (futures)";break;
case SYMBOL_CALC_MODE_CFD:str_calc_mode="SYMBOL_CALC_MODE_CFD (CFD)";break;
case SYMBOL_CALC_MODE_CFDINDEX:str_calc_mode="SYMBOL_CALC_MODE_CFDINDEX (CFD for indices)";br
case SYMBOL_CALC_MODE_CFDLEVERAGE:str_calc_mode="SYMBOL_CALC_MODE_CFDLEVERAGE (CFD at leverag
case SYMBOL_CALC_MODE_EXCH_STOCKS:str_calc_mode="SYMBOL_CALC_MODE_EXCH_STOCKS (trading securi
case SYMBOL_CALC_MODE_EXCH_FUTURES:str_calc_mode="SYMBOL_CALC_MODE_EXCH_FUTURES (trading futu
case SYMBOL_CALC_MODE_EXCH_FUTURES_FORTS:str_calc_mode="SYMBOL_CALC_MODE_EXCH_FUTURES_FORTS (
}
//--- string value output
temp_string=StringFormat(" SYMBOL_TRADE_CALC_MODE = %s\n",
str_calc_mode);
StringAdd(output_string,temp_string);
//--- double value output with 2 digits after the decimal point
double margin_initial=SymbolInfoDouble(_Symbol,SYMBOL_MARGIN_INITIAL);
temp_string=StringFormat(" SYMBOL_MARGIN_INITIAL = %.2f (initial margin)\n",
margin_initial);
StringAdd(output_string,temp_string);
//--- double value output with 2 digits after the decimal point
double margin_maintenance=SymbolInfoDouble(_Symbol,SYMBOL_MARGIN_MAINTENANCE);
temp_string=StringFormat(" SYMBOL_MARGIN_MAINTENANCE = %.2f (maintenance margin)\n",

© 2000-2025, MetaQuotes Ltd.


1611 Conversion Functions

margin_maintenance);
StringAdd(output_string,temp_string);
//--- int value output
int freeze_level=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_FREEZE_LEVEL);
temp_string=StringFormat(" SYMBOL_TRADE_FREEZE_LEVEL = %d (order freeze level in points)",
freeze_level);
StringAdd(output_string,temp_string);
Print(output_string);
Comment(output_string);
/* execution result
Contract specification for EURUSD:
SYMBOL_DIGITS = 5 (number of digits after the decimal point)
SYMBOL_POINT = 0.00001 (point value)
SYMBOL_SPREAD = 10 (current spread in points)
SYMBOL_TRADE_STOPS_LEVEL = 18 (minimal indention in points for Stop orders)
SYMBOL_TRADE_CONTRACT_SIZE = 100000 (contract size)
SYMBOL_TRADE_TICK_SIZE = 0.000010 (minimal price change)
SYMBOL_SWAP_MODE = SYMBOL_SWAP_MODE_POINTS (in points)
SYMBOL_SWAP_LONG = -0.700000 (buy order swap value)
SYMBOL_SWAP_SHORT = -1.000000 (sell order swap value)
SYMBOL_TRADE_MODE = SYMBOL_TRADE_MODE_FULL (no trade restrictions)
SYMBOL_VOLUME_MIN = 0.01 (minimal volume for a deal)
SYMBOL_VOLUME_STEP = 0.01 (minimal volume change step)
SYMBOL_VOLUME_MAX = 500 (maximal volume for a deal)
SYMBOL_TRADE_CALC_MODE = SYMBOL_CALC_MODE_FOREX (Forex)
SYMBOL_MARGIN_INITIAL = 0.00 (initial margin)
SYMBOL_MARGIN_MAINTENANCE = 0.00 (maintenance margin)
SYMBOL_TRADE_FREEZE_LEVEL = 0 (order freeze level in points)
*/
}

See also
PrintFormat, DoubleToS tring,ColorToS tring, TimeToS tring

© 2000-2025, MetaQuotes Ltd.


1612 Math Functions

Mathematical Functions
A set of mathematical and trigonometric functions.
Math functions were originally designed to perform relevant operations on scalar values. From this
build on, most of the functions can be applied to matrices and vectors. These include MathAbs,
MathArccos, MathArcsin, MathArctan, MathCeil, MathCos, MathExp, MathFloor, MathLog, MathLog10,
MathMod, MathPow, MathRound, MathS in, MathSqrt, MathTan, MathExpm1, MathLog1p, MathArccosh,
MathArcsinh, MathArctanh, MathCosh, MathS inh, and MathTanh. S uch operations imply element-wise
handling of matrices or vectors. Example:
//---
matrix a= {{1, 4}, {9, 16}};
Print("matrix a=\n",a);
a=MathSqrt(a);
Print("MatrSqrt(a)=\n",a);
/*
matrix a=
[[1,4]
[9,16]]
MatrSqrt(a)=
[[1,2]
[3,4]]
*/

For MathMod and MathPow, the second element can be either a scalar or a matrix/vector of the
appropriate size.

Function Action

MathAbs R eturns absolute value (modulus) of the specified numeric value


MathArccos R eturns the arc cosine of x in radians
MathArcsin R eturns the arc sine of x in radians
MathArctan R eturns the arc tangent of x in radians
MathArctan2 R eturn the angle (in radians) whose tangent is the quotient of two
specified numbers
MathClassify R eturns the type of a real number
MathCeil R eturns integer numeric value closest from above
MathCos R eturns the cosine of a number
MathExp R eturns exponent of a number
MathFloor R eturns integer numeric value closest from below
MathLog R eturns natural logarithm
MathLog10 R eturns the logarithm of a number by base 10

© 2000-2025, MetaQuotes Ltd.


1613 Math Functions

Function Action

MathMax R eturns the maximal value of the two numeric values


MathMin R eturns the minimal value of the two numeric values
MathMod R eturns the real remainder after the division of two numbers
MathPow R aises the base to the specified power
MathRand R eturns a pseudorandom value within the range of 0 to 32767
MathRound R ounds of a value to the nearest integer
MathS in R eturns the sine of a number
MathSqrt R eturns a s quare root
MathS rand S etsthe starting point for generating a series of pseudorandom
integers
MathTan R eturns the tangent of a number
MathIs ValidNumber Checks the correctness of a real number
MathExpm1 R eturns the value of the expression MathExp(x)-1
MathLog1p R eturns the value of the expression MathLog(1+x)
MathArccosh R eturns the hyperbolic arccosine
MathArcsinh R eturns the hyperbolic arcsine
MathArctanh R eturns the hyperbolic arctangent
MathCosh R eturns the hyperbolic cosine
MathS inh R eturns the hyperbolic sine
MathTanh R eturns the hyperbolic tangent
MathS wap Change the order of bytes in the ushort/uint/ushort types value

© 2000-2025, MetaQuotes Ltd.


1614 Math Functions

MathAbs
The function returns the absolute value (modulus) of the specified numeric value.
double MathAbs(
double value // numeric value
);

Parameters
value
[in] Numeric value.

Return Value

Value of double type more than or equal to zero.


Note

Instead the MathAbs() function you can use fabs().

Example:

//--- input parameters


input int InpValue = -10; // Enter any value here

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the absolute value of the number entered in the inputs
uint abs_value=MathAbs(InpValue);
//--- print the values in the journal
PrintFormat("The entered value %d received the value %u after using the MathAbs() function",InpV
}

© 2000-2025, MetaQuotes Ltd.


1615 Math Functions

MathArccos
The function returns the arccosine of x within the range 0 to p 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.

Return 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().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/1000);
delta[0]=-1;
//--- get 101 values from -1 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the arc cosine value for each value of the X vector
vector Y=MathArccos(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

© 2000-2025, MetaQuotes Ltd.


1616 Math Functions

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit
while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and saves the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


1617 Math Functions

int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_


if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1618 Math Functions

MathArcsin
The function returns the arc sine of x within the range of -p /2 to p /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.

Return Value

Arc sine ofthe val number in radians within the range of -p /2 to p /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().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/1000);
delta[0]=-1;
//--- get 101 values from -1 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the sine value for each value of the X vector
vector Y=MathArcsin(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

© 2000-2025, MetaQuotes Ltd.


1619 Math Functions

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit
while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


1620 Math Functions

int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_


if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1621 Math Functions

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.

Return Value

MathArctan returns a value within the range of -p /2 to p /2 radians.


Note

Instead of the MathArctan() function you can use atan().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/100);
delta[0]=0;
//--- get 101 values from 0 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the arc tangent value for each value of the X vector
vector Y=MathArctan(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1622 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_

© 2000-2025, MetaQuotes Ltd.


1623 Math Functions

if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1624 Math Functions

MathArctan2
R eturn the angle (in radians) whose tangent is the quotient of two specified numbers.
double MathArctan2(
double y // The y coordinate of a point
double x // The x coordinate of a point
);

Parameters
y
[in] Y coordinate value.

x
[in] X coordinate value.

Return Value

MathArctan2 returns an angle, θ, within the range from -p to p radians, so that MathTan(θ)=y/x.
Please note as follows:

· For (x, y) in quadrant 1, 0< θ < p /2


· For (x, y) in quadrant 2, p /2< θ ≤ p
· For (x, y) in quadrant 3, -p < θ < -p /2
· For (x, y) in quadrant 4, -p /2 < θ < 0

For points on the boundaries of the quadrants, the return value is the following:
· If y is 0 and x is not negative, θ = 0.
· If y is 0 and x is negative, θ = p .
· If y is positive and x is 0, θ = p /2.
· If y is negative and x is 0, θ = -p /2.
· If y is 0 and x is 0, θ = 0.
Note

Instead of the MathArctan2() function, you can use the atan2() function.

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()

© 2000-2025, MetaQuotes Ltd.


1625 Math Functions

{
vector delta=vector::Full(10,10);
delta[0]=0;
//--- get 101 values from 0 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the arc tangent value for each value of the X vector
vector Y=delta.CumSum();

Print("vector delta = \n",delta);


Print("vector X = \n",X);
Print("vector Y = \n",Y);

//--- transfer the calculated values from vectors to arrays


double x_array[];;
double y_array[];;
X.Swap(x_array);
Y.Swap(y_array);

double array[10];
for(int i=0; i<10; i++)
{
array[i]=MathArctan2(y_array[i],x_array[i]);
}

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit
while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'

© 2000-2025, MetaQuotes Ltd.


1626 Math Functions

if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL


return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_
if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

© 2000-2025, MetaQuotes Ltd.


1627 Math Functions

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1628 Math Functions

MathClassify
Determines the type of a real number and returns a result as a value from the ENUM _FP_CL ASS
enumeration
ENUM_FP_CLASS MathClassify(
double value // real number
);

Parameters
value
[in] The real number to be checked

Return Value

A value from the ENUM _FP_CLASS enumeration


ENUM_FP_CLASS

ID Description

FP_SUBNOR M AL A subnormal number which is closer to zero than


the smallest representable normal number
DBL _MIN (2.2250738585072014e-308)

FP_NOR M AL A normal number in the range between


2.2250738585072014e-308 and
1.7976931348623158e+308

FP_ZER O A positive or a negative zero


FP_INFINIT E A number which cannot be represented by the
appropriate type, positive or negative infinity
FP_NAN Not a number.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- test NaN
double nan=double("nan");
PrintFormat("Test NaN: %G is %s, MathIsValidNumber(NaN)=%s",
nan,
EnumToString(MathClassify(nan)),
(string)MathIsValidNumber(nan));
//--- test infinity
double inf=double("inf");
PrintFormat("Test Inf: %G is %s, MathIsValidNumber(inf)=%s",

© 2000-2025, MetaQuotes Ltd.


1629 Math Functions

inf,
EnumToString(MathClassify(inf)),
(string)MathIsValidNumber(inf));
//--- test normal value
double normal=1.2345e6;
PrintFormat("Test Normal: %G is %s, MathIsValidNumber(normal)=%s",
normal,
EnumToString(MathClassify(normal)),
(string)MathIsValidNumber(normal));
//--- test subnormal value
double sub_normal=DBL_MIN/2.0;
PrintFormat("Test Subnormal: %G is %s, MathIsValidNumber(sub_normal)=%s",
sub_normal,
EnumToString(MathClassify(sub_normal)),
(string)MathIsValidNumber(sub_normal));
//--- test zero value
double zero=0.0/(-1);
PrintFormat("Test Zero: %G is %s, MathIsValidNumber(zero)=%s",
zero,
EnumToString(MathClassify(zero)),
(string)MathIsValidNumber(zero));
}
/*
Result:
Test NaN: NAN is FP_NAN, MathIsValidNumber(NaN)=false
Test Inf: INF is FP_INFINITE, MathIsValidNumber(inf)=false
Test Normal: 1.2345E+06 is FP_NORMAL, MathIsValidNumber(normal)=true
Test Subnormal: 1.11254E-308 is FP_SUBNORMAL, MathIsValidNumber(sub_normal)=true
Test Zero: -0 is FP_ZERO, MathIsValidNumber(zero)=true
*/
//+------------------------------------------------------------------+

See also
R eal types (double, float), MathIs ValidNumber

© 2000-2025, MetaQuotes Ltd.


1630 Math Functions

MathCeil
The function returns integer numeric value closest from above.
double MathCeil(
double val // number
);

Parameters
val
[in] Numeric value.

Return Value

Numeric value representing the smallest integer that exceeds or equals to val.
Note

Instead of the MathCeil() function you can use ceil().

Example:

#define VALUES_TOTAL 31

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare variables for conversion
double value=0; // real number for MathCeil conversion
int ceil_value=0; // get the result here
//--- in a loop by the number of decimal increments of a real number
for(int i=0; i<VALUES_TOTAL; i++)
{
//--- increase the number value,
//--- get the nearest integer value from above
//--- and display control values in the journal
value+=0.1;
ceil_value=(int)MathCeil(NormalizeDouble(value,1));
PrintFormat("value: %.1f, ceil value: %d",value,ceil_value);
/*
result:
value: 0.1, ceil value: 1
value: 0.2, ceil value: 1
value: 0.3, ceil value: 1
value: 0.4, ceil value: 1
value: 0.5, ceil value: 1
value: 0.6, ceil value: 1

© 2000-2025, MetaQuotes Ltd.


1631 Math Functions

value: 0.7, ceil value: 1


value: 0.8, ceil value: 1
value: 0.9, ceil value: 1
value: 1.0, ceil value: 1
value: 1.1, ceil value: 2
value: 1.2, ceil value: 2
value: 1.3, ceil value: 2
value: 1.4, ceil value: 2
value: 1.5, ceil value: 2
value: 1.6, ceil value: 2
value: 1.7, ceil value: 2
value: 1.8, ceil value: 2
value: 1.9, ceil value: 2
value: 2.0, ceil value: 2
value: 2.1, ceil value: 3
value: 2.2, ceil value: 3
value: 2.3, ceil value: 3
value: 2.4, ceil value: 3
value: 2.5, ceil value: 3
value: 2.6, ceil value: 3
value: 2.7, ceil value: 3
value: 2.8, ceil value: 3
value: 2.9, ceil value: 3
value: 3.0, ceil value: 3
value: 3.1, ceil value: 4
*/
}
}

© 2000-2025, MetaQuotes Ltd.


1632 Math Functions

MathCos
The function returns the cosine of an angle.
double MathCos(
double value // number
);

Parameters
value
[in] Angle in radians.

Return Value

Value of double type within the range of -1 to 1.


Note

Instead of MathCos() you can use cos().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/100);
delta[0]=0;
//--- get 101 values from 0 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the cosine value for each value of the X vector
vector Y=MathCos(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1633 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_

© 2000-2025, MetaQuotes Ltd.


1634 Math Functions

if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1635 Math Functions

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.

Return Value

Anumber of double type. In case of overflow the function returns INF (infinity), in case of underflow
MathExp returns 0.
Note

Instead of MathExp() you can use exp().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get 9 values from 0 to 8 with step 1
vector X(9,VectorArange);
Print("vector X = \n",X);
//--- calculate the "e" (Euler number) to the power of each X vector value
X=MathExp(X);
Print("MathExp(X) = \n",X);

//--- transfer the calculated values from the vector to the array
double y_array[];
X.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1636 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| Fill a vector with 'value' in 'step' increments |
//+------------------------------------------------------------------+
template<typename T>
void VectorArange(vector<T> &vec,T value=0.0,T step=1.0)
{
for(ulong i=0; i<vec.Size(); i++,value+=step)
vec[i]=value;
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();

© 2000-2025, MetaQuotes Ltd.


1637 Math Functions

}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_
if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1638 Math Functions

MathFloor
The function returns integer numeric value closest from below.
double MathFloor(
double val // number
);

Parameters
val
[in] Numeric value.

Return Value

A numeric value representing the largest integer that is less than or equal to val.
Note

Instead of MathFloor() you can use floor().

Example:

#define VALUES_TOTAL 31

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare variables for conversion
double value=0; // real number for MathFloor conversion
int floor_value=0; // get the result here
//--- in a loop by the number of decimal increments of a real number
for(int i=0; i<VALUES_TOTAL; i++)
{
//--- increase the number value,
//--- get the nearest integer value from below
//--- and display control values in the journal
value+=0.1;
floor_value=(int)MathFloor(NormalizeDouble(value,1));
PrintFormat("value: %.1f, floor value: %d",value,floor_value);
/*
result:
value: 0.1, floor value: 0
value: 0.2, floor value: 0
value: 0.3, floor value: 0
value: 0.4, floor value: 0
value: 0.5, floor value: 0
value: 0.6, floor value: 0

© 2000-2025, MetaQuotes Ltd.


1639 Math Functions

value: 0.7, floor value: 0


value: 0.8, floor value: 0
value: 0.9, floor value: 0
value: 1.0, floor value: 1
value: 1.1, floor value: 1
value: 1.2, floor value: 1
value: 1.3, floor value: 1
value: 1.4, floor value: 1
value: 1.5, floor value: 1
value: 1.6, floor value: 1
value: 1.7, floor value: 1
value: 1.8, floor value: 1
value: 1.9, floor value: 1
value: 2.0, floor value: 2
value: 2.1, floor value: 2
value: 2.2, floor value: 2
value: 2.3, floor value: 2
value: 2.4, floor value: 2
value: 2.5, floor value: 2
value: 2.6, floor value: 2
value: 2.7, floor value: 2
value: 2.8, floor value: 2
value: 2.9, floor value: 2
value: 3.0, floor value: 3
value: 3.1, floor value: 3
*/
}

© 2000-2025, MetaQuotes Ltd.


1640 Math Functions

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.

Return 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().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get 9 values from 0 to 8 with step 1
vector X(9,VectorArange);
Print("vector X = \n",X);
//--- calculate the logarithm for each value of the X vector
X=MathLog(X);
Print("MathLog(X) = \n",X);

//--- transfer the calculated values from the vector to the array
double y_array[];
X.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1641 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
/*
result:
vector X =
[0,1,2,3,4,5,6,7,8]
MathLog(X) =
[-inf,0,0.6931471805599453,1.09861228866811,1.386294361119891,1.6094379124341,1.791759469228055,
*/
}
//+------------------------------------------------------------------+
//| Fill a vector with 'value' in 'step' increments |
//+------------------------------------------------------------------+
template<typename T>
void VectorArange(vector<T> &vec,T value=0.0,T step=1.0)
{
for(ulong i=0; i<vec.Size(); i++,value+=step)
vec[i]=value;
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);

© 2000-2025, MetaQuotes Ltd.


1642 Math Functions

ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_
if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

© 2000-2025, MetaQuotes Ltd.


1643 Math Functions

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1644 Math Functions

MathLog
R eturns 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.

Return 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().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get 9 values from 0 to 8 with step 1
vector X(9,VectorArange);
Print("vector X = \n",X);
//--- calculate the decimal logarithm for each value of the X vector
X=MathLog10(X);
Print("MathLog10(X) = \n",X);

//--- transfer the calculated values from the vector to the array
double y_array[];
X.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1645 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
/*
result:
vector X =
[0,1,2,3,4,5,6,7,8]
MathLog10(X) =
[-inf,0,0.3010299956639812,0.4771212547196624,0.6020599913279624,0.6989700043360189,0.7781512503
*/
}
//+------------------------------------------------------------------+
//| Fill a vector with 'value' in 'step' increments |
//+------------------------------------------------------------------+
template<typename T>
void VectorArange(vector<T> &vec,T value=0.0,T step=1.0)
{
for(ulong i=0; i<vec.Size(); i++,value+=step)
vec[i]=value;
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);

© 2000-2025, MetaQuotes Ltd.


1646 Math Functions

ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_
if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

© 2000-2025, MetaQuotes Ltd.


1647 Math Functions

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1648 Math Functions

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] S econd numeric value.

Return Value

The largest of the two values.


Note

Instead of MathMax() you can use fmax(). Functions fmax(), fmin(), MathMax(), MathMin() can
work with integer types without typecasting them to the type of double.
If parameters of different types are passed into a function, the parameter of the smaller type is
automatically cast to the larger type. The type of the return value corresponds to the larger type.
If data of the same type are passed, no casting is performed.

Example:

//--- input parameters


input int InpPeriod = 10; // Moving average calculation period
input ENUM_MA_METHOD InpMethod = MODE_SMA; // Moving average calculation method
input ENUM_APPLIED_PRICE InpPrice = PRICE_CLOSE; // Moving average calculation price

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- if the moving average period is set to a value less than 1, then the default value (10) is us
int period=(InpPeriod<1 ? 10 : InpPeriod);
//--- create the Moving Average indicator handle
int handle=iMA(Symbol(),Period(),period,0,InpMethod,InpPrice);
if(handle==INVALID_HANDLE)
{
Print("Failed to create the Moving Average indicator handle. Error ",GetLastError());
return;

© 2000-2025, MetaQuotes Ltd.


1649 Math Functions

}
//--- get the current Bid price
double bid=0;
ResetLastError();
if(!SymbolInfoDouble(Symbol(),SYMBOL_BID,bid))
{
Print("Failed to get Bid price. Error ",GetLastError());
return;
}
//--- get the moving average value on the current bar
double array[1];
int copied=CopyBuffer(handle,0,0,1,array);
if(copied!=1)
{
Print("Failed to get Moving Average data. Error ",GetLastError());
return;
}
//--- get the highest price of the two (Bid price and Moving Average value) and display the resulti
double max_price=MathMax(bid,array[0]);
PrintFormat("Bid: %.*f, Moving Average: %.*f, highest price of the two: %.*f",_Digits,bid,_Digit
PrintFormat("Bid price %s moving average",(bid>array[0] ? "higher" : bid<array[0] ? "lower" : "e
}

© 2000-2025, MetaQuotes Ltd.


1650 Math Functions

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] S econd numeric value.

Return Value

The smallest of the two values.


Note

Instead of MathMin() you can use fmin(). Functions fmax(), fmin(), MathMax(), MathMin() can work
with integer types without typecasting them to the type of double.
If parameters of different types are passed into a function, the parameter of the smaller type is
automatically cast to the larger type. The type of the return value corresponds to the larger type.
If data of the same type are passed, no casting is performed.

Example:

//--- input parameters


input uint InpBars = 100000; // Desired number of bars

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the number of available bars on the server
uint bars_total = Bars(Symbol(),Period());
if(bars_total==0)
{
PrintFormat("Data for timeseries %s %s not yet generated in the terminal. Please try again la
return;
}
//--- get the minimum number of bars from two values - from those available on the server and from
int bars = (int)MathMin(bars_total,InpBars);
//--- if more bars are requested than are available on the server, report this in the journal

© 2000-2025, MetaQuotes Ltd.


1651 Math Functions

if(bars_total<InpBars)
PrintFormat("Number of bars on the server (%u) is less than requested (%u)",bars_total,InpBar
//--- display the number of bars available for work in the journal
Print("Bars available for work: ",bars);
}

© 2000-2025, MetaQuotes Ltd.


1652 Math Functions

MathMod
The function returns the real remainder of division of two numbers.
double MathMod(
double value, // dividend value
double value2 // divisor value
);

Parameters
value
[in] Dividend value.

value2
[in] Divisor value.

Return Value

The MathMod function calculates the real remainder f from expression val/y so 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().

Example:

#property script_show_inputs

//--- input parameters


input double InpDividentValue = 10; // Dividend value
input double InpDivisorValue = 3; // Divisor value

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the real remainder of the division of the numbers entered in the inputs
double res=MathMod(InpDividentValue,InpDivisorValue);
//--- print the result in the journal
PrintFormat("Real remainder when dividing %.2f by %.2f = %.2f",InpDividentValue,InpDivisorValue,
}

© 2000-2025, MetaQuotes Ltd.


1653 Math Functions

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.

Return Value

Value of base raised to the specified power.


Note

Instead of MathPow() you can use pow().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#property script_show_inputs

#include <Graphics\Graphic.mqh>

//--- input parameters


input double InpExponentValue = 2; // exponent value

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get 11 values from 0 to 10 with step 1
vector X(11,VectorArange);
Print("vector X = \n",X);
//--- calculate each value of the X vector raised to the InpExponentValue power
X=MathPow(X,InpExponentValue);
Print("MathPow(X,",(string)InpExponentValue,") = \n",X);

© 2000-2025, MetaQuotes Ltd.


1654 Math Functions

//--- transfer the calculated values from the vector to the array
double y_array[];
X.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit
while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
/*
result:
vector X =
[0,1,2,3,4,5,6,7,8,9,10]
MathPow(X,2.0) =
[0,1,4,9,16,25,36,49,64,81,100]
*/
}
//+------------------------------------------------------------------+
//| Fill a vector with 'value' in 'step' increments |
//+------------------------------------------------------------------+
template<typename T>
void VectorArange(vector<T> &vec,T value=0.0,T step=1.0)
{
for(ulong i=0; i<vec.Size(); i++,value+=step)
vec[i]=value;
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);

© 2000-2025, MetaQuotes Ltd.


1655 Math Functions

}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_
if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

© 2000-2025, MetaQuotes Ltd.


1656 Math Functions

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1657 Math Functions

MathRand
R eturns a pseudorandom integer within the range of 0 to 32767.
int MathRand();

Return Value

Integer value within the range of 0 to 32767.


Note

Before the first call of the function, it's necessary to call MathS rand to set the generator of
pseudorandom numbers to the initial state.
Note

Instead of MathRand() you can use rand().

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set a new initial state to generate a series of pseudo-random integers at each launch
MathSrand(GetTickCount());
//--- in a loop, display 10 generated pseudo-random integers in the journal
for(int i=0; i<10; i++)
{
int rand_value=MathRand();
PrintFormat("Pseudorandom integer №%d: %u",i+1,rand_value);
}
}

© 2000-2025, MetaQuotes Ltd.


1658 Math Functions

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.

Return Value

Value rounded till to the nearest integer.


Note

Instead of MathRound() you can use round().

Example:

#define VALUES_TOTAL 31

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare variables for conversion
double value=0; // real number for MathRound conversion
int round_value=0; // get the result here
//--- in a loop by the number of decimal increments of a real number
for(int i=0; i<VALUES_TOTAL; i++)
{
//--- increase the real number value,
//--- get a numeric value rounded to the nearest integer
//--- and display control values in the journal
value+=0.1;
round_value=(int)MathRound(NormalizeDouble(value,1));
PrintFormat("value: %.1f, round value: %d",value,round_value);
/*
result:
value: 0.1, round value: 0
value: 0.2, round value: 0
value: 0.3, round value: 0
value: 0.4, round value: 0
value: 0.5, round value: 1
value: 0.6, round value: 1

© 2000-2025, MetaQuotes Ltd.


1659 Math Functions

value: 0.7, round value: 1


value: 0.8, round value: 1
value: 0.9, round value: 1
value: 1.0, round value: 1
value: 1.1, round value: 1
value: 1.2, round value: 1
value: 1.3, round value: 1
value: 1.4, round value: 1
value: 1.5, round value: 2
value: 1.6, round value: 2
value: 1.7, round value: 2
value: 1.8, round value: 2
value: 1.9, round value: 2
value: 2.0, round value: 2
value: 2.1, round value: 2
value: 2.2, round value: 2
value: 2.3, round value: 2
value: 2.4, round value: 2
value: 2.5, round value: 3
value: 2.6, round value: 3
value: 2.7, round value: 3
value: 2.8, round value: 3
value: 2.9, round value: 3
value: 3.0, round value: 3
value: 3.1, round value: 3
*/
}
}

© 2000-2025, MetaQuotes Ltd.


1660 Math Functions

MathSin
R eturns the sine of a specified angle.
double MathSin(
double value // argument in radians
);

Parameters
value
[in] Angle in radians.

Return Value

S ine of an angle measured in radians. Returns value within the range of -1 to 1.


Note

Instead of MathS in() you can use sin().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/100);
delta[0]=0;
//--- get 101 values from 0 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the sine value for each value of the X vector
vector Y=MathSin(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1661 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_

© 2000-2025, MetaQuotes Ltd.


1662 Math Functions

if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1663 Math Functions

MathSqrt
R eturns the s quare root of a number.
double MathSqrt(
double value // positive number
);

Parameters
value
[in] Positive numeric value.

Return Value

Square root of value. If value is negative, MathSqrt returns NaN (indeterminate value).
Note

Instead of MathSqrt() you can use s qrt().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get 11 values from 0 to 10 with step 1
vector X(11,VectorArange);
Print("vector X = \n",X);
//--- calculate the square root of each value of the X vector
X=MathSqrt(X);
Print("MathSqrt(X) = \n",X);

//--- transfer the calculated values from the vector to the array
double y_array[];
X.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit
while(!IsStopped())

© 2000-2025, MetaQuotes Ltd.


1664 Math Functions

{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
/*
result:
vector X =
[0,1,2,3,4,5,6,7,8,9,10]
MathSqrt(X) =
[0,1,1.414213562373095,1.732050807568877,2,2.23606797749979,2.449489742783178,2.645751311064591,
*/
}
//+------------------------------------------------------------------+
//| Fill a vector with 'value' in 'step' increments |
//+------------------------------------------------------------------+
template<typename T>
void VectorArange(vector<T> &vec,T value=0.0,T step=1.0)
{
for(ulong i=0; i<vec.Size(); i++,value+=step)
vec[i]=value;
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);

© 2000-2025, MetaQuotes Ltd.


1665 Math Functions

ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_
if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also

© 2000-2025, MetaQuotes Ltd.


1666 Math Functions

R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1667 Math Functions

MathSrand
S ets the starting point for generating a series of pseudorandom integers.
void MathSrand(
int seed // initializing number
);

Parameters
seed
[in] S tarting number for the sequence of random numbers.

Return Value

No return value.
Note

The MathRand() function is used for generating a sequence of pseudorandom numbers. Call of
MathS rand() with a certain initializing number allows to always produces the same sequence of
pseudorandom numbers.
To ensure receipt of non-recurring sequence, use the call of MathS rand(GetTickCount()), since the
value of GetTickCount() increases from the moment of the start of the operating system and is not
repeated within 49 days, until the built-in counter of milliseconds overflows. Use of
MathS rand(TimeCurrent()) is not suitable, because the TimeCurrent() function returns the time of
the last tick, which can be unchanged for a long time, for example at the weekend.
Initialization of the random number generator using MathS rand() for indicators and Expert Advisors
is better performed in the OnInit() handler; it saves you from the following multiple restarts of the
generator in OnTick() and OnCalculate().
Instead of the MathS rand() function you can use the srand() function.
Example:

#property description "The indicator shows the central limit theorem, which states:"
#property description "The sum of a sufficiently large number of weakly dependent random variables,
#property description "having approximately equal magnitude (none of the summands dominates,"
#property description "or makes a determining contribution to the sum), has a distribution close to

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//--- Properties of the graphical construction
#property indicator_label1 "Label"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrRoyalBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 5
//--- An input variable
input int sample_number=10;
//--- An indicator buffer to for drawing the distribution

© 2000-2025, MetaQuotes Ltd.


1668 Math Functions

double LabelBuffer[];
//--- A counter of ticks
double ticks_counter;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- Binding an array and an indicator buffer
SetIndexBuffer(0,LabelBuffer,INDICATOR_DATA);
//--- turn the indicator buffer around from the present to the past
ArraySetAsSeries(LabelBuffer,true);
//--- Initialize the generator of random numbers
MathSrand(GetTickCount());
//--- Initialize the counter of ticks
ticks_counter=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[])
{
//--- For a zero counter reset the indicator buffer
if(ticks_counter==0) ArrayInitialize(LabelBuffer,0);
//--- Increase the counter
ticks_counter++;
//--- We should periodically reset the counter ticks, to revive the distribution
if(ticks_counter>100)
{
Print("We've reset the indicator values, let's start filling the cells once again");
ticks_counter=0;
}
//--- Get a sample of random values as the sum of three numbers from 0 to 7
for(int i=0;i<sample_number;i++)
{
//--- Calculation of the index of the cell, where the random number falls as the sum of three
int rand_index=0;
//--- Get three random numbers from 0 to 7
for(int k=0;k<3;k++)
{

© 2000-2025, MetaQuotes Ltd.


1669 Math Functions

//--- A remainder in the division by 7 will return a value from 0 to 6


rand_index+=MathRand()%7;
}
//--- Increase the value in the cell number rand_index by 1
LabelBuffer[rand_index]++;
}
//--- Exit the OnCalculate() handler
return(rates_total);
}

© 2000-2025, MetaQuotes Ltd.


1670 Math Functions

MathTan
The function returns a tangent of a number.
double MathTan(
double rad // argument in radians
);

Parameters
rad
[in] Angle in radians.

Return 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 number.
Note

Instead of MathTan() you can use tan().

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/100);
delta[0]=-263;
//--- get 101 values from -263 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the tangent value for each value of the X vector
vector Y=MathTan(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

© 2000-2025, MetaQuotes Ltd.


1671 Math Functions

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit
while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


1672 Math Functions

int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_


if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1673 Math Functions

MathIsValidNumber
It checks the correctness of a real number.
bool MathIsValidNumber(
double number // number to check
);

Parameters
number
[in] Checked numeric value.

Return 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
R eal types (double, float)

© 2000-2025, MetaQuotes Ltd.


1674 Math Functions

MathExpm1
R eturns the value of the expression MathExp(x)-1.
double MathExpm1(
double value // power for the number e
);

Parameters
value
[in] The number specifying the power.

Return Value

A value of the double type. In case of overflow the function returns INF (infinity), in case of
underflow MathExpm1 returns 0.
Note

At values of x close to 0, the MathExpm1(x) function generates much more accurate values than the
MathExp(x)-1 function.
Instead of the MathExpm1() function you can use the expm1() function.

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get 9 values from 0 to 8 with step 1
vector X(9,VectorArange);
Print("vector X = \n",X);
//--- calculate the ("e"(Euler number) to the power of each X vector value) - 1
X=MathExpm1(X);
Print("MathExpm1(X) = \n",X);

//--- transfer the calculated values from the vector to the array
double y_array[];
X.Swap(y_array);

//--- draw a graph of the calculated vector values

© 2000-2025, MetaQuotes Ltd.


1675 Math Functions

CurvePlot(y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit
while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| Fill a vector with 'value' in 'step' increments |
//+------------------------------------------------------------------+
template<typename T>
void VectorArange(vector<T> &vec,T value=0.0,T step=1.0)
{
for(ulong i=0; i<vec.Size(); i++,value+=step)
vec[i]=value;
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";

© 2000-2025, MetaQuotes Ltd.


1676 Math Functions

ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));


ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_
if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1677 Math Functions

MathLog1p
R eturns the value of the expression MathLog(1+x).
double MathLog1p(
double value // value to take the logarithm
);

Parameters
value
[in] The value, the logarithm of which is to be calculated.

Return Value

The natural logarithm of the value (value + 1) if successful. If value is < -1, the function returns NaN
(undefined value). If value is equal to -1, the function returns INF (infinity).
Note

At values
of x close to 0, the MathLog1p(x) function generates much more accurate values than the
MathLog(1+x) function.
Instead of the MathLog1p() function you can use the log1p() function.

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get 9 values from 0 to 8 with step 1
vector X(9,VectorArange);
Print("vector X = \n",X);
//--- for each vector value, calculate the logarithm for the expression (1 + X vector value)
X=MathLog1p(X);
Print("MathLog1p(X) = \n",X);

//--- transfer the calculated values from the vector to the array
double y_array[];
X.Swap(y_array);

//--- draw a graph of the calculated vector values

© 2000-2025, MetaQuotes Ltd.


1678 Math Functions

CurvePlot(y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit
while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
/*
result:
vector X =
[0,1,2,3,4,5,6,7,8]
MathLog1p(X) =
[0,0.6931471805599453,1.09861228866811,1.386294361119891,1.6094379124341,1.791759469228055,1.945
*/
}
//+------------------------------------------------------------------+
//| Fill a vector with 'value' in 'step' increments |
//+------------------------------------------------------------------+
template<typename T>
void VectorArange(vector<T> &vec,T value=0.0,T step=1.0)
{
for(ulong i=0; i<vec.Size(); i++,value+=step)
vec[i]=value;
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)

© 2000-2025, MetaQuotes Ltd.


1679 Math Functions

{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_
if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

© 2000-2025, MetaQuotes Ltd.


1680 Math Functions

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1681 Math Functions

MathArccosh
R eturns the hyperbolic arccosine.
double MathArccosh(
double value // 1 <= value < ∞
);

Parameters
value
[in] The value, the hyperbolic arccosine of which is to be calculated.

Return Value

The hyperbolic arccosine of the number. If value is less than +1, the function returns NaN (undefined
value).
Note

Instead of the MathArccosh() function you can use the acosh() function.

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/10);
delta[0]=1;
//--- get 101 values from 1 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the hyperbolic arc cosine value for each value of the X vector
vector Y=MathArccosh(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

© 2000-2025, MetaQuotes Ltd.


1682 Math Functions

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit
while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and saves the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


1683 Math Functions

int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_


if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1684 Math Functions

MathArcsinh
R eturns the hyperbolic arcsine.
double MathArcsinh(
double value // -∞ < value < +∞
);

Parameters
val
[in] The value, the hyperbolic arcsine of which is to be calculated.

Return Value

The hyperbolic arcsine of the number.


Note

Instead of the MathArcsinh() function you can use the asinh() function.

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/10);
delta[0]=-31;
//--- get 101 values from -31 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the hyperbolic arc sine value for each value of the X vector
vector Y=MathArcsinh(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1685 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_

© 2000-2025, MetaQuotes Ltd.


1686 Math Functions

if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1687 Math Functions

MathArctanh
R eturns the hyperbolic arctangent.
double MathArctanh(
double value // value in the range of -1 < value < 1
);

Parameters
value
[in] Number within the range of -1 < value < 1, which represents the tangent.

Return Value

The hyperbolic arctangent of the number.


Note

Instead of the MathArctanh() function you can use the atanh() function.

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(34,2*M_PI/100);
delta[0]=-1;
//--- get 34 values from -1 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the hyperbolic arc tangent value for each value of the X vector
vector Y=MathArctanh(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1688 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_

© 2000-2025, MetaQuotes Ltd.


1689 Math Functions

if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1690 Math Functions

MathCosh
R eturns the hyperbolic cosine of the number.
double MathCosh(
double value // number
);

Parameters
value
[in] Value.

Return Value

The hyperbolic cosine of the number, value within the range of +1 to positive infinity.
Note

Instead of the MathCosh() function you can use the cosh() function.

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/100);
delta[0]=0;
//--- get 101 values from 0 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the hyperbolic cosine value for each value of the X vector
vector Y=MathCosh(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1691 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_

© 2000-2025, MetaQuotes Ltd.


1692 Math Functions

if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1693 Math Functions

MathSinh
R eturns the hyperbolic sine of the number.
double MathSinh(
double value // number
);

Parameters
value
[in] Value.

Return Value

The hyperbolic sine of the number.


Note

Instead of the MathS inh() function you can use the sinh() function.

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/100);
delta[0]=0;
//--- get 101 values from 0 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the hyperbolic sine value for each value of the X vector
vector Y=MathSinh(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1694 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_

© 2000-2025, MetaQuotes Ltd.


1695 Math Functions

if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1696 Math Functions

MathTanh
R eturns the hyperbolic tangent of the number.
double MathTanh(
double value // number
);

Parameters
value
[in] Value.

Return Value

The hyperbolic tangent of the number, value within the range of -1 to +1.
Note

Instead of the MathTanh() function you can use the tanh() function.

Example:

#define GRAPH_WIDTH 750


#define GRAPH_HEIGHT 350

#include <Graphics\Graphic.mqh>

CGraphic ExtGraph;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
vector delta=vector::Full(101,2*M_PI/100);
delta[0]=0;
//--- get 101 values from 0 to 2 pi with delta step
vector X=delta.CumSum();
//--- calculate the hyperbolic tangent value for each value of the X vector
vector Y=MathTanh(X);

//--- transfer the calculated values from vectors to arrays


double x_array[],y_array[];
X.Swap(x_array);
Y.Swap(y_array);

//--- draw a graph of the calculated vector values


CurvePlot(x_array,y_array,clrDodgerBlue);

//--- wait for pressing the Escape or PgDn keys to delete the graph (take a screenshot) and exit

© 2000-2025, MetaQuotes Ltd.


1697 Math Functions

while(!IsStopped())
{
if(StopKeyPressed())
break;
Sleep(16);
}

//--- clean up
ExtGraph.Destroy();
}
//+------------------------------------------------------------------+
//| When pressing ESC, return 'true' |
//| When pressing PgDn, take a graph screenshot and return 'true' |
//| Otherwise, return 'false' |
//+------------------------------------------------------------------+
bool StopKeyPressed()
{
//--- if ESC is pressed, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)!=0)
return(true);
//--- if PgDn is pressed and a graph screenshot is successfully taken, return 'true'
if(TerminalInfoInteger(TERMINAL_KEYSTATE_PAGEDOWN)!=0 && MakeAndSaveScreenshot(MQLInfoString(MQL
return(true);
//--- return 'false'
return(false);
}
//+------------------------------------------------------------------+
//| Create a graph object and draw a curve |
//+------------------------------------------------------------------+
void CurvePlot(double &x_array[], double &y_array[], const color colour)
{
ExtGraph.Create(ChartID(), "Graphic", 0, 0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
ExtGraph.CurveAdd(x_array, y_array, ColorToARGB(colour), CURVE_LINES);
ExtGraph.IndentUp(30);
ExtGraph.CurvePlotAll();
string text1="Press ESC to delete the graph and stop the script, or";
string text2="Press PgDn to create a screen, delete the graph and stop the script";
ExtGraph.TextAdd(54, 9, text1, ColorToARGB(clrBlack));
ExtGraph.TextAdd(54,21, text2, ColorToARGB(clrBlack));
ExtGraph.Update();
}
//+------------------------------------------------------------------+
//| Take a screenshot and save the image to a file |
//+------------------------------------------------------------------+
bool MakeAndSaveScreenshot(const string file_name)
{
string file_names[];
ResetLastError();
int selected=FileSelectDialog("Save Picture", NULL, "All files (*.*)|*.*", FSD_WRITE_FILE, file_

© 2000-2025, MetaQuotes Ltd.


1698 Math Functions

if(selected<1)
{
if(selected<0)
PrintFormat("%s: FileSelectDialog() function returned error %d", __FUNCTION__, GetLastErro
return false;
}

bool res=false;
if(ChartSetInteger(0,CHART_SHOW,false))
res=ChartScreenShot(0, file_names[0], GRAPH_WIDTH, GRAPH_HEIGHT);
ChartSetInteger(0,CHART_SHOW,true);
return(res);
}

Result:

See also
R eal types (double, float), S tatistics, S cientific Charts, Client Terminal Properties

© 2000-2025, MetaQuotes Ltd.


1699 Math Functions

MathSwap
Change the order of bytes in the ushort type value.
ushort MathSwap(
ushort value // value
);

Parameters
value
[in] Value for changing the order of bytes.

Return Value

ushort value with the reverse byte order.

MathSwap
Change the order of bytes in the uint type value.
uint MathSwap(
uint value // value
);

Parameters
value
[in] Value for changing the order of bytes.

Return Value

uint value with the reverse byte order.

MathSwap
Change the order of bytes in the ulong type value.
ulong MathSwap(
ulong value // value
);

Parameters
value
[in] Value for changing the order of bytes.

Return Value

ulong value with the reverse byte order.

Example:

© 2000-2025, MetaQuotes Ltd.


1700 Math Functions

#property script_show_inputs

input ulong InpLongValue = 1; // Enter any ulong value here


input uint InpIntValue = 2; // Enter any uint value here
input ushort InpShortValue = 3; // Enter any ushort value here

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{

//--- print the values entered and converted by MathSwap() in decimal and binary representation in
Print(ValueDescription(InpLongValue));
Print(ValueDescription(InpIntValue));
Print(ValueDescription(InpShortValue));
/*
result:
ulong value: 1
ulong value: 72057594037927936 using MathSwap()
binary ulong value: 0000000000000000000000000000000000000000000000000000000000000001
binary ulong value: 0000000100000000000000000000000000000000000000000000000000000000 using MathS

uint value: 2
uint value: 33554432 using MathSwap()
binary uint value: 00000000000000000000000000000010
binary uint value: 00000010000000000000000000000000 using MathSwap()

ushort value: 3
ushort value: 768 using MathSwap()
binary ushort value: 0000000000000011
binary ushort value: 0000001100000000 using MathSwap()
*/
}
//+------------------------------------------------------------------+
//| Return the text describing the variable values |
//+------------------------------------------------------------------+
template <typename T>
string ValueDescription(T x)
{
int num_bits = sizeof(T)*8;
string type_name = typename(T);
string bin_x = NumberToBinaryString(x);
string bin_swap_x = NumberToBinaryString(MathSwap(x));
return(StringFormat("%s value: %lld\n%s value: %lld using MathSwap()\nbinary %s value: %0*s\nbin
type_name, x, type_name, MathSwap(x), type_name, num_bits, bin_x, type_name,
}
//+------------------------------------------------------------------+
//| Return the binary representation of a number as a string |

© 2000-2025, MetaQuotes Ltd.


1701 Math Functions

//+------------------------------------------------------------------+
template <typename T>
string NumberToBinaryString(T x)
{
string res = "";
int i = -1;
uchar size = sizeof(T)*8-1;
ulong mask = (ulong)1<<size;
while(!((x<<++i)& mask));
for(; i <=size; i++)
res += !((x<<i)& mask) ? "0" : "1";
return res;
}

See also
Network functions, S ocketRead, S ocketS end, S ocketTls Read, S ocketTls ReadAvailable, S ocketTls S end

© 2000-2025, MetaQuotes Ltd.


1702 String Functions

String Functions
This is a group of functions intended for working with data of the string type.

Function Action

S tring Add Adds a string to the end of another string


S tring BufferLen R eturns the size of buffer allocated for the string
S tringCompare Compares two strings and returns 1 if the first string is greater than
the second; 0 - if the strings are equal; -1 (minus 1) - if the first string
is less than the second one
S tringConcatenate Forms a string of parameters passed
S tring Fill Fills out a specified string by selected symbols
S tring Find S earch for a substring in a string
S tring GetCharacter R eturns the value of a number located in the specified string position
S tringInit Initializes string by specified symbols and provides the specified string
length
S tringLen R eturns the number of symbols in a string
S tring S etLength S ets a specified length (in characters) for a string
S tring R eplace R eplaces all the found substrings of a string by a set sequence of
symbols
S tring R eserve R eserves the buffer of a specified size for a string in memory.
S tring S etCharacter R eturns a copy of a string with a changed value of a symbol in a
specified position
S tring S plit Gets substrings by a specified separator from the specified string,
returns the number of substrings obtained
S tring S ubstr Extracts a substring from a text string starting from a specified
position
S tringToLower Transforms all symbols of a selected string to lowercase
S tringToUpper Transforms all symbols of a selected string into capitals
S tringTrimLeft Cuts line feed characters, spaces and tabs in the left part of the string
S tringTrimR ight Cuts line feed characters, spaces and tabs in the right part of the string

© 2000-2025, MetaQuotes Ltd.


1703 String Functions

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] S tring, to which another one is added.
add_substring
[in] S tring that is added to the end of a source string.

Return Value

In case of success returns true, otherwise false. In order to get an error code, the GetLastError()
function should be called.
Example:

void OnStart()
{
long length=1000000;
string a="a",b="b",c;
//--- first method
uint 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++)

© 2000-2025, MetaQuotes Ltd.


1704 String Functions

{
StringConcatenate(c,a,b);
}
stop=GetTickCount();
Print("time for 'StringConcatenate(c,a,b)' = ",(stop-start)," milliseconds, i = ",i);
}

See also
S tringConcatenate, S tring S plit, S tring S ubstr

© 2000-2025, MetaQuotes Ltd.


1705 String Functions

StringBufferLen
The function returns the size of buffer allocated for the string.
int StringBufferLen(
string string_var // string
)

Parameters
string_var
[in] S tring.

Return 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.
Example:

void OnStart()
{
long length=1000;
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
S tring Add, S tringInit, S tringLen, S tring Fill

© 2000-2025, MetaQuotes Ltd.


1706 String Functions

StringCompare
The function compares two strings and returns the comparison result in form of an integer.
int StringCompare(
const string& string1, // the first string in the comparison
const string& string2, // the second string in the comparison
bool case_sensitive=true // case sensitivity mode selection for the comparison
);

Parameters
string1
[in] The first string.
string2
[in] The second string.
case_sensitive=true
[in] Case sensitivity mode selection. If it is true, then "A">" a" . If it is false, then "A"=" a" . By
default the value is equal to true.

Return Value
· -1 (minus one), if string1<string2
· 0 (zero), if string1=string2
· 1 (one), if string 1>string 2

Note

The strings are compared symbol by symbol, the symbols are compared in the alphabetic order in
accordance with the current code page.
Example:

void OnStart()
{
//--- what is larger - apple or home?
string s1="Apple";
string s2="home";

//--- compare case sensitive


int result1=StringCompare(s1,s2);
if(result1>0) PrintFormat("Case sensitive comparison: %s > %s",s1,s2);
else
{
if(result1<0)PrintFormat("Case sensitive comparison: %s < %s",s1,s2);
else PrintFormat("Case sensitive comparison: %s = %s",s1,s2);
}

//--- compare case-insensitive


int result2=StringCompare(s1,s2,false);
if(result2>0) PrintFormat("Case insensitive comparison: %s > %s",s1,s2);
else

© 2000-2025, MetaQuotes Ltd.


1707 String Functions

{
if(result2<0)PrintFormat("Case insensitive comparison: %s < %s",s1,s2);
else PrintFormat("Case insensitive comparison: %s = %s",s1,s2);
}
/* Result
Case-sensitive comparison: Apple < home
Case insensitive comparison: Apple < home
*/
}

See also
S tring Type, CharToS tring(), S hortToS tring(), S tringToCharArray(), S tringToS hortArray(),
S tring GetCharacter(), Use of a Codepage

© 2000-2025, MetaQuotes Ltd.


1708 String Functions

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
[out] S tring that will be formed as a result of concatenation.
argumentN
[in] Any comma separated values. From 2 to 63 parameters of any simple type.

Return Value

R eturns
the string length, formed by concatenation of parameters transformed into string type.
Parameters are transformed into strings according to the same rules as in Print() and Comment().
Example:

void OnStart()
{
//--- declare and define variables participating in concatenation
string text="";
string text1="This script shows how the StringConcatenate() function works.\n";
string text2="This is the second line, at the end of which there is a line break control code.\n
string text3="This is line number ";
int num3=3;
string text31=", the number of which is entered into the function as a separate parameter.";
string textN="\n";
string text4="This is line number 4, preceded by a separate parameter with a line break code.";
int length=StringConcatenate(text, text1, text2, text3, num3, text31, textN, text4, "\nLine 5
Print(text, "\nLength of the resulting string = ", length);

/*
Result
This script shows how the StringConcatenate() function works.
This is the second line, at the end of which there is a line break control code.
This is line number 3, the number of which is entered into the function as a separate parameter.
This is line number 4, preceded by a separate parameter with a line break code.
Line 5 includes a real number: 0.12345
Length of the resulting string = 358
*/
}

© 2000-2025, MetaQuotes Ltd.


1709 String Functions

See also

S tring Add, S tring S plit, S tring S ubstr

© 2000-2025, MetaQuotes Ltd.


1710 String Functions

StringFill
It fills out a selected string by specified symbols.
bool StringFill(
string& string_var, // string to fill
ushort character // symbol that will fill the string
);

Parameters
string_var
[in][out] S tring, that will be filled out by the selected symbol.
character
[in] S ymbol, by which the string will be filled out.

Return 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
S tring BufferLen, S tringLen, S tringInit

© 2000-2025, MetaQuotes Ltd.


1711 String Functions

StringFind
S earch 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] S tring, in which search is made.
match_substring
[in] S earched substring.

start_pos=0
[in] Position in the string from which search is started.

Return Value

R eturns position number in a string, from which the searched substring starts, or -1, if the substring
is not found.
Example:

#define RESERVE 100

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the symbol base currency and the profit currency
string symbol_currency_base =SymbolInfoString(Symbol(), SYMBOL_CURRENCY_BASE);
string symbol_currency_profit=SymbolInfoString(Symbol(), SYMBOL_CURRENCY_PROFIT);
PrintFormat("Symbol Currency Base: %s\nSymbol Currency Profit: %s", symbol_currency_base, symbol

//--- in the loop through all symbols available on the server


int total=SymbolsTotal(false), pos=-1;
for(int i=0; i<total; i++)
{
//--- get the name of the next symbol
string name=SymbolName(i, false);

//--- look for a substring in the symbol name with the name of the base currency and
//--- if a substring is found, display the symbol name, its index in the currency list and th
pos = StringFind(name, symbol_currency_base);
if(pos >= 0)

© 2000-2025, MetaQuotes Ltd.


1712 String Functions

PrintFormat("The '%s' symbol at index %u in the list contains the '%s' currency. Substring

//--- look for a substring in the symbol name with the name of the quoted currency and
//--- if a substring is found, display the symbol name, its index in the currency list and th
pos = StringFind(name, symbol_currency_profit);
if(pos >= 0)
PrintFormat("The '%s' symbol at index %u in the list contains the '%s' currency. Substring
}

/*
Result
StringFind (EURUSD,D1) Symbol Currency Base: EUR
StringFind (EURUSD,D1) Symbol Currency Profit: USD
The 'EURUSD' symbol at index 0 in the list contains the 'EUR' currency. Substring position in th
The 'EURUSD' symbol at index 0 in the list contains the 'USD' currency. Substring position in th
The 'GBPUSD' symbol at index 1 in the list contains the 'USD' currency. Substring position in th
The 'USDCHF' symbol at index 2 in the list contains the 'USD' currency. Substring position in th
The 'USDJPY' symbol at index 3 in the list contains the 'USD' currency. Substring position in th
The 'USDCNH' symbol at index 4 in the list contains the 'USD' currency. Substring position in th
The 'USDRUB' symbol at index 5 in the list contains the 'USD' currency. Substring position in th
The 'AUDUSD' symbol at index 6 in the list contains the 'USD' currency. Substring position in th
The 'NZDUSD' symbol at index 7 in the list contains the 'USD' currency. Substring position in th
The 'USDCAD' symbol at index 8 in the list contains the 'USD' currency. Substring position in th
The 'USDSEK' symbol at index 9 in the list contains the 'USD' currency. Substring position in th
The 'USDHKD' symbol at index 10 in the list contains the 'USD' currency. Substring position in t
The 'USDSGD' symbol at index 11 in the list contains the 'USD' currency. Substring position in t
The 'USDNOK' symbol at index 12 in the list contains the 'USD' currency. Substring position in t
The 'USDDKK' symbol at index 13 in the list contains the 'USD' currency. Substring position in t
The 'USDTRY' symbol at index 14 in the list contains the 'USD' currency. Substring position in t
The 'USDZAR' symbol at index 15 in the list contains the 'USD' currency. Substring position in t
The 'USDCZK' symbol at index 16 in the list contains the 'USD' currency. Substring position in t
The 'USDHUF' symbol at index 17 in the list contains the 'USD' currency. Substring position in t
The 'USDPLN' symbol at index 18 in the list contains the 'USD' currency. Substring position in t
The 'USDRUR' symbol at index 19 in the list contains the 'USD' currency. Substring position in t
The 'EURAUD' symbol at index 27 in the list contains the 'EUR' currency. Substring position in t
The 'EURCAD' symbol at index 28 in the list contains the 'EUR' currency. Substring position in t
The 'EURCHF' symbol at index 29 in the list contains the 'EUR' currency. Substring position in t
The 'EURCZK' symbol at index 30 in the list contains the 'EUR' currency. Substring position in t
The 'EURDKK' symbol at index 31 in the list contains the 'EUR' currency. Substring position in t
The 'EURGBP' symbol at index 32 in the list contains the 'EUR' currency. Substring position in t
The 'EURHKD' symbol at index 33 in the list contains the 'EUR' currency. Substring position in t
The 'EURHUF' symbol at index 34 in the list contains the 'EUR' currency. Substring position in t
The 'EURJPY' symbol at index 35 in the list contains the 'EUR' currency. Substring position in t
The 'EURNOK' symbol at index 36 in the list contains the 'EUR' currency. Substring position in t
The 'EURNZD' symbol at index 37 in the list contains the 'EUR' currency. Substring position in t
The 'EURPLN' symbol at index 38 in the list contains the 'EUR' currency. Substring position in t
The 'EURRUR' symbol at index 39 in the list contains the 'EUR' currency. Substring position in t
The 'EURRUB' symbol at index 40 in the list contains the 'EUR' currency. Substring position in t
The 'EURSEK' symbol at index 41 in the list contains the 'EUR' currency. Substring position in t

© 2000-2025, MetaQuotes Ltd.


1713 String Functions

The 'EURTRY' symbol at index 42 in the list contains the 'EUR' currency. Substring position in t
The 'EURZAR' symbol at index 43 in the list contains the 'EUR' currency. Substring position in t
The 'XAUUSD' symbol at index 47 in the list contains the 'USD' currency. Substring position in t
The 'XAUEUR' symbol at index 48 in the list contains the 'EUR' currency. Substring position in t
The 'XAGUSD' symbol at index 50 in the list contains the 'USD' currency. Substring position in t
The 'XAGEUR' symbol at index 51 in the list contains the 'EUR' currency. Substring position in t
The 'USDCRE' symbol at index 53 in the list contains the 'USD' currency. Substring position in t
The 'XPDUSD' symbol at index 65 in the list contains the 'USD' currency. Substring position in t
The 'XPTUSD' symbol at index 66 in the list contains the 'USD' currency. Substring position in t
The 'USDGEL' symbol at index 67 in the list contains the 'USD' currency. Substring position in t
The 'USDMXN' symbol at index 68 in the list contains the 'USD' currency. Substring position in t
The 'EURMXN' symbol at index 69 in the list contains the 'EUR' currency. Substring position in t
The 'USDCOP' symbol at index 75 in the list contains the 'USD' currency. Substring position in t
The 'USDARS' symbol at index 76 in the list contains the 'USD' currency. Substring position in t
The 'USDCLP' symbol at index 77 in the list contains the 'USD' currency. Substring position in t
The 'EURSGD' symbol at index 89 in the list contains the 'EUR' currency. Substring position in t
The 'USDILS' symbol at index 95 in the list contains the 'USD' currency. Substring position in t
The 'USDTHB' symbol at index 122 in the list contains the 'USD' currency. Substring position in
The 'USDRMB' symbol at index 123 in the list contains the 'USD' currency. Substring position in
The 'EURILS' symbol at index 126 in the list contains the 'EUR' currency. Substring position in
The 'EURCNH' symbol at index 137 in the list contains the 'EUR' currency. Substring position in
The 'USDBRL' symbol at index 139 in the list contains the 'USD' currency. Substring position in
*/
}

See also

S tring S ubstr, S tring GetCharacter, S tringLen, S tringLen

© 2000-2025, MetaQuotes Ltd.


1714 String Functions

StringGetCharacter
R eturns value of a symbol, located in the specified position of a string.
ushort StringGetCharacter(
string string_value, // string
int pos // symbol position in the string
);

Parameters
string_value
[in] S tring.

pos
[in] Position of a symbol in the string. Can be from 0 to S tringLen(text) -1.

Return Value

S ymbol code or 0 in case of an error. To get the error code call GetLastError().
Example:

void OnStart()
{
//--- delete all comments on the chart
Comment("");
//--- declare a string, from which we will obtain the values of symbol codes and remember the strin
string message = "The script demonstrates the operation of the StringGetCharacter() function";
int length = StringLen(message);
//--- declare a string variable, to which we will add the obtained symbols from the demo string
string text = "";
//--- in the loop by the demo string length
for(int i=0; i<length; i++)
{
//--- wait 1/10 seconds
Sleep(100);
//--- get a symbol from a string located at the loop index in the demo string
ushort char_code=StringGetCharacter(message, i);
//--- add a symbol to the displayed string and display the resulting string as a chart commen
text+=ShortToString(char_code);
Comment(text);
}
//--- wait two seconds and remove the comment from the chart
Sleep(2000);
Comment("");

/*
Result: the demo string appears on the screen character by character
The script demonstrates the operation of the StringGetCharacter() function
*/

© 2000-2025, MetaQuotes Ltd.


1715 String Functions

See also

S tring S etCharacter, S tring BufferLen, S tringLen, S tring Fill, S tringInit, S tringToCharArray,


S tringToS hortArray

© 2000-2025, MetaQuotes Ltd.


1716 String Functions

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
ushort character=0 // symbol, by which the string will be filled
);

Parameters
string_var
[in][out] S tring that should be initialized and deinitialized.
new_len=0
[in] S tringlength 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] S ymbol to fill the string.

Return 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
S tring BufferLen, S tringLen

© 2000-2025, MetaQuotes Ltd.


1717 String Functions

StringLen
R eturns the number of symbols in a string.
int StringLen(
string string_value // string
);

Parameters
string_value
[in] S tring to calculate length.

Return Value

Number of symbols in a string without the ending zero.


Example:

void OnStart()
{
//--- define the test string
string text="123456789012345";
//--- get the number of symbols in the string
int str_len=StringLen(text);
//--- display the string and the number of symbols in it in the log
PrintFormat("The StringLen() function returned the value of %d chars in string: '%s'", str_len,

/*
Result
The StringLen() function returned the value of 15 chars in string: '123456789012345'
*/
}

See also

S tring BufferLen, S tringTrimLeft, S tringTrimR ight, S tringToCharArray, S tringToS hortArray

© 2000-2025, MetaQuotes Ltd.


1718 String Functions

StringSetLength
S ets a specified length (in characters) for a string.
bool StringSetLength(
string& string_var, // string
uint new_length // new string length
);

Parameters
string_var
[in][out] S tring, for which a new length in characters should be set.
new_capacity
[in] R equired stringlength in characters. If new_length is less than the current size, the excessive
characters are discarded.

Return Value

In case of successful execution, returns true, otherwise - false. To receive an error code, the
GetLastError() function should be called.

Note

TheS tringS etLength() function does not change the size of the buffer allocated for a string.
Example:

void OnStart()
{
//--- define the string
string text="123456789012345";

//--- display a string and its length in the log


PrintFormat("Before StringSetLength() the string '%s' has a size of %d characters", text, String

//--- reduce the string size to 10 characters


StringSetLength(text, 10);

//--- display a string, changed due to StringSetLength() operation, and its new length to the log
PrintFormat("After StringSetLength() the string is now '%s', and has a size of %d characters", t

/*
Result
Before StringSetLength() the string '123456789012345' has a size of 15 characters
After StringSetLength() the string is now '1234567890', and has a size of 10 characters
*/
}

See also

S tringLen, S tring BufferLen, S tring R eserve S tringInit, S tring S etCharacter

© 2000-2025, MetaQuotes Ltd.


1719 String Functions

StringReplace
It replaces all the found substrings of a string by a set sequence of symbols.
int StringReplace(
string& str, // the string in which substrings will be replaced
const string find, // the searched substring
const string replacement // the substring that will be inserted to the found positions
);

Parameters
str
[in][out] The string in which you are going to replace substrings.
find
[in] The desired substring to replace.
replacement
[in] The string that will be inserted instead of the found one.

Return Value

The function returns the number of replacements in case of success, otherwise -1. To get an error
code call the GetLastError() function.
Note

If the function has run successfully but no replacements have been made (the substring to replace
was not found), it returns 0.
The error can result from incorrect str or find parameters (empty or non-initialized string, see
S tringInit() ). Besides, the error occurs if there is not enough memory to complete the replacement.

Example:

string text="The quick brown fox jumped over the lazy dog.";
int replaced=StringReplace(text,"quick","slow");
replaced+=StringReplace(text,"brown","black");
replaced+=StringReplace(text,"fox","bear");
Print("Replaced: ", replaced,". Result=",text);

// Result
// Replaced: 3. Result=The slow black bear jumped over the lazy dog.
//

See also
S tring S etCharacter(), S tring S ubstr()

© 2000-2025, MetaQuotes Ltd.


1720 String Functions

StringReserve
R eserves the buffer of a specified size for a string in memory.
bool StringReserve(
string& string_var, // string
uint new_capacity // buffer size for storing a string
);

Parameters
string_var
[in][out] S tring the buffer size should change the size for.
new_capacity
[in] Buffer size required for a string. If the new_capacity size is less than the string length, the
size of the current buffer does not change.

Return Value

In case of successful execution, returns true, otherwise - false. To receive an error code, the
GetLastError() function should be called.

Note

Generally, the string size is not equal to the size of the buffer meant for storing the string. W hen
creating a string, the appropriate buffer is usually allocated with a margin. The S tringReserve()
function allows managing the buffer size and specify the optimal size for future operations.
Unlik e S tringInit(), the S tringReserve() function does not change the string contents and does not fill
it with characters.
Example:

void OnStart()
{
string s;
//--- check the operation speed without using StringReserve
ulong t0=GetMicrosecondCount();
for(int i=0; i< 1024; i++)
s+=" "+(string)i;
ulong msc_no_reserve=GetMicrosecondCount()-t0;
s=NULL;
//--- now, let's do the same using StringReserve
StringReserve(s,1024 * 3);
t0=GetMicrosecondCount();
for(int i=0; i< 1024; i++)
s+=" "+(string)i;
ulong msc_reserve=GetMicrosecondCount()-t0;
//--- check the time
Print("Test with StringReserve passed for "+(string)msc_reserve+" msc");
Print("Test without StringReserve passed for "+(string)msc_no_reserve+" msc");
/* Result

© 2000-2025, MetaQuotes Ltd.


1721 String Functions

Test with StringReserve passed for 50 msc


Test without StringReserve passed for 121 msc
*/
}

See also
S tring BufferLen, S tring S etLength, S tringInit, S tring S etCharacter

© 2000-2025, MetaQuotes Ltd.


1722 String Functions

StringSetCharacter
R eturns copy of a string with a changed character in a specified position.
bool StringSetCharacter(
string& string_var, // string
int pos, // position
ushort character // character
);

Parameters
string_var
[in][out] S tring.

pos
[in] Position of a character in a string. Can be from 0 to S tringLen(text).
character
[in] S ymbol code Unicode.

Return Value

In case of success returns true, otherwise false. In order to get an error code, the GetLastError()
function should be called.
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 string remains 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

© 2000-2025, MetaQuotes Ltd.


1723 String Functions

after: str = 012345 ,StringBufferLen(str) = 16 StringLen(str) = 6


addition: str = 012345+ ,StringBufferLen(str) = 16 StringLen(str) = 7
*/

See also
S tring BufferLen, S tringLen, S tring Fill, S tringInit, CharToS tring, S hortToS tring, CharArrayToS tring,
S hortArrayToS tring

© 2000-2025, MetaQuotes Ltd.


1724 String Functions

StringSplit
Gets substrings by a specified separator from the specified string, returns the number of substrings
obtained.
int StringSplit(
const string string_value, // A string to search in
const ushort separator, // A separator using which substrings will be searched
string & result[] // An array passed by reference to get the found substrings
);

Parameters
string_value
[in] The string from which you need to get substrings. The string will not change.
pos
[in] The code of the separator character. To get the code, you can use the S tringGetCharacter()
function.
result[]
[out] An array of strings where the obtained substrings are located.

Return Value

The number of substrings in the result[] array. If the separator is not found in the passed string,
only one source string will be placed in the array.
If string_value is empty or NULL, the function will return zero. In case of an error the function
returns -1. To get the error code, call the GetLastError() function.
Example:

string to_split="_life_is_good_"; // A string to split into substrings


string sep="_"; // A separator as a character
ushort u_sep; // The code of the separator character
string result[]; // An array to get strings
//--- Get the separator code
u_sep=StringGetCharacter(sep,0);
//--- Split the string to substrings
int k=StringSplit(to_split,u_sep,result);
//--- Show a comment
PrintFormat("Strings obtained: %d. Used separator '%s' with the code %d",k,sep,u_sep);
//--- Now output all obtained strings
if(k>0)
{
for(int i=0;i<k;i++)
{
PrintFormat("result[%d]=\"%s\"",i,result[i]);
}
}

© 2000-2025, MetaQuotes Ltd.


1725 String Functions

See also
S tring R eplace(), S tring S ubstr(), S tringConcatenate()

© 2000-2025, MetaQuotes Ltd.


1726 String Functions

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] S tring to extract a substring from.
start_pos
[in] Initial position of a substring. Can be from 0 to S tringLen(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.

Return Value

Copy of a extracted substring, if possible. Otherwise returns an empty string.


Example:

void OnStart()
{
//--- get the name of the current symbol
string name = Symbol();

//--- get the base and quoted symbol currencies


string base = StringSubstr(name, 0, 3);
string quoted = StringSubstr(name, 3, 3);

//--- display the obtained symbol currencies in the log


PrintFormat("Symbol: %s. Currency base: %s, currency quoted: %s", name, base, quoted);

/*
Result
Symbol: EURUSD. Currency base: EUR, currency quoted: USD
*/
}

See also

S tring S plit, S tring Find, S tring GetCharacter

© 2000-2025, MetaQuotes Ltd.


1727 String Functions

StringToLower
Transforms all symbols of a selected string into lowercase.
bool StringToLower(
string& string_var // string to process
);

Parameters
string_var
[in][out] S tring.

Return Value

In case of success returns true, otherwise - false. To get the error code call GetLastError().
Example:

void OnStart()
{
//--- define the source string in uppercase
string text=" - THIS STRING, WRITTEN IN UPPERCASE, MUST BE WRITTEN IN LOWERCASE";
//--- Display the source string in the log
Print("Source line:\n", text);
//--- convert all string characters to lowercase and display the result in the log
if(StringToLower(text))
Print("The original string after using the StringToLower() function:\n", text);

/*
Result
Source line:
- THIS STRING, WRITTEN IN UPPERCASE, MUST BE WRITTEN IN LOWERCASE
The original string after using the StringToLower() function:
- this string, written in uppercase, must be written in lowercase
*/
}

See also

S tringToUpper, S tringTrimLeft, S tringTrimR ight

© 2000-2025, MetaQuotes Ltd.


1728 String Functions

StringToUpper
Transforms all symbols of a selected string into capitals.
bool StringToUpper(
string& string_var // string to process
);

Parameters
string_var
[in][out] S tring.

Return Value

In case of success returns true, otherwise - false. To get the error code call GetLastError().
Example:

void OnStart()
{
//--- define the source string in lowercase
string text=" - this string, written in lowercase, must be written in uppercase";
//--- Display the source string in the log
Print("Source line:\n", text);
//--- convert all string characters to uppercase and display the result in the log
if(StringToUpper(text))
Print("The original string after using the StringToUpper() function:\n", text);

/*
Result
Source line:
- this string, written in lowercase, must be written in uppercase
The original string after using the StringToUpper() function:
- THIS STRING, WRITTEN IN LOWERCASE, MUST BE WRITTEN IN UPPERCASE
*/
}

See also

S tringToLower, S tringTrimLeft, S tringTrimR ight

© 2000-2025, MetaQuotes Ltd.


1729 String Functions

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] S tring that will be cut from the left.

Return Value

R eturns the number of cut symbols.


Example:

void OnStart()
{
//--- define the source string with six spaces on the left
string text=" All spaces on the left will be removed from this string";
//--- Display the source string in the log
PrintFormat("Source line:\n'%s'", text);
//--- remove all spaces on the left and display the number of removed characters and the resulting
int num=StringTrimLeft(text);
PrintFormat("The StringTrimLeft() function removed %d chars from the left side. Now the line loo

/*
Result
Source line:
' All spaces on the left will be removed from this string'
The StringTrimLeft() function removed 6 chars from the left side. Now the line looks like this:
'All spaces on the left will be removed from this string'
*/
}

See also

S tringTrimR ight, S tringToLower, S tringToUpper

© 2000-2025, MetaQuotes Ltd.


1730 String Functions

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] S tring that will be cut from the right.

Return Value

R eturns the number of cut symbols.


Example:

void OnStart()
{
//--- define the source string with six spaces on the right
string text="All spaces on the right will be removed from this string ";
//--- Display the source string in the log
PrintFormat("Source line:\n'%s'", text);
//--- remove all spaces on the right and display the number of removed characters and the resulting
int num=StringTrimRight(text);
PrintFormat("The StringTrimRight() function removed %d chars from the right side. Now the line l

/*
Result
Source line:
'All spaces on the right will be removed from this string '
The StringTrimRight() function removed 6 chars from the right side. Now the line looks like this
'All spaces on the right will be removed from this string'
*/
}

See also

S tringTrimLeft, S tringToLower, S tringToUpper

© 2000-2025, MetaQuotes Ltd.


1731 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).
To arrange high-resolution counters and timers, use the GetTickCount() function, which produces
values in milliseconds.

Function Action

TimeCurrent R eturnsthe last known server time (time of the last quote receipt) in
the datetime format
TimeTradeS erver R eturns the current calculation time of the trade server
TimeLocal R eturns the local computer time in datetime format
TimeGMT R eturns GMT in datetime format with the Daylight S aving Time by local
time of the computer, where the client terminal is running
TimeDaylightS avings R eturns the sign of Daylight S aving Time switch
TimeGMTOffset R eturns the current difference between GMT time and the local computer
time in seconds, taking into account DS T switch
TimeToS truct Converts a datetime value into a variable of M qlDateTime structure type
S tructToTime Converts a variable of M qlDateTime structure type into a datetime value

© 2000-2025, MetaQuotes Ltd.


1732 Date and Time

TimeCurrent
R eturns the last k nown server time, time of the last quote receipt for one of the symbols selected in
the " Market W atch" 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 W atch" 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] M qlDateTime structure type variable.

Return Value

Value of datetime type


Note

If the M qlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function, which produces
values in milliseconds.
During testing in the strategy tester, TimeCurrent() is simulated according to historical data.
Example:

void OnStart()
{
//--- declare the MqlDateTime variable to be filled with date/time data and get the time of the las
MqlDateTime tm={};
datetime time1=TimeCurrent(); // first form of call: time of the last quote for one of the
datetime time2=TimeCurrent(tm); // second form of call: time of the last quote for one of th

//--- display the result of receiving the date/time and filling the structure with the correspondin
PrintFormat("Tick time: %s\n- Year: %u\n- Month: %02u\n- Day: %02u\n- Hour: %02u\n- Min: %02u\n-
(string)time1, tm.year, tm.mon, tm.day, tm.hour, tm.min, tm.sec, tm.day_of_year, tm.
/*
result:
Tick time: 2024.04.18 15:40:06
- Year: 2024
- Month: 04

© 2000-2025, MetaQuotes Ltd.


1733 Date and Time

- Day: 18
- Hour: 15
- Min: 40
- Sec: 06
- Day of Year: 108
- Day of Week: 4 (THURSDAY)
*/
}

© 2000-2025, MetaQuotes Ltd.


1734 Date and Time

TimeTradeServer
R eturnsthe 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 M qlDateTime.

Return Value

Value of datetime type


Note

If the M qlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function, which produces
values in milliseconds.
During testing in the strategy tester, TimeTradeS erver() is simulated according to historical data
and always equal to TimeCurrent().
Example:

void OnStart()
{
//--- declare the MqlDateTime variable to be filled with date/time data and get the time of the las
MqlDateTime tm={};
datetime time_current=TimeCurrent(); // first form of call: time of the last
datetime time_server =TimeTradeServer(tm); // second form of call: estimated curre
int difference =int(time_current-time_server); // difference between Time Current and

//--- display the time of the last quote and the estimated current time of the trade server with th
PrintFormat("Time Current: %s\nTime Trade Server: %s\n- Year: %u\n- Month: %02u\n- Day: %02u\n"+
"- Hour: %02u\n- Min: %02u\n- Sec: %02u\n- Day of Year: %03u\n- Day of Week: %u (%s)
(string)time_current, (string)time_server, tm.year, tm.mon, tm.day, tm.hour, tm.min,
EnumToString((ENUM_DAY_OF_WEEK)tm.day_of_week), difference);
/*
result:
Time Current: 2024.04.18 16:10:14
Time Trade Server: 2024.04.18 16:10:15

© 2000-2025, MetaQuotes Ltd.


1735 Date and Time

- Year: 2024
- Month: 04
- Day: 18
- Hour: 16
- Min: 10
- Sec: 15
- Day of Year: 108
- Day of Week: 4 (THURSDAY)
Difference between Time Current and Time Trade Server: -1
*/
}

© 2000-2025, MetaQuotes Ltd.


1736 Date and Time

TimeLocal
R eturnsthe 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 M qlDateTime.

Return Value

Value of datetime type


Note

If the M qlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function, which produces
values in milliseconds.
During testing in the strategy tester, TimeLocal() is always equal to TimeCurrent() simulated server
time.
Example:

void OnStart()
{
//--- declare the MqlDateTime variable to be filled with PC local time data
MqlDateTime tm={};
datetime time1=TimeLocal(); // first form of call: PC local time
datetime time2=TimeLocal(tm); // second form of call: PC local time with filling the MqlDateT

//--- display the result of receiving PC local time and filling the structure with the correspondin
PrintFormat("Local time: %s\n- Year: %u\n- Month: %02u\n- Day: %02u\n- Hour: %02u\n- Min: %02u\n
(string)time1, tm.year, tm.mon, tm.day, tm.hour, tm.min, tm.sec, tm.day_of_year, tm.
/*
result:
Local time: 2024.04.18 19:44:09
- Year: 2024
- Month: 04
- Day: 18
- Hour: 19
- Min: 44

© 2000-2025, MetaQuotes Ltd.


1737 Date and Time

- Sec: 09
- Day of Year: 108
- Day of Week: 4 (THURSDAY)
*/
}

© 2000-2025, MetaQuotes Ltd.


1738 Date and Time

TimeGMT
R eturns
the GMT, which is calculated taking into account the DS T 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 M qlDateTime.

Return Value

Value of datetime type


Note

If the M qlDateTime structure type variable has been passed as a parameter, it is filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function, which produces
values in milliseconds.
During testing in the strategy tester, TimeGMT() is always equal to TimeTradeS erver() simulated
server time.
Example:

void OnStart()
{
//--- declare the MqlDateTime variable to be filled with date/time data and get the PC local time a
MqlDateTime tm={};
datetime time1=TimeLocal(); // first form of call: PC local time
datetime time2=TimeGMT(tm); // second form of call: GMT calculated from the PC loc
int shift=int(time1-time2)/3600; // local time offset relative to GMT

//--- display local time and GMT with the data of the filled MqlDateTime structure in the log
PrintFormat("Time Local: %s\nTime GMT: %s\n- Year: %u\n- Month: %02u\n- Day: %02u\n"+
"- Hour: %02u\n- Min: %02u\n- Sec: %02u\n- Day of Year: %03u\n- Day of Week: %u (%s)
(string)time1, (string)time2, tm.year, tm.mon, tm.day, tm.hour, tm.min, tm.sec, tm.d
EnumToString((ENUM_DAY_OF_WEEK)tm.day_of_week), shift);
/*
result:
Time Local: 2024.04.18 19:37:23
Time GMT: 2024.04.18 12:37:23
- Year: 2024

© 2000-2025, MetaQuotes Ltd.


1739 Date and Time

- Month: 04
- Day: 18
- Hour: 12
- Min: 37
- Sec: 23
- Day of Year: 108
- Day of Week: 4 (THURSDAY)
Local time offset relative to GMT: +7
*/
}

© 2000-2025, MetaQuotes Ltd.


1740 Date and Time

TimeDaylightSavings
R eturnscorrection for daylight saving time in seconds, if the switch to summer time has been made.
It depends on the time settings of your computer.
int TimeDaylightSavings();

Return Value

If switch to winter (standard) time has been made, it returns 0.


Example:

void OnStart()
{
//--- get daylight saving time adjustment in seconds
int sec_dl=TimeDaylightSavings();

//--- create the text describing the received value


string text=(sec_dl==0 ? "Standard \"winter\" time is used" :
StringFormat("Daylight saving time has been switched over. The correction is %d sec

//--- display a description of the daylight saving time adjustment in seconds in the log
Print(text);
/*
result for "winter" time:
Standard "winter" time is used

result for "summer" time:


Daylight saving time has been switched over. The correction is -3600 seconds
*/
}

© 2000-2025, MetaQuotes Ltd.


1741 Date and Time

TimeGMTOffset
R eturnsthe current difference between GMT time and the local computer time in seconds, taking into
account switch to winter or summer time. Depends on the time settings of your computer.
int TimeGMTOffset();

Return Value

The value of int type, representing the current difference between GMT time and the local time of
the computer TimeLocal in seconds.
TimeGMTOffset() = TimeGMT() - TimeLocal()
Example:

void OnStart()
{
//--- get local time, GMT and the difference between GMT and local computer time in seconds
datetime time_local=TimeLocal();
datetime time_gmt =TimeGMT();
int offset =TimeGMTOffset();

//--- show the obtained time and offset values in the log
PrintFormat("Local Time: %s, GMT Time: %s, Seconds Offset: %+d", (string)time_local, (string)tim
/*
result:
Local Time: 2024.04.18 19:35:52, GMT Time: 2024.04.18 12:35:52, Seconds Offset: -25200
*/
}

© 2000-2025, MetaQuotes Ltd.


1742 Date and Time

TimeToStruct
Converts a value of datetime type (number of seconds since 01.01.1970) into a structure variable
M qlDateTime.
bool 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 M qlDateTime.

Return Value

True if successful, otherwise false. To get information about the error, call the GetLastError()
function.
Example:

void OnStart()
{
//--- get the last known time of the server, declare the date/time structure and fill in the struct
datetime time=TimeCurrent();
MqlDateTime tm ={};
if(!TimeToStruct(time,tm))
Print("TimeToStruct() failed. Error ", GetLastError());

//--- display the obtained server time and the result of filling the MqlDateTime structure using Ti
PrintFormat("Server time: %s\n- Year: %u\n- Month: %02u\n- Day: %02u\n- Hour: %02u\n- Min: %02u\
(string)time, tm.year, tm.mon, tm.day, tm.hour, tm.min, tm.sec, tm.day_of_year, tm.d
/*
result:
Server time: 2024.04.18 15:47:27
- Year: 2024
- Month: 04
- Day: 18
- Hour: 15
- Min: 47
- Sec: 27
- Day of Year: 108
- Day of Week: 4 (THURSDAY)
*/
}

© 2000-2025, MetaQuotes Ltd.


1743 Date and Time

StructToTime
Converts a structure variable M qlDateTime 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 M qlDateTime.

Return Value

The value of datetime type containing the number of seconds since 01.01.1970.
Example:

#property script_show_inputs

input int InpYear = 0; // Year


input int InpMonth = 0; // Month
input int InpDay = 0; // Day
input int InpHour = 0; // Hour
input int InpMin = 0; // Minutes
input int InpSec = 0; // Seconds

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- adjust the entered values and write them to variables
int year = (InpYear<1970 ? 1970 : InpYear); // If the year entered is less than 1970, then 1970
int month= (InpMonth<1 ? 1 : InpMonth > 12 ? 12 : InpMonth);
int day = (InpDay <1 ? 1 : InpDay > 31 ? 31 : InpDay);
int hour = (InpHour <0 ? 0 : InpHour > 23 ? 23 : InpHour);
int min = (InpMin <0 ? 0 : InpMin > 59 ? 59 : InpMin);
int sec = (InpSec <0 ? 0 : InpSec > 59 ? 59 : InpSec);

//--- display the entered values in the log


PrintFormat("Entered date and time: %04u.%02u.%02u %02u:%02u:%02u", InpYear, InpMonth, InpDay, I

//--- display the adjusted entered values in the log


PrintFormat("Corrected date and time: %04u.%02u.%02u %02u:%02u:%02u", year, month, day, hour, mi

//--- write the input values to the corresponding structure fields


MqlDateTime time_struct={};
time_struct.year= year;

© 2000-2025, MetaQuotes Ltd.


1744 Date and Time

time_struct.mon = month;
time_struct.day = day;
time_struct.hour= hour;
time_struct.min = min;
time_struct.sec = sec;

//--- convert the date and time from the structure into a variable of datetime type and
datetime time = StructToTime(time_struct);

//--- display the result of conversion from an MqlDateTime structure type variable to a datetime ty
Print("Converted date and time: ",TimeToString(time,TIME_DATE|TIME_MINUTES|TIME_SECONDS));
/*
results if zero default values are entered:
Entered date and time: 0000.00.00 00:00:00
Corrected date and time: 1970.01.01 00:00:00
Converted date and time: 1970.01.01 00:00:00

results if the wrong day of the current year's February is entered:


Entered date and time: 2024.02.31 00:00:00
Corrected date and time: 2024.02.31 00:00:00
Converted date and time: 2024.03.02 00:00:00
*/
}

© 2000-2025, MetaQuotes Ltd.


1745 Account Information

Account Information
Functions that return parameters of the current account.

Function Action

AccountInfoDouble R eturns a value of double type of the corresponding account


property
AccountInfoInteger R eturns a value of integer type (bool, int or long) of the
corresponding account property
AccountInfoS tring R eturns a value string type corresponding account property

© 2000-2025, MetaQuotes Ltd.


1746 Account Information

AccountInfoDouble
R eturns the value of the appropriate account property.
double AccountInfoDouble(
ENUM_ACCOUNT_INFO_DOUBLE property_id // Property identifier
);

Parameters
property_id
[in] Property identifier. The value can be one of the values of ENUM _ACCOUNT_INFO_DOUBLE.

Return 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_MARGIN_FREE = %G",AccountInfoDouble(ACCOUNT_MARGIN_FREE));
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
S ymbolInfoDouble, S ymbolInfoS tring, S ymbolInfoInteger, PrintFormat

© 2000-2025, MetaQuotes Ltd.


1747 Account Information

AccountInfoInteger
R eturns the value of the appropriate account property.
long AccountInfoInteger(
ENUM_ACCOUNT_INFO_INTEGER property_id // Identifier of the property
);

Parameters
property_id
[in] Property identifier. The value can be one of the values of ENUM _ACCOUNT_INFO_INTEGER.

Return Value

Value of long type.


Note

The property must be of bool, int or long type.


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=(ENUM_ACCOUNT_TRADE_MODE)AccountInfoInteger(ACCOUNT_TRADE_MODE
ENUM_ACCOUNT_STOPOUT_MODE stopOutMode=(ENUM_ACCOUNT_STOPOUT_MODE)AccountInfoInteger(ACCOUNT_MARG

//--- 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):

© 2000-2025, MetaQuotes Ltd.


1748 Account Information

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

© 2000-2025, MetaQuotes Ltd.


1749 Account Information

AccountInfoString
R eturns the value of the appropriate account property.
string AccountInfoString(
ENUM_ACCOUNT_INFO_STRING property_id // Property identifier
);

Parameters
property_id
[in] Property identifier. The value can be one of the values of ENUM _ACCOUNT_INFO_S TRING.

Return 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

© 2000-2025, MetaQuotes Ltd.


1750 Checkup

State Checking
Functions that return parameters of the current state of the client terminal

Function Action

GetLastError R eturns the last error


Is S topped R eturnstrue, if an mql5 program has been commanded to stop its
operation
UninitializeR eason R eturns the code of the reason for deinitialization
TerminalInfoInteger R eturnsan integer value of a corresponding property of the mql5
program environment
TerminalInfoDouble R eturnsa double value of a corresponding property of the mql5
program environment
TerminalInfoS tring R eturns
a string value of a corresponding property of the mql5 program
environment
MQLInfoInteger R eturns an integer value of a corresponding property of a running mql5
program
MQLInfoS tring R eturns a string value of a corresponding property of a running mql5
program
S ymbol R eturns the name of a symbol of the current chart
Period R eturns the current chart timeframe
Digits R eturns the number of decimal digits determining the accuracy of the
price value of the current chart symbol
Point R eturns the point size of the current symbol in the quote currency

© 2000-2025, MetaQuotes Ltd.


1751 Checkup

GetLastError
R eturns the contents of the system variable _LastError.
int GetLastError();

Return Value

R eturns 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().
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
MqlRates rates[1]={}; // display the current bar data here

//--- intentionally call a function with inappropriate parameters


int res=CopyRates(NULL, PERIOD_CURRENT, 0, 2, rates);
if(res!=2)
PrintFormat("CopyRates() returned %d. LastError %d", res, GetLastError());

//--- reset the last error code before copying the current bar data to the MqlRates structure
ResetLastError();
//--- if the function does not work correctly, the error code will differ from 0
CopyRates(NULL, PERIOD_CURRENT, 0, 1, rates);
Print("CopyRates() error ", GetLastError());

//--- print the array of obtained values


ArrayPrint(rates);
}

See also

Trade S erver Return Codes

© 2000-2025, MetaQuotes Ltd.


1752 Checkup

IsStopped
Checks the forced shutdown of an mql5 program.
bool IsStopped();

Return Value

R eturns true, if the _S topFlag system variable contains a value other than 0. A nonzero value is
written into _S topFlag, 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.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- in an endless loop with a stop check
while(!IsStopped())
{
//--- display the local PC time on the chart
Comment("Time Local: ", TimeToString(TimeLocal(), TIME_DATE|TIME_MINUTES|TIME_SECONDS));
Sleep(16);
}
Print("The StopFlag is set. The program will be stopped.");

//--- clean up
Comment("");
}

© 2000-2025, MetaQuotes Ltd.


1753 Checkup

UninitializeReason
R eturns the code of a reason for deinitialization.
int UninitializeReason();

Return Value

R eturnsthe value of _UninitReason which is formed before OnDeinit() is called. Value depends on
the reasons that led to deinitialization.
Example:

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- get the deinitialization reason code into the 'reason' variable
int reason=UninitializeReason();
//--- create a message string with a deinitialization reason and send the message to the journal
string message=StringFormat("%s: Uninitialize reason code: %d (%s)",__FUNCTION__, reason, Uninit
Print(message);
//--- successful
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- create a message string with a deinitialization reason code from the 'reason' formal variable
string message=StringFormat("%s: Uninitialize reason code: %d (%s)",__FUNCTION__, reason, Uninit
Print(message);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
}
//+------------------------------------------------------------------+
//| Return a description of the deinitialization reason code |
//+------------------------------------------------------------------+
string UninitializeReasonDescription(const int reason)
{
switch(reason)
{
//--- the EA has stopped working calling the ExpertRemove() function
case REASON_PROGRAM :

© 2000-2025, MetaQuotes Ltd.


1754 Checkup

return("Expert Advisor terminated its operation by calling the ExpertRemove() function");


//--- program removed from a chart
case REASON_REMOVE :
return("Program has been deleted from the chart");
//--- program recompiled
case REASON_RECOMPILE :
return("Program has been recompiled");
//--- symbol or chart period changed
case REASON_CHARTCHANGE :
return("Symbol or chart period has been changed");
//--- chart closed
case REASON_CHARTCLOSE :
return("Chart has been closed");
//--- inputs changed by user
case REASON_PARAMETERS :
return("Input parameters have been changed by a user");
//--- another account has been activated or reconnection to the trade server has occurred due
case REASON_ACCOUNT :
return("Another account has been activated or reconnection to the trade server has occurred
//--- another chart template applied
case REASON_TEMPLATE :
return("A new template has been applied");
//--- OnInit() handler returned a non-zero value
case REASON_INITFAILED :
return("This value means that OnInit() handler has returned a nonzero value");
//--- terminal closed
case REASON_CLOSE :
return("Terminal has been closed");
}

//--- deinitialization reason unknown


return("Unknown reason");
}

© 2000-2025, MetaQuotes Ltd.


1755 Checkup

TerminalInfoInteger
R eturns 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 of the values of the ENUM _T ER MINAL _INFO_INT EGER
enumeration.

Return Value

Value of int type.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the build number of the running terminal and its "64-bit terminal" property
int build = TerminalInfoInteger(TERMINAL_BUILD);
bool x64 = TerminalInfoInteger(TERMINAL_X64);

//--- print the obtained terminal data in the journal


PrintFormat("MetaTrader 5 %s build %d", (x64 ? "x64" : "x32"), build);
/*
result:
MetaTrader 5 x64 build 4330
*/
}

© 2000-2025, MetaQuotes Ltd.


1756 Checkup

TerminalInfoDouble
R eturns the value of a corresponding property of the mql5 program environment.
double TerminalInfoDouble(
int property_id // identifier of a property
);

Parameters
property_id
[in]Identifier of a property. Can be one of the values of the ENUM _T ER MINAL _INFO_DOUBL E
enumeration.

Return Value

Value of double type.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the build number of the running terminal and its "64-bit terminal" property
int build = TerminalInfoInteger(TERMINAL_BUILD);
bool x64 = TerminalInfoInteger(TERMINAL_X64);

//--- print the obtained terminal data in the journal


PrintFormat("MetaTrader 5 %s build %d", (x64 ? "x64" : "x32"), build);
/*
result:
MetaTrader 5 x64 build 4330
*/
}

© 2000-2025, MetaQuotes Ltd.


1757 Checkup

TerminalInfoString
R eturns 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. Can be one of the values of the ENUM _T ER MINAL _INFO_S T R ING
enumeration.

Return Value

Value of string type.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get OS and terminal data
string os_ver = TerminalInfoString(TERMINAL_OS_VERSION); // user's OS
string name = TerminalInfoString(TERMINAL_NAME); // terminal name
string path = TerminalInfoString(TERMINAL_PATH); // folder the terminal is launche
string data = TerminalInfoString(TERMINAL_DATA_PATH); // folder for storing the termina
string common = TerminalInfoString(TERMINAL_COMMONDATA_PATH); // common folder for all client t

//--- send the obtained data to the journal


PrintFormat("OS: %s\nTerminal: %s\n- Path: %s\n- Data path: %s\n- Common Data path: %s", os_ver,
/*
OS: Windows 10 build 19045
Terminal: MetaTrader 5
- Path: E:\MetaQuotes\MetaTrader 5
- Data path: E:\MetaQuotes\MetaTrader 5
- Common Data path: C:\Users\admin\AppData\Roaming\MetaQuotes\Terminal\Common
*/
}

© 2000-2025, MetaQuotes Ltd.


1758 Checkup

MQLInfoInteger
R eturns the value of a corresponding property of a running mql5 program.
int MQLInfoInteger(
int property_id // identifier of a property
);

Parameters
property_id
[in] Identifier of a property. Can be one of values of the ENUM _MQL_INFO_INTEGER enumeration.

Return Value

Value of int type.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the values of available and consumed memory for the MQL program
int limit = MQLInfoInteger(MQL_MEMORY_LIMIT); // maximum possible amount of dynamic memory for
int used = MQLInfoInteger(MQL_MEMORY_USED); // memory size used by MQL5 program in MB

//--- send the received values to the journal


PrintFormat("Maximum possible amount of dynamic memory for MQL5 program: %d Mb\n"+
"Memory used by MQL5 program: %d Mb", limit, used);
/*
result
Maximum possible amount of dynamic memory for MQL5 program: 8388608 Mb
Memory used by MQL5 program: 2 Mb
*/
}

© 2000-2025, MetaQuotes Ltd.


1759 Checkup

MQLInfoString
R eturns the value of a corresponding property of a running mql5 program.
string MQLInfoString(
int property_id // Identifier of a property
);

Parameters
property_id
[in] Identifier of a property. Can be one of the ENUM _MQL_INFO_S TRING enumeration.

Return Value

Value of string type.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the launched program data
string name = MQLInfoString(MQL_PROGRAM_NAME); // name of the launched MQL5 program
string path = MQLInfoString(MQL_PROGRAM_PATH); // running program path

//--- send the obtained data to the journal


PrintFormat("Name of the running MQL program: '%s'\nPath of the running MQL program: %s", name,
/*
result:
Name of the running MQL program: 'MQLInfoString'
Path of the running MQL program: E:\MetaQuotes\MetaTrader 5\MQL5\Scripts\MQLInfoString.ex5
*/
}

© 2000-2025, MetaQuotes Ltd.


1760 Checkup

Symbol
R eturns the name of a symbol of the current chart.
string Symbol();

Return Value

Value of the _S ymbol system variable, which stores the name of the current chart symbol.
Note

Unlik e Expert Advisors, indicators and scripts, services are not bound to a specific chart. Therefore,
S ymbol() returns an empty string ("" ) for a service.

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the current chart symbol name
string name = Symbol();

//--- send the obtained data to the journal


PrintFormat("Current chart symbol name: '%s'", name);
/*
result
Current chart symbol name: 'EURUSD'
*/
}

© 2000-2025, MetaQuotes Ltd.


1761 Checkup

Period
R eturns the current chart timeframe.
ENUM_TIMEFRAMES Period();

Return 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 _TIM EFRAM ES enumeration.
Note

Unlik e Expert Advisors, indicators and scripts, services are not bound to a specific chart. Therefore,
Period() returns 0 for a service.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the timeframe value of the current chart and its description
ENUM_TIMEFRAMES period = Period();
string timeframe = StringSubstr(EnumToString(period), 7);

//--- send the obtained data to the journal


PrintFormat("Current chart timeframe: %s\nTimeframe value: %s (%d)",
timeframe, EnumToString(period), period);
/*
result:
Current chart timeframe: H4
Timeframe value: PERIOD_H4 (16388)
*/
}

See also

PeriodS econds, Chart timeframes, Date and Time, Visibility of objects

© 2000-2025, MetaQuotes Ltd.


1762 Checkup

Digits
R eturns the number of decimal digits determining the accuracy of price of the current chart symbol.
int Digits();

Return Value

The value of the _Digits variable which stores the number of decimal digits determining the
accuracy of price of the current chart symbol.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the number of decimal places for the current chart symbol
int digits = Digits();

//--- send the obtained data to the journal


Print("Number of decimal digits for the current chart symbol: ", digits);
/*
result:
Number of decimal digits for the current chart symbol: 5
*/
}

© 2000-2025, MetaQuotes Ltd.


1763 Checkup

Point
R eturns the point size of the current symbol in the quote currency.
double Point();

Return Value

The value of the _Point variable which stores the point size of the current symbol in the quote
currency.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the current symbol point size in the quote currency
double point = Point();

//--- send the obtained data to the journal


Print("Point size of the current symbol in the quote currency: ", DoubleToString(point, _Digits)
/*
result:
Point size of the current symbol in the quote currency: 0.00001
*/
}

© 2000-2025, MetaQuotes Ltd.


1764 Event Handling

Event Handling
The MQL5 language provides handling of certain predefined events. The functions for handling these
events should be defined in an MQL5 program: function name, return type, a set of parameters (if
any) and their types should strictly correspond to the description of an event handling function.
The client terminal event handler uses the return and parameter types to identify functions processing
an event. If a certain function has some parameters or a return type not corresponding to the
descriptions below, such a function cannot be used for handling an event.

Function Description

OnS tart The function is called when the S tart event occurs to perform
actions set in the script
OnInit The function is called in indicators and EAs when the Init event
occurs to initialize a launched MQL5 program
OnDeinit The function is called in indicators and EAs when the Deinit event
occurs to de-initialize a launched MQL5 program
OnTick The function is called in EAs when the NewTick event occurs to
handle a new quote
OnCalculate The function is called in indicators when the Calculate event occurs
to handle price data changes
OnTimer The function is called in indicators and EAs during the Timer
periodic event generated by the terminal at fixed time intervals
OnTrade The function is called in EAs during the Trade event generated at
the end of a trading operation on a trade server
OnTradeTransaction The function is called in EAs when the TradeTransaction event
occurs to process a trade request execution results
OnBookEvent The function is called in EAs when the BookEvent event occurs to
process changes in the market depth
OnChartEvent The function is called in indicators and EAs when the ChartEvent
event occurs to process chart changes made by a user or an MQL5
program
OnTester The function is called in EAs when the Tester event occurs to
perform necessary actions after testing an EA on history data
OnTesterInit The function is called in EAs when the TesterInit event occurs to
perform necessary actions before optimization in the strategy
tester
OnTesterDeinit The function is called in EAs when the TesterDeinit event occurs
after EA optimization in the strategy tester
OnTesterPass The function is called in EAs when the TesterPass even occurs to
handle an arrival of a new data frame during EA optimization in the
strategy tester

© 2000-2025, MetaQuotes Ltd.


1765 Event Handling

The client terminal sends incoming events to corresponding open charts. Also, events may be
generated by charts (chart events) or mql5 programs (custom events). Generating graphical object
creation/deletion events can be enabled/disabled by setting the CHART_EVENT_OBJECT_CREATE and
CHART_EVENT_OBJECT_DELETE chart properties. Each mql5 application and chart have their own
queue of events where all newly arrived events are placed.

A program gets events only from the chart it is running on. All events are handled one after another in
the order of their receipt. If the queue already contains the NewTick event or this event is in the
processing stage, then the new NewTick event is not added to mql5 application queue. S imilarly, if the
ChartEvent is already in an mql5 program queue or such an event is being handled, then a new event
of this type is not placed into a queue. Timer event handling is processed in the same way – if the
Timer event is already in the queue or is being handled, no new timer event is set into a queue.
Event queues have a limited but sufficient size, so the queue overflow is unlikely for a correctly
developed program. W hen the queue overflows, new events are discarded without being set into a
queue.

It is strongly recommended not to use infinite loops to handle events. Possible exceptions are scripts
handling a single S tart event.
Libraries do not handle any events.

© 2000-2025, MetaQuotes Ltd.


1766 Event Handling

OnStart
The function is called in scripts and services when the S tart event occurs. The function is intended for
one-time execution of actions implemented in a program. There are two function types.
The version that returns the result
int OnStart(void);

Return Value

The value of int type displayed in the Journal tab.


The entry " script script_name removed (result code N)" is created in the terminal journal after a
script execution is complete. Here N is a value returned by the OnS tart() function.
The entry " service service_name stopped (result code N)" is created in the terminal journal after a
service execution is complete. Here N is a value returned by the OnS tart() function.
The OnS tart() call that returns the execution result is recommended for use since it not only allows for
a script or service execution, but also returns an error code or other useful data to analyze the
program execution result.
The version without a result return is left only for compatibility with old codes. It is not
recommended for use
void OnStart(void);

Note

OnS tart() is the only function for handling events in scripts and services. No other events are sent to
these programs. In turn, the S tart event is not passed to EAs and custom indicators.
Sample script:

//--- macros for working with colors


#define XRGB(r,g,b) (0xFF000000|(uchar(r)<<16)|(uchar(g)<<8)|uchar(b))
#define GETRGB(clr) ((clr)&0xFFFFFF)
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set a downward candle color
Comment("Set a downward candle color");
ChartSetInteger(0,CHART_COLOR_CANDLE_BEAR,GetRandomColor());
ChartRedraw(); // update the chart immediately without waiting for a new tick
Sleep(1000); // pause for 1 second to see all the changes
//--- set an upward candle color
Comment("Set an upward candle color");
ChartSetInteger(0,CHART_COLOR_CANDLE_BULL,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set the background color

© 2000-2025, MetaQuotes Ltd.


1767 Event Handling

Comment("Set the background color");


ChartSetInteger(0,CHART_COLOR_BACKGROUND,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set color of Ask line
Comment("Set color of Ask line");
ChartSetInteger(0,CHART_COLOR_ASK,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set color of Bid line
Comment("Set color of Bid line");
ChartSetInteger(0,CHART_COLOR_BID,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set color of a downward bar and a downward candle frame
Comment("Set color of a downward bar and a downward candle frame");
ChartSetInteger(0,CHART_COLOR_CHART_DOWN,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set color of a chart line and Doji candlesticks
Comment("Set color of a chart line and Doji candlesticks");
ChartSetInteger(0,CHART_COLOR_CHART_LINE,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set color of an upward bar and an upward candle frame
Comment("Set color of an upward bar and an upward candle frame");
ChartSetInteger(0,CHART_COLOR_CHART_UP,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set color of axes, scale and OHLC line
Comment("Set color of axes, scale and OHLC line");
ChartSetInteger(0,CHART_COLOR_FOREGROUND,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set a grid color
Comment("Set a grid color");
ChartSetInteger(0,CHART_COLOR_GRID,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set Last price color
Comment("Set Last price color");
ChartSetInteger(0,CHART_COLOR_LAST,GetRandomColor());
ChartRedraw();
Sleep(1000);
//--- set color of Stop Loss and Take Profit order levels
Comment("Set color of Stop Loss and Take Profit order levels");
ChartSetInteger(0,CHART_COLOR_STOP_LEVEL,GetRandomColor());
ChartRedraw();
Sleep(1000);

© 2000-2025, MetaQuotes Ltd.


1768 Event Handling

//--- set color of volumes and market entry levels


Comment("Set color of volumes and market entry levels");
ChartSetInteger(0,CHART_COLOR_VOLUME,GetRandomColor());
ChartRedraw();
}
//+------------------------------------------------------------------+
//| Return a randomly generated color |
//+------------------------------------------------------------------+
color GetRandomColor()
{
color clr=(color)GETRGB(XRGB(rand()%255,rand()%255,rand()%255));
return clr;
}

See also
Event handling functions, Program running, Client terminal events

© 2000-2025, MetaQuotes Ltd.


1769 Event Handling

OnInit
The function is called in indicators and EAs when the Init event occurs. It is used to initialize a running
MQL5 program. There are two function types.
The version that returns the result
int OnInit(void);

Return Value

int type value, zero means successful initialization.


W hen returning INIT _FAIL ED, the EA is forcibly unloaded from the chart.
W hen returning INIT _FAIL ED,the indicator is not unloaded from the chart. The indicator remaining
on the chart is non-operational — event handlers are not called in the indicator.
The OnInit() call that returns the execution result is recommended for use since it not only allows for
program initialization, but also returns an error code in case of an early program termination.
The version without a result return is left only for compatibility with old codes. It is not
recommended for use
void OnInit(void);

Note

The Init event is generated immediately after loading an EA or an indicator. The event is not
generated for scripts. The OnInit() function is used to initialize an MQL5 program. If OnInit() has a
return value of int type, the non-zero return code means failed initialization and generates the
Deinit event with the REAS ON_INIT FAIL ED deinitialization reason code.

OnInit() function of void type always means successful initialization and is not recommended for
use.
For optimizing the EA inputs, it is recommended to use values from the ENUM _INIT_RETCODE
enumeration as a return code. These values are intended for establishing the optimization process
management, including selection of the most suitable test agents. It is possible to request data on
agent configuration and resources (number of cores, free memory amount, etc.) using the
TerminalInfoInteger() function during the EA initialization before launching the test. Based on the
obtained data, you can either allow using the test agent or ban it from optimizing the EA.

ID Description

INIT_SUCCEEDED Initialization successful, EA test can be continued.


This code means the same as the zero value – the EA
initialization in the tester is successful.
INIT_FAILED Initialization failed. There is no point in continuing the test due
to unavoidable errors. For example, it is impossible to create
an indicator necessary for the EA operation.
The return of this value means the same as returning the value
different from zero – EA initialization in the tester failed.

© 2000-2025, MetaQuotes Ltd.


1770 Event Handling

ID Description

INIT_PARAM ETERS_INCORRECT Designed to denote an incorrect set of input parameters by a


programmer. In the general optimization table, the result string
with this return code is highlighted in red.
A test for such a set of EA inputs is not performed. The agent
is ready to receive a new tas k.
W hen this value is received, the strategy tester does not pass
this tas k to other agents for repeated execution.
INIT_AGENT_NOT_SUITABLE No program execution errors during initialization. However, for
some reasons, the agent is not suitable for conducting a test.
For example, there is not enough RAM, no OpenCL support,
etc.
After returning this code, the agent no longer receives tas k s
until the very end of this optimization.

Using OnInit() returning INIT_FAILED/INIT_PARAM ETERS_INCORRECT in the tester have some


peculiarities that should be considered when optimizing EAs :
· the set of parameters the OnInit() returned I NIT _PARAM ET ERS_I NCORRECT for is considered
unsuitable for testing and is not used to obtain the next population during genetic optimization.
Too many " discarded" parameter sets may lead to incorrect results when searching for optimal EA
parameters. The search algorithm assumes that the optimization criterion function is smooth and
has no gaps on the entire multitude of input parameters.
· if OnInit() returns I NIT _FAIL ED, this means that a test cannot be launched, and the EA is unloaded
from the agent's memory. The EA is loaded again to perform the next pass with a new set of
parameters. Launching the next optimization pass takes much more time as compared to calling
TesterS top().
Sample OnInit() function for an EA

//--- input parameters


input int ma_period=20; // moving average period

//--- handle of the indicator used in the EA


int indicator_handle;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- check ma_period validity
if(ma_period<=0)
{
PrintFormat("Invalid ma_period input value: %d",ma_period);
return (INIT_PARAMETERS_INCORRECT);
}
//--- during optimization
if(MQLInfoInteger(MQL_OPTIMIZATION))
{

© 2000-2025, MetaQuotes Ltd.


1771 Event Handling

//--- check available RAM for the agent


int available_memory_mb=TerminalInfoInteger(TERMINAL_MEMORY_TOTAL);
if(available_memory_mb<2000)
{
PrintFormat("Insufficient memory for the test agent: %d MB",
available_memory_mb);
return (INIT_AGENT_NOT_SUITABLE);
}
}
//--- check for the indicator
indicator_handle=iCustom(_Symbol,_Period,"My_Indicator",ma_period);
if(indicator_handle==INVALID_HANDLE)
{
PrintFormat("Failed to generate My_Indicator handle. Error code %d",
GetLastError());
return (INIT_FAILED);
}
//--- EA initialization successful
return(INIT_SUCCEEDED);
}

See also
OnDeinit, Event handling functions, Program running, Client terminal events, Initialization of
variables, Creating and deleting objects

© 2000-2025, MetaQuotes Ltd.


1772 Event Handling

OnDeinit
The function is called in indicators and EAs when the Deinit event occurs. It is used to deinitialize a
running MQL5 program.
void OnDeinit(
const int reason // deinitialization reason code
);

Parameters
reason
[in] Deinitialization reason code.

Return Value

No return value
Note

Deinit event is generated for EAs and indicators in the following cases :
· before a re-initialization due to the change of a symbol or a chart period the mql5 program is
attached to;
· before a re-initialization due to the change of the inputs ;
· before unloading an mql5 program.
The reason parameter may have the following values :
Constant Value Description

REAS ON_PR OGRAM 0 The EA has stopped working calling the


ExpertR emove() function

REAS ON_REMOVE 1 Program removed from a chart


REAS ON_RECOMPIL E 2 Program recompiled
REAS ON_CHAR TCHANGE 3 A symbol or a chart period is changed
REAS ON_CHAR TCLOSE 4 Chart closed
REAS ON_PARAM ET ERS 5 Inputs changed by a user
REAS ON_ACCOUNT 6 Another account has been activated or reconnection
to the trade server has occurred due to changes in
the account settings
REAS ON_T EMPL AT E 7 Another chart template applied
REAS ON_INIT FAIL ED 8 The OnInit() handler returned a non-zero value
REAS ON_CLOSE 9 Terminal closed
EA deinitialization reason codes can be received by the UninitializeReason() function or from the
predefined _UninitReason variable.
Sample OnInit() and OnDeinit() functions for the EA

© 2000-2025, MetaQuotes Ltd.


1773 Event Handling

input int fake_parameter=3; // useless parameter


//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Get the number of a build where the program is compiled
Print(__FUNCTION__," Build #",__MQLBUILD__);
//--- Reset reason code can also be obtained in OnInit()
Print(__FUNCTION__," Deinitialization reason code can be received during the EA reset");
//--- The first way to get a deinitialization reason code
Print(__FUNCTION__," _UninitReason = ",getUninitReasonText(_UninitReason));
//--- The second way to get a deinitialization reason code
Print(__FUNCTION__," UninitializeReason() = ",getUninitReasonText(UninitializeReason()));
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- The first way to get a deinitialization reason code
Print(__FUNCTION__," Deinitialization reason code = ",reason);
//--- The second way to get a deinitialization reason code
Print(__FUNCTION__," _UninitReason = ",getUninitReasonText(_UninitReason));
//--- The third way to get a deinitialization reason code
Print(__FUNCTION__," UninitializeReason() = ",getUninitReasonText(UninitializeReason()));
}
//+------------------------------------------------------------------+
//| Return a textual description of the deinitialization reason code |
//+------------------------------------------------------------------+
string getUninitReasonText(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;

© 2000-2025, MetaQuotes Ltd.


1774 Event Handling

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

See also
OnInit, Event handling functions, Program running, Client terminal events, Uninitialization reason
codes, Visibility scope and lifetime of variables, Creating and deleting objects

© 2000-2025, MetaQuotes Ltd.


1775 Event Handling

OnTick
The function is called in EAs when the NewTick event occurs to handle a new quote.
void OnTick(void);

Return Value

No return value
Note

The NewTick event is generated only for EAs upon receiving a new tick for a symbol of the chart the
EA is attached to. There is no point in defining the OnTick () function in a custom indicator or a
script since a NewTick event is not generated for them.
The Tick event is generated only for EAs, but this does not mean that EAs have to feature the
OnTick() function, since Timer, BookEvent and ChartEvent events are also generated for EAs in
addition to NewTick.
All events are handled one after another in the order of their receipt. If the queue already contains
the NewTick event or this event is in the processing stage, then the new NewTick event is not added
to mql5 application queue.
The NewTick event is generated regardless of whether auto trading is enabled (AutoTrading button).
Disabled auto trading means only a ban on sending trade requests from an EA. The EA operation is
not stopped.
Disablingauto trading by pressing the AutoTrading button does not interrupt the current execution
of the OnTick() function.
Example of the EA featuring its entire trading logic in the OnTick() function
//+------------------------------------------------------------------+
//| TradeByATR.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "Sample EA trading in the \"explosive\" candle direction"
#property description "\"Explosive\" candle has the body size exceeding k*ATR"
#property description "The \"revers\" parameter reverses the signal direction"

input double lots=0.1; // volume in lots


input double kATR=3; // signal candle length in ATR
input int ATRperiod=20; // ATR indicator period
input int holdbars=8; // number of bars to hold position on
input int slippage=10; // allowable slippage
input bool revers=false; // reverse the signal?
input ulong EXPERT_MAGIC=0; // EA's MagicNumber
//--- for storing the ATR indicator handle

© 2000-2025, MetaQuotes Ltd.


1776 Event Handling

int atr_handle;
//--- here we will store the last ATR values and the candle body
double last_atr,last_body;
datetime lastbar_timeopen;
double trade_lot;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- initialize global variables
last_atr=0;
last_body=0;
//--- set the correct volume
double min_lot=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
trade_lot=lots>min_lot? lots:min_lot;
//--- create ATR indicator handle
atr_handle=iATR(_Symbol,_Period,ATRperiod);
if(atr_handle==INVALID_HANDLE)
{
PrintFormat("%s: failed to create iATR, error code %d",__FUNCTION__,GetLastError());
return(INIT_FAILED);
}
//--- successful EA initialization
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- inform of the EA operation end code
Print(__FILE__,": Deinitialization reason code = ",reason);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- trading signal
static int signal=0; // +1 means a buy signal, -1 means a sell signal
//--- check and close old positions opened more than 'holdbars' bars ago
ClosePositionsByBars(holdbars,slippage,EXPERT_MAGIC);
//--- check for a new bar
if(isNewBar())
{
//--- check for a signal presence
signal=CheckSignal();
}

© 2000-2025, MetaQuotes Ltd.


1777 Event Handling

//--- if a netting position is opened, skip the signal - wait till it closes
if(signal!=0 && PositionsTotal()>0 && (ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGI
{
signal=0;
return; // exit the NewTick event handler and do not enter the market before a new bar appear
}
//--- for a hedging account, each position is held and closed separately
if(signal!=0)
{
//--- buy signal
if(signal>0)
{
PrintFormat("%s: Buy signal! Revers=%s",__FUNCTION__,string(revers));
if(Buy(trade_lot,slippage,EXPERT_MAGIC))
signal=0;
}
//--- sell signal
if(signal<0)
{
PrintFormat("%s: Sell signal! Revers=%s",__FUNCTION__,string(revers));
if(Sell(trade_lot,slippage,EXPERT_MAGIC))
signal=0;
}
}
//--- OnTick function end
}
//+------------------------------------------------------------------+
//| Check for a new trading signal |
//+------------------------------------------------------------------+
int CheckSignal()
{
//--- 0 means no signal
int res=0;
//--- get ATR value on a penultimate complete bar (the bar index is 2)
double atr_value[1];
if(CopyBuffer(atr_handle,0,2,1,atr_value)!=-1)
{
last_atr=atr_value[0];
//--- get data on the last closed bar to the MqlRates type array
MqlRates bar[1];
if(CopyRates(_Symbol,_Period,1,1,bar)!=-1)
{
//--- calculate the bar body size on the last complete bar
last_body=bar[0].close-bar[0].open;
//--- if the body of the last bar (with index 1) exceeds the previous ATR value (on the ba
if(MathAbs(last_body)>kATR*last_atr)
res=last_body>0?1:-1; // positive value for the upward candle
}
else

© 2000-2025, MetaQuotes Ltd.


1778 Event Handling

PrintFormat("%s: Failed to receive the last bar! Error",__FUNCTION__,GetLastError());


}
else
PrintFormat("%s: Failed to receive ATR indicator value! Error",__FUNCTION__,GetLastError());
//--- if reverse trading mode is enabled
res=revers?-res:res; // reverse the signal if necessary (return -1 instead of 1 and vice versa)
//--- return a trading signal value
return (res);
}
//+------------------------------------------------------------------+
//| Return 'true' when a new bar appears |
//+------------------------------------------------------------------+
bool isNewBar(const bool print_log=true)
{
static datetime bartime=0; // store open time of the current bar
//--- get open time of the zero bar
datetime currbar_time=iTime(_Symbol,_Period,0);
//--- if open time changes, a new bar has arrived
if(bartime!=currbar_time)
{
bartime=currbar_time;
lastbar_timeopen=bartime;
//--- display data on open time of a new bar in the log
if(print_log && !(MQLInfoInteger(MQL_OPTIMIZATION)||MQLInfoInteger(MQL_TESTER)))
{
//--- display a message with a new bar open time
PrintFormat("%s: new bar on %s %s opened at %s",__FUNCTION__,_Symbol,
StringSubstr(EnumToString(_Period),7),
TimeToString(TimeCurrent(),TIME_SECONDS));
//--- get data on the last tick
MqlTick last_tick;
if(!SymbolInfoTick(Symbol(),last_tick))
Print("SymbolInfoTick() failed, error = ",GetLastError());
//--- display the last tick time up to milliseconds
PrintFormat("Last tick was at %s.%03d",
TimeToString(last_tick.time,TIME_SECONDS),last_tick.time_msc%1000);
}
//--- we have a new bar
return (true);
}
//--- no new bar
return (false);
}
//+------------------------------------------------------------------+
//| Buy at a market price with a specified volume |
//+------------------------------------------------------------------+
bool Buy(double volume,ulong deviation=10,ulong magicnumber=0)
{
//--- buy at a market price

© 2000-2025, MetaQuotes Ltd.


1779 Event Handling

return (MarketOrder(ORDER_TYPE_BUY,volume,deviation,magicnumber));
}
//+------------------------------------------------------------------+
//| Sell at a market price with a specified volume |
//+------------------------------------------------------------------+
bool Sell(double volume,ulong deviation=10,ulong magicnumber=0)
{
//--- sell at a market price
return (MarketOrder(ORDER_TYPE_SELL,volume,deviation,magicnumber));
}
//+------------------------------------------------------------------+
//| Close positions by hold time in bars |
//+------------------------------------------------------------------+
void ClosePositionsByBars(int holdtimebars,ulong deviation=10,ulong magicnumber=0)
{
int total=PositionsTotal(); // number of open positions
//--- iterate over open positions
for(int i=total-1; i>=0; i--)
{
//--- position parameters
ulong position_ticket=PositionGetTicket(i); // position
string position_symbol=PositionGetString(POSITION_SYMBOL); // symbol
ulong magic=PositionGetInteger(POSITION_MAGIC); // position
datetime position_open=(datetime)PositionGetInteger(POSITION_TIME); // position
int bars=iBarShift(_Symbol,PERIOD_CURRENT,position_open)+1; // how many

//--- if a position's lifetime is already large, while MagicNumber and a symbol match
if(bars>holdtimebars && magic==magicnumber && position_symbol==_Symbol)
{
int digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS); // number o
double volume=PositionGetDouble(POSITION_VOLUME); // position
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); // position
string str_type=StringSubstr(EnumToString(type),14);
StringToLower(str_type); // lower the text case for correct message formatting
PrintFormat("Close position #%I64u %s %s %.2f",
position_ticket,position_symbol,str_type,volume);
//--- set an order type and sending a trade request
if(type==POSITION_TYPE_BUY)
MarketOrder(ORDER_TYPE_SELL,volume,deviation,magicnumber,position_ticket);
else
MarketOrder(ORDER_TYPE_BUY,volume,deviation,magicnumber,position_ticket);
}
}
}
//+------------------------------------------------------------------+
//| Prepare and send a trade request |
//+------------------------------------------------------------------+
bool MarketOrder(ENUM_ORDER_TYPE type,double volume,ulong slip,ulong magicnumber,ulong pos_ticket=0
{

© 2000-2025, MetaQuotes Ltd.


1780 Event Handling

//--- declaring and initializing structures


MqlTradeRequest request={};
MqlTradeResult result={};
double price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
if(type==ORDER_TYPE_BUY)
price=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
//--- request parameters
request.action =TRADE_ACTION_DEAL; // trading operation type
request.position =pos_ticket; // position ticket if closing
request.symbol =Symbol(); // symbol
request.volume =volume; // volume
request.type =type; // order type
request.price =price; // trade price
request.deviation=slip; // allowable deviation from the price
request.magic =magicnumber; // order MagicNumber
//--- send a request
if(!OrderSend(request,result))
{
//--- display data on failure
PrintFormat("OrderSend %s %s %.2f at %.5f error %d",
request.symbol,EnumToString(type),volume,request.price,GetLastError());
return (false);
}
//--- inform of a successful operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
return (true);
}

See also
Event handling functions, Program running, Client terminal events, OnTimer, OnBookEvent,
OnChartEvent

© 2000-2025, MetaQuotes Ltd.


1781 Event Handling

OnCalculate
The function is called in the indicators when the Calculate event occurs for processing price data
changes. There are two function types. Only one of them can be used within a single indicator.
Calculation based on data array
int OnCalculate(
const int rates_total, // price[] array size
const int prev_calculated, // number of handled bars at the previous call
const int begin, // index number in the price[] array meaningful data starts
const double& price[] // array of values for calculation
);

Calculations based on the current timeframe timeseries


int OnCalculate(
const int rates_total, // size of input time series
const int prev_calculated, // number of handled bars at the previous call
const datetime& time[], // Time array
const double& open[], // Open array
const double& high[], // High array
const double& low[], // Low array
const double& close[], // Close array
const long& tick_volume[], // Tick Volume array
const long& volume[], // Real Volume array
const int& spread[] // Spread array
);

Parameters
rates_total
[in] S ize of
the price[] array or input series available to the indicator for calculation. In the second
function type, the parameter value corresponds to the number of bars on the chart it is launched
at.
prev_calculated
[in] Contains the value returned by the OnCalculate() function during the previous call. It is
designed to s kip the bars that have not changed since the previous launch of this function.
begin
[in] Index value in the price[] array meaningful data starts from. It allows you to s kip missing or
initial data, for which there are no correct values.
price[]
[in] Array of values for calculations. One of the price timeseries or a calculated indicator buffer
can be passed as the price[] array. Type of data passed for calculation can be defined using the
_AppliedTo predefined variable.

time{}
[in] Array with bar open time values.

© 2000-2025, MetaQuotes Ltd.


1782 Event Handling

open[]
[in] Array with Open price values.

high[]
[in] Array with H igh price values.

low[]
[in] Array with Low price values.

close[]
[in] Array with Close price values.

tick_volume[]
[in] Array with tick volume values.
volume[]
[in] Array with trade volume values.

spread[]
[in] Array with spread values for bars.

Return Value

int type value to be passed as the prev_calculated parameter during the next function call.
Note

If the OnCalculate() function is equal to zero, no indicator values are shown in the DataW indow of
the client terminal.
If the price data have been changed since the last call of the OnCalculate() function (a deeper
history has been loaded or gaps in the history have been filled), the value of the prev_calculated
input parameter is set to zero by the terminal itself.
To define the indexing direction in the time[], open[], high[], low[], close[], tick_volume[],
volume[] and spread[] arrays, call the A rrayGetA s S eries() function. In order not to depend on

defaults, call the ArrayS etAs S eries() function for the arrays to work with.
W hen using the first function type, a necessary timeseries or indicator is selected by a user as the
price[] array in the Parameters tab when launching the indicator. To do this, specify the necessary
element in the drop-down list of the "Apply to" field.
To get custom indicator values from other mql5 programs, the iCustom() function is used. It returns
the indicator handle for subsequent operations. It is also possible to specify the required price []
array or the handle of another indicator. This parameter should be passed the last in the list of input
variables of a custom indicator.
It is necessary to use the connection between the value returned by the OnCalculate() function and
the prev_calculated second input parameter. W hen calling the function, the prev_calculated
parameter contains the value returned by the OnCalculate() function during the previous call. This
makes it possible to implement resource-saving algorithms for calculating a custom indicator in
order to avoid repetitive calculations for the bars that have not changed since the previous launch of
this function.

© 2000-2025, MetaQuotes Ltd.


1783 Event Handling

Sample indicator

//+------------------------------------------------------------------+
//| OnCalculate_Sample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "Sample Momentum indicator calculation"

//---- indicator settings


#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_color1 Blue
//---- inputs
input int MomentumPeriod=14; // Calculation period
//---- indicator buffer
double MomentumBuffer[];
//--- global variable for storing calculation period
int IntPeriod;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- check the input parameter
if(MomentumPeriod<0)
{
IntPeriod=14;
Print("Period parameter has an incorrect value. The following value is to be used for calcula
}
else
IntPeriod=MomentumPeriod;
//---- buffers
SetIndexBuffer(0,MomentumBuffer,INDICATOR_DATA);
//---- indicator name to be displayed in DataWindow and subwindow
IndicatorSetString(INDICATOR_SHORTNAME,"Momentum"+"("+string(IntPeriod)+")");
//--- set index of the bar the drawing starts from
PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,IntPeriod-1);
//--- set 0.0 as an empty value that is not drawn
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);
//--- indicator accuracy to be displayed
IndicatorSetInteger(INDICATOR_DIGITS,2);
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1784 Event Handling

//| Momentum indicator calculation |


//+------------------------------------------------------------------+
int OnCalculate(const int rates_total, // price[] array size
const int prev_calculated, // number of previously handled bars
const int begin, // where significant data start from
const double &price[]) // value array for handling
{
//--- initial position for calculations
int StartCalcPosition=(IntPeriod-1)+begin;
//---- if calculation data is insufficient
if(rates_total<StartCalcPosition)
return(0); // exit with a zero value - the indicator is not calculated
//--- correct draw begin
if(begin>0)
PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,StartCalcPosition+(IntPeriod-1));
//--- start calculations, define the starting position
int pos=prev_calculated-1;
if(pos<StartCalcPosition)
pos=begin+IntPeriod;
//--- main calculation loop
for(int i=pos;i<rates_total && !IsStopped();i++)
MomentumBuffer[i]=price[i]*100/price[i-IntPeriod];
//--- OnCalculate execution is complete. Return the new prev_calculated value for the subsequent ca
return(rates_total);
}

See also
ArrayGetAs S eries, ArrayS etAs S eries, iCustom, Event handling functions, Program running, Client
terminal events, Access to timeseries and indicators

© 2000-2025, MetaQuotes Ltd.


1785 Event Handling

OnTimer
The function is called in EAs during the Timer event generated by the terminal at fixed time intervals.
void OnTimer(void);

Return Value

No return value
Note

The Timer event is periodically generated by the client terminal for an EA, which activated the timer
using the EventS etTimer() function. Usually, this function is called in the OnInit() function. W hen
the EA stops working, the timer should be eliminated using EventKillTimer(), which is usually called
in the OnDeinit() function.
Each Expert Advisor and each indicator work with its own timer receiving events solely from this
timer. During mql5 application shutdown, the timer is forcibly destroyed in case it has been created
but has not been disabled by EventKillTimer() function.
If you need to receive timer events more frequently than once per second, use
EventS etMillisecondTimer() for creating a high-resolution timer.

In general, when the timer period is reduced, the testing time is increased, as the handler of timer
events is called more often. W hen working in real-time mode, timer events are generated no more
than 1 time in 10-16 milliseconds due to hardware limitations.
Only one timer can be launched for each program. Each mql5 application and chart have their own
queue of events where all newly arrived events are placed. If the queue already contains Timer
event or this event is in the processing stage, then the new Timer event is not added to mql5
application queue.
Sample EA with the OnTimer() handler
//+------------------------------------------------------------------+
//| OnTimer_Sample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "Example of using the timer for calculating the trading server time"
#property description "It is recommended to run the EA at the end of a trading week before the week
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create a timer with a 1 second period
EventSetTimer(1);

© 2000-2025, MetaQuotes Ltd.


1786 Event Handling

//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy the timer after completing the work
EventKillTimer();

}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---

}
//+------------------------------------------------------------------+
//| Timer function |
//+------------------------------------------------------------------+
void OnTimer()
{
//--- time of the OnTimer() first call
static datetime start_time=TimeCurrent();
//--- trade server time during the first OnTimer() call
static datetime start_tradeserver_time=0;
//--- calculated trade server time
static datetime calculated_server_time=0;
//--- local PC time
datetime local_time=TimeLocal();
//--- current estimated trade server time
datetime trade_server_time=TimeTradeServer();
//--- if a server time is unknown for some reason, exit ahead of time
if(trade_server_time==0)
return;
//--- if the initial trade server value is not set yet
if(start_tradeserver_time==0)
{
start_tradeserver_time=trade_server_time;
//--- set a calculated value of a trade server
Print(trade_server_time);
calculated_server_time=trade_server_time;
}
else
{
//--- increase time of the OnTimer() first call

© 2000-2025, MetaQuotes Ltd.


1787 Event Handling

if(start_tradeserver_time!=0)
calculated_server_time=calculated_server_time+1;;
}
//---
string com=StringFormat(" Start time: %s\r\n",TimeToString(start_time,TIME_MINU
com=com+StringFormat(" Local time: %s\r\n",TimeToString(local_time,TIME_MINUTES
com=com+StringFormat("TimeTradeServer time: %s\r\n",TimeToString(trade_server_time,TIME_MINUTES|
com=com+StringFormat(" EstimatedServer time: %s\r\n",TimeToString(calculated_server_time,TIME_MI
//--- display values of all counters on the chart
Comment(com);
}

See also
EventS etTimer, EventS etMillisecondTimer, EventKillTimer, GetTick Count, GetMicrosecondCount,
Client terminal events

© 2000-2025, MetaQuotes Ltd.


1788 Event Handling

OnTrade
The function is called in EAs when the Trade event occurs. The function is meant for processing
changes in order, position and trade lists.
void OnTrade(void);

Return Value

No return value
Note

OnTrade() is called only for Expert Advisors. It is not used in indicators and scripts even if you add
there a function with the same name and type.
For any trade action (placing a pending order, opening/closing a position, placing stops, activating
pending orders, etc.), the history of orders and trades and/or the list of positions and current orders
is changed appropriately.
W hen handling an order, a trade server sends the terminal a message about the incoming Trade
event. To retrieve relevant data on orders and trades from history, it is necessary to perform a
trading history request using HistoryS elect() first.
The trade events are generated by the server in case of:
· changing active orders,
· changing positions,
· changing deals,
· changing trade history.

Each Trade event may appear as a result of one or several trade requests. Trade requests are sent
to the server using OrderS end() or OrderS endAsync(). Each request can lead to several trade events.
You cannot rely on the statement " One request - one Trade event" , since the processing of events
may be performed in several stages, and each operation may change the state of orders, positions
and the trade history.

OnTrade() handler is called after the appropriate OnTradeTransaction() calls. In general, there is no
exact correlation in the number of OnTrade () and OnTradeTransaction () calls. One OnTrade() call
corresponds to one or several OnTradeTransaction calls.
Sample EA with OnTrade() handler
//+------------------------------------------------------------------+
//| OnTrade_Sample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

input int days=7; // depth of trade history in days

© 2000-2025, MetaQuotes Ltd.


1789 Event Handling

//--- set the limits of the trade history on the global scope
datetime start; // start date for trade history in cache
datetime end; // end date for trade history in cache
//--- global counters
int orders; // number of active orders
int positions; // number of open positions
int deals; // number of deals in the trade history cache
int history_orders; // number of orders in the trade history cache
bool started=false; // flag of counter relevance

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
end=TimeCurrent();
start=end-days*PeriodSeconds(PERIOD_D1);
PrintFormat("Limits of the history to be loaded: start - %s, end - %s",
TimeToString(start),TimeToString(end));
InitCounters();
//---
return(0);
}
//+------------------------------------------------------------------+
//| initialization of position, order and trade counters |
//+------------------------------------------------------------------+
void InitCounters()
{
ResetLastError();
//--- load history
bool selected=HistorySelect(start,end);
if(!selected)
{
PrintFormat("%s. Failed to load history from %s to %s to cache. Error code: %d",
__FUNCTION__,TimeToString(start),TimeToString(end),GetLastError());
return;
}
//--- get the current value
orders=OrdersTotal();
positions=PositionsTotal();
deals=HistoryDealsTotal();
history_orders=HistoryOrdersTotal();
started=true;
Print("Counters of orders, positions and deals successfully initialized");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1790 Event Handling

void OnTick()
{
if(started) SimpleTradeProcessor();
else InitCounters();
}
//+------------------------------------------------------------------+
//| called when a Trade event arrives |
//+------------------------------------------------------------------+
void OnTrade()
{
if(started) SimpleTradeProcessor();
else InitCounters();
}
//+------------------------------------------------------------------+
//| example of processing changes in trade and history |
//+------------------------------------------------------------------+
void SimpleTradeProcessor()
{
end=TimeCurrent();
ResetLastError();
//--- download trading history from the specified interval to the program cache
bool selected=HistorySelect(start,end);
if(!selected)
{
PrintFormat("%s. Failed to load history from %s to %s to cache. Error code: %d",
__FUNCTION__,TimeToString(start),TimeToString(end),GetLastError());
return;
}
//--- get the current values
int curr_orders=OrdersTotal();
int curr_positions=PositionsTotal();
int curr_deals=HistoryDealsTotal();
int curr_history_orders=HistoryOrdersTotal();
//--- check if the number of active orders has been changed
if(curr_orders!=orders)
{
//--- number of active orders has been changed
PrintFormat("Number of orders has been changed. Previous value is %d, current value is %d",
orders,curr_orders);
//--- update the value
orders=curr_orders;
}
//--- changes in the number of open positions
if(curr_positions!=positions)
{
//--- number of open positions has been changed
PrintFormat("Number of positions has been changed. Previous value is %d, current value is %d"
positions,curr_positions);
//--- update the value

© 2000-2025, MetaQuotes Ltd.


1791 Event Handling

positions=curr_positions;
}
//--- changes in the number of deals in the trade history cache
if(curr_deals!=deals)
{
//--- number of deals in the trade history cache has been changed
PrintFormat("Number of deals has been changed. Previous value is %d, current value is %d",
deals,curr_deals);
//--- update the value
deals=curr_deals;
}
//--- changes in the number of history orders in the trade history cache
if(curr_history_orders!=history_orders)
{
//--- number of history orders in the trade history cache has been changed
PrintFormat("Number of orders in history has been changed. Previous value is %d, current valu
history_orders,curr_history_orders);
//--- update the value
history_orders=curr_history_orders;
}
//--- checking if it is necessary to change the limits of the trade history to be requested in cach
CheckStartDateInTradeHistory();
}
//+------------------------------------------------------------------+
//| changing the start date for requesting the trade history |
//+------------------------------------------------------------------+
void CheckStartDateInTradeHistory()
{
//--- initial interval, if we were to start working right now
datetime curr_start=TimeCurrent()-days*PeriodSeconds(PERIOD_D1);
//--- make sure that the start limit of the trade history has not gone
//--- more than 1 day over the intended date
if(curr_start-start>PeriodSeconds(PERIOD_D1))
{
//--- correct the start date of history to be loaded in the cache
start=curr_start;
PrintFormat("New start limit of the trade history to be loaded: start => %s",
TimeToString(start));
//--- now reload the trade history for the updated interval
HistorySelect(start,end);
//--- correct the deal and order counters in history for further comparison
history_orders=HistoryOrdersTotal();
deals=HistoryDealsTotal();
}
}
//+------------------------------------------------------------------+
/* Sample output:
Limits of the history to be loaded: start - 2018.07.16 18:11, end - 2018.07.23 18:11
The counters of orders, positions and deals are successfully initialized

© 2000-2025, MetaQuotes Ltd.


1792 Event Handling

Number of orders has been changed. Previous value 0, current value 1


Number of orders has been changed. Previous value 1, current value 0
Number of positions has been changed. Previous value 0, current value 1
Number of deals has been changed. Previous value 0, current value 1
Number of orders in the history has been changed. Previous value 0, current value 1
*/

See also
OrderS end, OrderS endAsync, OnTradeTransaction, Client terminal events

© 2000-2025, MetaQuotes Ltd.


1793 Event Handling

OnTradeTransaction
The function is called in EAs when the TradeTransaction event occurs. The function is meant for
handling trade request execution results.
void OnTradeTransaction()
const MqlTradeTransaction& trans, // trade transaction structure
const MqlTradeRequest& request, // request structure
const MqlTradeResult& result // response structure
);

Parameters
trans
[in] M qlTradeTransaction type variable describing a transaction made on a trading account.
request
[in] M qlTradeRequest type variable describing a trade request that led to a transaction. It
contains the values for TRADE_TRANSACTION_REQUES T type transaction only.
result
[in] M qlTradeResult type variable containing an execution result of a trade request that led to a
transaction. It contains the values for TRADE_TRANSACTION_REQUES T type transaction only.

Return Value

No return value
Note

OnTradeTransaction() is called to handle the TradeTransaction event sent by the trade server to the
terminal in the following cases :
· sending a trade request from an MQL5 program using the OrderS end()/OrderS endAsync()
functions and its subsequent execution;
· sending a trade request manually via the GUI and its subsequent execution;
· activations of pending and stop orders on the server;
· performing operations on the trade server side.

Data on transaction type is contained in the type field of the trans variable. Types of trade
transactions are described in the ENUM _TRADE_TRANSACTION_TYPE enumeration:
· T RADE_T RANSACTION_ORDER_ADD – adding a new active order
· T RADE_T RANSACTION_ORDER_UPDAT E – changing an existing order
· T RADE_T RANSACTION_ORDER_DEL ET E – deleting an order from the list of active ones
· T RADE_T RANSACTION_DEAL _ADD – adding a deal to history
· T RADE_T RANSACTION_DEAL _UPDAT E – changing a deal in history
· T RADE_T RANSACTION_DEAL _DEL ET E – deleting a deal from history
· T RADE_T RANSACTION_H I S TORY_ADD – adding an order to history as a result of execution or
cancelation
· T RADE_T RANSACTION_H I S TORY_UPDAT E – changing an order in the order history
· T RADE_T RANSACTION_H I S TORY_DEL ET E – deleting an order from the order history
· T RADE_T RANSACTION_POS ITION – position change not related to a trade execution

© 2000-2025, MetaQuotes Ltd.


1794 Event Handling

· TRADE_TRANSACTION_REQUES T – notification that a trade request has been processed by the


server and the result of its processing has been received.
W hen handling transactions of TRADE_TRANSACTION_REQUES T type, it is necessary to analyze the
second and third parameters of the OnTradeTransaction() function – request and result – to receive
additional information.
S ending a buy trade request leads to a chain of trade transactions on a trading account: 1) request
is accepted for processing, 2) an appropriate purchase order is created for the account, 3) the order
is then executed, 4) the executed order is removed from the list of active ones, 5) adding to the
history of orders, 6) the subsequent transaction is added to history and 7) a new position is created.
All these stages are trade transactions. The arrival of each such transaction to the terminal is the
TradeTransaction event. Priority of these transactions ' arrival at the terminal is not guaranteed.
Thus, you should not expect that one group of transactions will arrive after another one when
developing your trading algorithm.
W hen transactions are processed by the EA's OnTradeTransaction() handler, the terminal goes on
handling the incoming trade transactions. Thus, the trading account status may change at the
course of OnTradeTransaction() operation. For example, while an MQL5 program handles adding a
new order, it can be executed, deleted from the list of open orders and moved to history. The
program is notified of all these events.
Transactions queue length comprises 1024 elements. If OnTradeTransaction() handles yet another
transaction for too long, the previous ones can be superseded by new transactions in the queue.
OnTrade() handler is called after the appropriate OnTradeTransaction() calls. In general, there is no
exact correlation in the number of OnTrade () and OnTradeTransaction () calls. One OnTrade() call
corresponds to one or several OnTradeTransaction calls.
Each Trade event may appear as a result of one or several trade requests. Trade requests are sent
to the server using OrderS end() or OrderS endAsync(). Each request can lead to several trade events.
You cannot rely on the statement " One request - one Trade event" , since the processing of events
may be performed in several stages and each operation may change the state of orders, positions
and the trade history.
Sample EA with OnTradeTransaction() handler
//+------------------------------------------------------------------+
//| OnTradeTransaction_Sample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "Sample listener of TradeTransaction events"
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
PrintFormat("LAST PING=%.f ms",

© 2000-2025, MetaQuotes Ltd.


1795 Event Handling

TerminalInfoInteger(TERMINAL_PING_LAST)/1000.);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---

}
//+------------------------------------------------------------------+
//| TradeTransaction function |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
//---
static int counter=0; // counter of OnTradeTransaction() calls
static uint lasttime=0; // time of the OnTradeTransaction() last call
//---
uint time=GetTickCount();
//--- if the last transaction was performed more than 1 second ago,
if(time-lasttime>1000)
{
counter=0; // then this is a new trade operation, an the counter can be reset
if(IS_DEBUG_MODE)
Print(" New trade operation");
}
lasttime=time;
counter++;
Print(counter,". ",__FUNCTION__);
//--- result of trade request execution
ulong lastOrderID =trans.order;
ENUM_ORDER_TYPE lastOrderType =trans.order_type;
ENUM_ORDER_STATE lastOrderState=trans.order_state;
//--- the name of the symbol, for which a transaction was performed
string trans_symbol=trans.symbol;
//--- type of transaction
ENUM_TRADE_TRANSACTION_TYPE trans_type=trans.type;
switch(trans.type)
{
case TRADE_TRANSACTION_POSITION: // position modification
{
ulong pos_ID=trans.position;
PrintFormat("MqlTradeTransaction: Position #%I64u %s modified: SL=%.5f TP=%.5f",
pos_ID,trans_symbol,trans.price_sl,trans.price_tp);

© 2000-2025, MetaQuotes Ltd.


1796 Event Handling

}
break;
case TRADE_TRANSACTION_REQUEST: // sending a trade request
PrintFormat("MqlTradeTransaction: TRADE_TRANSACTION_REQUEST");
break;
case TRADE_TRANSACTION_DEAL_ADD: // adding a trade
{
ulong lastDealID =trans.deal;
ENUM_DEAL_TYPE lastDealType =trans.deal_type;
double lastDealVolume=trans.volume;
//--- Trade ID in an external system - a ticket assigned by an exchange
string Exchange_ticket="";
if(HistoryDealSelect(lastDealID))
Exchange_ticket=HistoryDealGetString(lastDealID,DEAL_EXTERNAL_ID);
if(Exchange_ticket!="")
Exchange_ticket=StringFormat("(Exchange deal=%s)",Exchange_ticket);

PrintFormat("MqlTradeTransaction: %s deal #%I64u %s %s %.2f lot %s",EnumToString(trans_t


lastDealID,EnumToString(lastDealType),trans_symbol,lastDealVolume,Exchange_tic
}
break;
case TRADE_TRANSACTION_HISTORY_ADD: // adding an order to the history
{
//--- order ID in an external system - a ticket assigned by an Exchange
string Exchange_ticket="";
if(lastOrderState==ORDER_STATE_FILLED)
{
if(HistoryOrderSelect(lastOrderID))
Exchange_ticket=HistoryOrderGetString(lastOrderID,ORDER_EXTERNAL_ID);
if(Exchange_ticket!="")
Exchange_ticket=StringFormat("(Exchange ticket=%s)",Exchange_ticket);
}
PrintFormat("MqlTradeTransaction: %s order #%I64u %s %s %s %s",EnumToString(trans_type),
lastOrderID,EnumToString(lastOrderType),trans_symbol,EnumToString(lastOrderSta
}
break;
default: // other transactions
{
//--- order ID in an external system - a ticket assigned by Exchange
string Exchange_ticket="";
if(lastOrderState==ORDER_STATE_PLACED)
{
if(OrderSelect(lastOrderID))
Exchange_ticket=OrderGetString(ORDER_EXTERNAL_ID);
if(Exchange_ticket!="")
Exchange_ticket=StringFormat("Exchange ticket=%s",Exchange_ticket);
}
PrintFormat("MqlTradeTransaction: %s order #%I64u %s %s %s",EnumToString(trans_type),
lastOrderID,EnumToString(lastOrderType),EnumToString(lastOrderState),Exchange_

© 2000-2025, MetaQuotes Ltd.


1797 Event Handling

}
break;
}
//--- order ticket
ulong orderID_result=result.order;
string retcode_result=GetRetcodeID(result.retcode);
if(orderID_result!=0)
PrintFormat("MqlTradeResult: order #%d retcode=%s ",orderID_result,retcode_result);
//---
}
//+------------------------------------------------------------------+
//| convert numeric response codes to string mnemonics |
//+------------------------------------------------------------------+
string GetRetcodeID(int retcode)
{
switch(retcode)
{
case 10004: return("TRADE_RETCODE_REQUOTE"); break;
case 10006: return("TRADE_RETCODE_REJECT"); break;
case 10007: return("TRADE_RETCODE_CANCEL"); break;
case 10008: return("TRADE_RETCODE_PLACED"); break;
case 10009: return("TRADE_RETCODE_DONE"); break;
case 10010: return("TRADE_RETCODE_DONE_PARTIAL"); break;
case 10011: return("TRADE_RETCODE_ERROR"); break;
case 10012: return("TRADE_RETCODE_TIMEOUT"); break;
case 10013: return("TRADE_RETCODE_INVALID"); break;
case 10014: return("TRADE_RETCODE_INVALID_VOLUME"); break;
case 10015: return("TRADE_RETCODE_INVALID_PRICE"); break;
case 10016: return("TRADE_RETCODE_INVALID_STOPS"); break;
case 10017: return("TRADE_RETCODE_TRADE_DISABLED"); break;
case 10018: return("TRADE_RETCODE_MARKET_CLOSED"); break;
case 10019: return("TRADE_RETCODE_NO_MONEY"); break;
case 10020: return("TRADE_RETCODE_PRICE_CHANGED"); break;
case 10021: return("TRADE_RETCODE_PRICE_OFF"); break;
case 10022: return("TRADE_RETCODE_INVALID_EXPIRATION"); break;
case 10023: return("TRADE_RETCODE_ORDER_CHANGED"); break;
case 10024: return("TRADE_RETCODE_TOO_MANY_REQUESTS"); break;
case 10025: return("TRADE_RETCODE_NO_CHANGES"); break;
case 10026: return("TRADE_RETCODE_SERVER_DISABLES_AT"); break;
case 10027: return("TRADE_RETCODE_CLIENT_DISABLES_AT"); break;
case 10028: return("TRADE_RETCODE_LOCKED"); break;
case 10029: return("TRADE_RETCODE_FROZEN"); break;
case 10030: return("TRADE_RETCODE_INVALID_FILL"); break;
case 10031: return("TRADE_RETCODE_CONNECTION"); break;
case 10032: return("TRADE_RETCODE_ONLY_REAL"); break;
case 10033: return("TRADE_RETCODE_LIMIT_ORDERS"); break;
case 10034: return("TRADE_RETCODE_LIMIT_VOLUME"); break;
case 10035: return("TRADE_RETCODE_INVALID_ORDER"); break;
case 10036: return("TRADE_RETCODE_POSITION_CLOSED"); break;

© 2000-2025, MetaQuotes Ltd.


1798 Event Handling

default:
return("TRADE_RETCODE_UNKNOWN="+IntegerToString(retcode));
break;
}
//---
}

See also
OrderS end, OrderS endAsync, OnTradeTransaction, Trade request structure, Trade transaction
structure, Trade transaction types, Trade operation types, Client terminal events

© 2000-2025, MetaQuotes Ltd.


1799 Event Handling

OnBookEvent
The function is called in indicators and EAs when the BookEvent event occurs. It is meant for handling
Depth of Mark et changes.

void OnBookEvent(
const string& symbol // symbol
);

Parameters
symbol
[in] Name of a symbol the BookEvent has arrived for

Return Value

No return value
Note

To get the BookEvent events for any symbol, simply subscribe to receive them for this symbol using
the MarketBookAdd() function. To cancel subscription for receiving the BookEvent for a certain
symbol, call the MarketBookRelease() function.
The BookEvent broadcasts within the entire chart. This means that if one application on a chart
subscribes to the BookEvent using the MarketBookAdd function, all other indicators and EAs
launched on the same chart and having the OnBookEvent() handler receive this event as well.
Therefore, it is necessary to analyze a symbol name passed to the OnBookEvent() handler as the
symbol parameter.

S eparate BookEvent counters sorted by symbols are provided for all applications running on the same
chart. This means that each chart may have multiple subscriptions to different symbols, and a
counter is provided for each symbol. S ubscribing and unsubscribing from BookEvent changes the
subscription counter for specified symbols only within one chart. In other words, there may be two
adjacent charts to the BookEvent for the same symbol but different subscription counter values.
The initial subscription counter value is zero. At each MarketBookAdd() call, the subscription counter
for a specified symbol on the chart is increased by one (chart symbol and symbol in MarketBookAdd()
do not have to match). W hen calling MarketBookRelease(), the counter of subscriptions for a
specified symbol within the chart is decreased by one. The BookEvent events for any symbol are
broadcast within the chart till the counter is equal to zero. Therefore, it is important that each
MQL5 program that contains MarketBookAdd () calls correctly unsubscribes from getting events for
each symbol using MarketBookRelease () at the end of its work. To achieve this, the number of
MarketBookAdd() and MarketBookRelease() calls should be even for each call during the entire MQL5
program lifetime. Using flags or custom subscription counters within the program allows you to
safely work with BookEvent events and prevents disabling subscriptions for getting this event in
third-party programs within the same chart.
BookEvent events are never s k ipped and are always placed into a queue even if handling the
previous BookEvent handling is not over yet.

Example

//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1800 Event Handling

//| OnBookEvent_Sample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com/en/articles/2635"
#property version "1.00"
#property description "Example of measuring the market depth refresh rate using OnBookEvent()"
#property description "The code is taken from the article https://www.mql5.com/en/articles/2635"
//--- input parameters
input ulong ExtCollectTime =30; // test time in seconds
input ulong ExtSkipFirstTicks=10; // number of ticks skipped at start
//--- flag of subscription to BookEvent events
bool book_subscribed=false;
//--- array for accepting requests from the market depth
MqlBookInfo book[];
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- show the start
Comment(StringFormat("Waiting for the first %I64u ticks to arrive",ExtSkipFirstTicks));
PrintFormat("Waiting for the first %I64u ticks to arrive",ExtSkipFirstTicks);
//--- enable market depth broadcast
if(MarketBookAdd(_Symbol))
{
book_subscribed=true;
PrintFormat("%s: MarketBookAdd(%s) function returned true",__FUNCTION__,_Symbol);
}
else
PrintFormat("%s: MarketBookAdd(%s) function returned false! GetLastError()=%d",__FUNCTION__,_
//--- successful initialization
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Deinitialize expert |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- display deinitialization reason code
Print(__FUNCTION__,": Deinitialization reason code = ",reason);
//--- cancel subscription for getting market depth events
if(book_subscribed)
{
if(!MarketBookRelease(_Symbol))
PrintFormat("%s: MarketBookRelease(%s) returned false! GetLastError()=%d",_Symbol,GetLastE
else

© 2000-2025, MetaQuotes Ltd.


1801 Event Handling

book_subscribed=false;
}
//---
}
//+------------------------------------------------------------------+
//| BookEvent function |
//+------------------------------------------------------------------+
void OnBookEvent(const string &symbol)
{
static ulong starttime=0; // test start time
static ulong tickcounter=0; // market depth update counter
//--- work with depth market events only if we subscribed to them ourselves
if(!book_subscribed)
return;
//--- count updates only for a certain symbol
if(symbol!=_Symbol)
return;
//--- skip first ticks to clear the queue and to prepare
tickcounter++;
if(tickcounter<ExtSkipFirstTicks)
return;
//--- remember the start time
if(tickcounter==ExtSkipFirstTicks)
starttime=GetMicrosecondCount();
//--- request for the market depth data
MarketBookGet(symbol,book);
//--- when to stop?
ulong endtime=GetMicrosecondCount()-starttime;
ulong ticks =1+tickcounter-ExtSkipFirstTicks;
// how much time has passed in microseconds since the start of the test?
if(endtime>ExtCollectTime*1000*1000)
{
PrintFormat("%I64u ticks for %.1f seconds: %.1f ticks/sec ",ticks,endtime/1000.0/1000.0,ticks
ExpertRemove();
return;
}
//--- display the counters in the comment field
if(endtime>0)
Comment(StringFormat("%I64u ticks for %.1f seconds: %.1f ticks/sec ",ticks,endtime/1000.0/100
}

See also
MarketBookAdd, MarketBookRelease, MarketBookGet, OnTrade, OnTradeTransaction, OnTick, Event
handling functions, Program running, Client terminal events

© 2000-2025, MetaQuotes Ltd.


1802 Event Handling

OnChartEvent
The function is called in indicators and EAs when the ChartEvent event occurs. The function is meant
for handling chart changes made by a user or an MQL5 program.
void OnChartEvent()
const int id, // event ID
const long& lparam, // long type event parameter
const double& dparam, // double type event parameter
const string& sparam // string type event parameter
);

Parameters
id
[in] Event ID from the ENUM _CHART_EVENT enumeration.
lparam
[in] long type event parameter
dparam
[in] double type event parameter
sparam
[in] string type event parameter

Return Value

No return value
Note

There are 11 types of events that can be handled using the predefined OnChartEvent() function.
65535 IDs from CHAR T EVENT _CUS TOM to CHAR T EVENT _CUS TOM _L AS T inclusive are provided for
custom events. To generate a custom event, use the EventChartCustom() function.
S hort event description from
the ENUM _CHART_EVENT enumeration:
· CHARTEVENT_KEYDOWN — pressing a key on the keyboard when a chart window is in focus ;
· CHARTEVENT_MOUSE_MOVE — moving the mouse and mouse button clicks (if
CHART_EVENT_MOUSE_MOVE=true for a chart);
· CHARTEVENT_OBJECT_CREATE — create a graphical object (if
CHART_EVENT_OBJECT_CREATE=true for a chart);
· CHARTEVENT_OBJECT_CHANGE — change object properties via the properties dialog;
· CHARTEVENT_OBJECT_DELETE — delete a graphical object (if
CHART_EVENT_OBJECT_DELETE=true for a chart);
· CHARTEVENT_CLICK — clicking on a chart;
· CHARTEVENT_OBJECT_CLICK — mouse click on a graphical object belonging to a chart;
· CHARTEVENT_OBJECT_DRAG — dragging a graphical object with a mouse;
· CHARTEVENT_OBJECT_ENDEDIT — finish editing text in the Edit input box of a graphical object
(OBJ_EDIT);
· CHARTEVENT_CHART_CHANGE — change a chart;

© 2000-2025, MetaQuotes Ltd.


1803 Event Handling

· CHARTEVENT_CUS TOM+n — custom event ID, where n is within the range from 0 to 65535.
CHARTEVENT_CUS TOM _LAS T contains the last acceptable custom event ID
(CHARTEVENT_CUS TOM+65535).
All MQL5 programs work in threads other than the main thread of the application. The main
application thread is responsible for handling all W indows system messages and, in its turn,
generates W indows messages for its own application as a result of this handling. For example,
moving the mouse on a chart (W M _MOUSE_MOVE event) generates several system messages for
subsequent rendering of the application window, and also sends internal messages to experts and
indicators launched on the chart. A situation may occur, where the main application thread has not
yet processed the W M _PAINT system message (and therefore has not yet rendered the modified
chart), while an EA or an indicator has already received the mouse movement event. In this case,
the chart property CHART_FIRS T_VIS IBLE_BAR will be changed only after the chart is rendered.
Foreach event type, the inputs of the OnChartEvent() function have certain values necessary for
handling that event. The table lists events and values passed via the parameters.

Event 'id' parameter 'lparam' 'dparam' 'sparam'


value parameter value parameter value parameter value

Keystrok e event CHARTEVENT_KE pressed button The number of S tring value of


YDOWN code k eypresses the bit mas k,
generated while which describes
the key was held the status of the
in the pressed k eyboard k eys
state
Mouse events (if CHARTEVENT_M X coordinate Y coordinate S tring value of
CHART_EVENT_ OUSE_MOVE the bit mas k,
MOUSE_MOVE=tr which describes
ue for a chart) the status of the
mouse keys
Mouse wheel CHARTEVENT_M Flags of states The Delta value —
event (if OUSE_WHEEL of keys and of the mouse
CHART_EVENT_ mouse buttons, wheel scroll
MOUSE_WHEEL= X and Y
true for the coordinates of
chart) the cursor. S ee
the description
in the example
Creating a CHARTEVENT_O — — Name of a
graphical object BJECT _CREAT E created
(if graphical object
CHART_EVENT_
OBJECT_CREATE
=true for a
chart)
Changing object CHARTEVENT_O — — Name of a
properties via BJECT _CHANGE changed
the properties graphical object
dialog

© 2000-2025, MetaQuotes Ltd.


1804 Event Handling

Event 'id' parameter 'lparam' 'dparam' 'sparam'


value parameter value parameter value parameter value

R emoving a CHARTEVENT_O — — Name of a


graphical object BJECT _DEL ET E removed
(if graphical object
CHART_EVENT_
OBJECT_DELETE
=true for a
chart)
Mouse click on a CHARTEVENT_C X coordinate Y coordinate —
chart LICK
Mouse click on a CHARTEVENT_O X coordinate Y coordinate Name of a
graphical object BJECT _CLICK graphical object
the event has
occurred on
Moving a CHARTEVENT_O — — Name of a
graphical object BJECT _DRAG moved graphical
with mouse object
Finishing a text CHARTEVENT_O — — Name of the
editing in the BJECT _ENDEDIT " Input field"
" Input field" graphical object,
graphical object in which text
input box editing
completed
R esizing the CHARTEVENT_C — — —
chart or HAR T _CHANGE
modifying the
chart properties
via the
properties dialog
window
Custom event CHARTEVENT_C Value defined by Value defined by Value defined by
with N number US TOM+N the the the
EventChartCusto EventChartCusto EventChartCusto
m() function m() function m() function

Sample chart event listener:

//+------------------------------------------------------------------+
//| OnChartEvent_Sample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

© 2000-2025, MetaQuotes Ltd.


1805 Event Handling

#property description "Sample chart event listener and custom events generator"
//--- service keys IDs
#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
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- display the CHARTEVENT_CUSTOM constant value
Print("CHARTEVENT_CUSTOM=",CHARTEVENT_CUSTOM);
//---
Print("Launched the EA ",MQLInfoString(MQL5_PROGRAM_NAME));
//--- set the flag of receiving chart object creation events
ChartSetInteger(ChartID(),CHART_EVENT_OBJECT_CREATE,true);
//--- set the flag of receiving chart object removal events
ChartSetInteger(ChartID(),CHART_EVENT_OBJECT_DELETE,true);
//--- enabling mouse wheel scrolling messages
ChartSetInteger(0,CHART_EVENT_MOUSE_WHEEL,1);
//--- forced updating of chart properties ensures readiness for event processing
ChartRedraw();
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- tick counter for generating a custom event
static int tick_counter=0;
//--- divide accumulated ticks by this value
int simple_number=113;
//---
tick_counter++;
//--- send a custom event if the tick counter is multiple of simple_number
if(tick_counter%simple_number==0)
{
//--- form custom event ID from 0 to 65535
ushort custom_event_id=ushort(tick_counter%65535);
//--- send a custom event with parameters filling

© 2000-2025, MetaQuotes Ltd.


1806 Event Handling

EventChartCustom(ChartID(),custom_event_id,tick_counter,SymbolInfoDouble(Symbol(),SYMBOL_BID)
//--- add to a log for analyzing the example results
Print(__FUNCTION__,": Sent a custom event ID=",custom_event_id);
}
//---
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- keypress
if(id==CHARTEVENT_KEYDOWN)
{
switch((int)lparam)
{
case KEY_NUMLOCK_LEFT: Print("Pressed KEY_NUMLOCK_LEFT"); break;
case KEY_LEFT: Print("Pressed KEY_LEFT"); break;
case KEY_NUMLOCK_UP: Print("Pressed KEY_NUMLOCK_UP"); break;
case KEY_UP: Print("Pressed KEY_UP"); break;
case KEY_NUMLOCK_RIGHT: Print("Pressed KEY_NUMLOCK_RIGHT"); break;
case KEY_RIGHT: Print("Pressed KEY_RIGHT"); break;
case KEY_NUMLOCK_DOWN: Print("Pressed KEY_NUMLOCK_DOWN"); break;
case KEY_DOWN: Print("Pressed KEY_DOWN"); break;
case KEY_NUMPAD_5: Print("Pressed KEY_NUMPAD_5"); break;
case KEY_NUMLOCK_5: Print("Pressed KEY_NUMLOCK_5"); break;
default: Print("Pressed unlisted key");
}
}
//--- left-clicking on a chart
if(id==CHARTEVENT_CLICK)
Print("Mouse click coordinates on a chart: x = ",lparam," y = ",dparam);
//--- clicking on a graphical object
if(id==CHARTEVENT_OBJECT_CLICK)
Print("Clicking a mouse button on an object named '"+sparam+"'");
//--- object removed
if(id==CHARTEVENT_OBJECT_DELETE)
Print("Removed object named ",sparam);
//--- object created
if(id==CHARTEVENT_OBJECT_CREATE)
Print("Created object named ",sparam);
//--- changed object
if(id==CHARTEVENT_OBJECT_CHANGE)
Print("Changed object named ",sparam);
//--- object moved or anchor point coordinates changed
if(id==CHARTEVENT_OBJECT_DRAG)

© 2000-2025, MetaQuotes Ltd.


1807 Event Handling

Print("Changing anchor points of object named ",sparam);


//--- changed a text in the input field of the Edit graphical object
if(id==CHARTEVENT_OBJECT_ENDEDIT)
Print("Changed text in Edit object ",sparam," id=",id);
//--- mouse movement events
if(id==CHARTEVENT_MOUSE_MOVE)
Comment("POINT: ",(int)lparam,",",(int)dparam,"\n",MouseState((uint)sparam));
if(id==CHARTEVENT_MOUSE_WHEEL)
{
//--- Consider the state of mouse buttons and wheel for this event
int flg_keys = (int)(lparam>>32); // The flag of states of the Ctrl and Shift keys,
int x_cursor = (int)(short)lparam; // X coordinate where the mouse wheel event occurr
int y_cursor = (int)(short)(lparam>>16); // Y coordinate where the mouse wheel event occurr
int delta = (int)dparam; // Total value of mouse scroll, triggers when +120
//--- handling the flag
string str_keys="";
if((flg_keys&0x0001)!=0)
str_keys+="LMOUSE ";
if((flg_keys&0x0002)!=0)
str_keys+="RMOUSE ";
if((flg_keys&0x0004)!=0)
str_keys+="SHIFT ";
if((flg_keys&0x0008)!=0)
str_keys+="CTRL ";
if((flg_keys&0x0010)!=0)
str_keys+="MMOUSE ";
if((flg_keys&0x0020)!=0)
str_keys+="X1MOUSE ";
if((flg_keys&0x0040)!=0)
str_keys+="X2MOUSE ";

if(str_keys!="")
str_keys=", keys='"+StringSubstr(str_keys,0,StringLen(str_keys)-1)+"'";
PrintFormat("%s: X=%d, Y=%d, delta=%d%s",EnumToString(CHARTEVENT_MOUSE_WHEEL),x_cursor,y_curs
}
//--- event of resizing the chart or modifying the chart properties using the properties dialog win
if(id==CHARTEVENT_CHART_CHANGE)
Print("Changing the chart size or properties");
//--- custom event
if(id>CHARTEVENT_CUSTOM)
PrintFormat("Custom event ID=%d, lparam=%d, dparam=%G, sparam=%s",id,lparam,dparam,sparam);
}
//+------------------------------------------------------------------+
//| MouseState |
//+------------------------------------------------------------------+
string MouseState(uint state)
{
string res;
res+="\nML: " +(((state& 1)== 1)?"DN":"UP"); // mouse left

© 2000-2025, MetaQuotes Ltd.


1808 Event Handling

res+="\nMR: " +(((state& 2)== 2)?"DN":"UP"); // mouse right


res+="\nMM: " +(((state&16)==16)?"DN":"UP"); // mouse middle
res+="\nMX: " +(((state&32)==32)?"DN":"UP"); // mouse first X key
res+="\nMY: " +(((state&64)==64)?"DN":"UP"); // mouse second X key
res+="\nSHIFT: "+(((state& 4)== 4)?"DN":"UP"); // shift key
res+="\nCTRL: " +(((state& 8)== 8)?"DN":"UP"); // control key
return(res);
}

See also
EventChartCustom, Types of chart events, Event handling functions, Program running, Client
terminal events

© 2000-2025, MetaQuotes Ltd.


1809 Event Handling

OnTester
The function is called in Expert Advisors when the Tester event occurs to perform necessary actions
after testing.
double OnTester(void);

Return Value

Value of the custom criterion optimization for assessing test results.


Note

The OnTester() function can be used only when testing EAs and is intended primarily for the
calculation of a value that is used as a 'Custom max' criterion when optimizing input parameters.
During the genetic optimization, sorting results within one generation is performed in descending
order. This means that the results with the highest value are deemed the best from the optimization
criterion point of view. The worst values ​for such sorting are placed at the end and are subsequently
discarded. Therefore, they do not take part in forming the next generation.
Thus, the OnTester() function allows you not only to create and save your own test results reports,
but also control the optimization process to find the best parameters of the trading strategy.
Below is an example of calculating the custom criterion optimization. The idea is to calculate the
linear regression of the balance graph. It is described in the article Optimizing a strategy using
balance graph and comparing results with "Balance + max S harpe Ratio" criterion.
//+------------------------------------------------------------------+
//| OnTester_Sample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "Sample EA with the OnTester() handler"
#property description "As a custom optimization criterion, "
#property description "the ratio of the balance graph linear regression"
#property description "divided by the deviation mean-square error is returned"
//--- include the class for trading operations
#include <Trade\Trade.mqh>
//--- EA input parameters
input double Lots = 0.1; // Volume
input int Slippage = 10; // Allowable slippage
input int MovingPeriod = 80; // Moving average period
input int MovingShift = 6; // Moving average shift
//--- global variables
int IndicatorHandle=0; // indicator handle
bool IsHedging=false; // flag of the account
CTrade trade; // for performing trading operations
//---

© 2000-2025, MetaQuotes Ltd.


1810 Event Handling

#define EA_MAGIC 18052018


//+------------------------------------------------------------------+
//| Check for position opening conditions |
//+------------------------------------------------------------------+
void CheckForOpen(void)
{
MqlRates rt[2];
//--- trade only at the start of a new bar
if(CopyRates(_Symbol,_Period,0,2,rt)!=2)
{
Print("CopyRates of ",_Symbol," failed, no history");
return;
}
//--- tick volume
if(rt[1].tick_volume>1)
return;
//--- receive moving average values
double ma[1];
if(CopyBuffer(IndicatorHandle,0,1,1,ma)!=1)
{
Print("CopyBuffer from iMA failed, no data");
return;
}
//--- check for a signal presence
ENUM_ORDER_TYPE signal=WRONG_VALUE;
//--- candle opened higher but closed below the moving average
if(rt[0].open>ma[0] && rt[0].close<ma[0])
signal=ORDER_TYPE_BUY; // buy signal
else // candle opened lower but closed above the moving average
{
if(rt[0].open<ma[0] && rt[0].close>ma[0])
signal=ORDER_TYPE_SELL;// sell signal
}
//--- additional checks
if(signal!=WRONG_VALUE)
{
if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
{
double price=SymbolInfoDouble(_Symbol,signal==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK);
trade.PositionOpen(_Symbol,signal,Lots,price,0,0);
}
}
//---
}
//+------------------------------------------------------------------+
//| Check for position closing conditions |
//+------------------------------------------------------------------+
void CheckForClose(void)
{

© 2000-2025, MetaQuotes Ltd.


1811 Event Handling

MqlRates rt[2];
//--- trade only at the start of a new bar
if(CopyRates(_Symbol,_Period,0,2,rt)!=2)
{
Print("CopyRates of ",_Symbol," failed, no history");
return;
}
if(rt[1].tick_volume>1)
return;
//--- receive moving average values
double ma[1];
if(CopyBuffer(IndicatorHandle,0,1,1,ma)!=1)
{
Print("CopyBuffer from iMA failed, no data");
return;
}
//--- position has already been selected earlier using PositionSelect()
bool signal=false;
long type=PositionGetInteger(POSITION_TYPE);
//--- candle opened higher but closed below the moving average - close a short position
if(type==(long)POSITION_TYPE_SELL && rt[0].open>ma[0] && rt[0].close<ma[0])
signal=true;
//--- candle opened lower but closed above the moving average - close a long position
if(type==(long)POSITION_TYPE_BUY && rt[0].open<ma[0] && rt[0].close>ma[0])
signal=true;
//--- additional checks
if(signal)
{
if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
trade.PositionClose(_Symbol,Slippage);
}
//---
}
//+-------------------------------------------------------------------+
//| Select a position considering an account type: Netting or Hedging |
//+-------------------------------------------------------------------+
bool SelectPosition()
{
bool res=false;
//--- select a position for a Hedging account
if(IsHedging)
{
uint total=PositionsTotal();
for(uint i=0; i<total; i++)
{
string position_symbol=PositionGetSymbol(i);
if(_Symbol==position_symbol && EA_MAGIC==PositionGetInteger(POSITION_MAGIC))
{
res=true;

© 2000-2025, MetaQuotes Ltd.


1812 Event Handling

break;
}
}
}
//--- select a position for a Netting account
else
{
if(!PositionSelect(_Symbol))
return(false);
else
return(PositionGetInteger(POSITION_MAGIC)==EA_MAGIC); //---check Magic number
}
//--- execution result
return(res);
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit(void)
{
//--- set a trading type: Netting or Hedging
IsHedging=((ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE)==ACCOUNT_MARGIN_MOD
//--- initialize an object for correct position control
trade.SetExpertMagicNumber(EA_MAGIC);
trade.SetMarginMode();
trade.SetTypeFillingBySymbol(Symbol());
trade.SetDeviationInPoints(Slippage);
//--- create Moving Average indicator
IndicatorHandle=iMA(_Symbol,_Period,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE);
if(IndicatorHandle==INVALID_HANDLE)
{
printf("Error creating iMA indicator");
return(INIT_FAILED);
}
//--- ok
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick(void)
{
//--- if a position is already opened, check the closing condition
if(SelectPosition())
CheckForClose();
// check the position opening condition
CheckForOpen();
//---
}

© 2000-2025, MetaQuotes Ltd.


1813 Event Handling

//+------------------------------------------------------------------+
//| Tester function |
//+------------------------------------------------------------------+
double OnTester()
{
//--- custom criterion optimization value (the higher, the better)
double ret=0.0;
//--- get trade results to the array
double array[];
double trades_volume;
GetTradeResultsToArray(array,trades_volume);
int trades=ArraySize(array);
//--- if there are less than 10 trades, test yields no positive results
if(trades<10)
return (0);
//--- average result per trade
double average_pl=0;
for(int i=0;i<ArraySize(array);i++)
average_pl+=array[i];
average_pl/=trades;
//--- display the message for the single-test mode
if(MQLInfoInteger(MQL_TESTER) && !MQLInfoInteger(MQL_OPTIMIZATION))
PrintFormat("%s: Trades=%d, Average profit=%.2f",__FUNCTION__,trades,average_pl);
//--- calculate linear regression ratios for the profit graph
double a,b,std_error;
double chart[];
if(!CalculateLinearRegression(array,chart,a,b))
return (0);
//--- calculate the error of the chart deviation from the regression line
if(!CalculateStdError(chart,a,b,std_error))
return (0);
//--- calculate the ratio of trend profits to the standard deviation
ret=(std_error == 0.0) ? a*trades : a*trades/std_error;
//--- return custom criterion optimization value
return(ret);
}
//+------------------------------------------------------------------+
//| Get the array of profits/losses from deals |
//+------------------------------------------------------------------+
bool GetTradeResultsToArray(double &pl_results[],double &volume)
{
//--- request the complete trading history
if(!HistorySelect(0,TimeCurrent()))
return (false);
uint total_deals=HistoryDealsTotal();
volume=0;
//--- set the initial size of the array with a margin - by the number of deals in history
ArrayResize(pl_results,total_deals);
//--- counter of deals that fix the trading result - profit or loss

© 2000-2025, MetaQuotes Ltd.


1814 Event Handling

int counter=0;
ulong ticket_history_deal=0;
//--- go through all deals
for(uint i=0;i<total_deals;i++)
{
//--- select a deal
if((ticket_history_deal=HistoryDealGetTicket(i))>0)
{
ENUM_DEAL_ENTRY deal_entry =(ENUM_DEAL_ENTRY)HistoryDealGetInteger(ticket_history_deal,DE
long deal_type =HistoryDealGetInteger(ticket_history_deal,DEAL_TYPE);
double deal_profit =HistoryDealGetDouble(ticket_history_deal,DEAL_PROFIT);
double deal_volume =HistoryDealGetDouble(ticket_history_deal,DEAL_VOLUME);
//--- we are only interested in trading operations
if((deal_type!=DEAL_TYPE_BUY) && (deal_type!=DEAL_TYPE_SELL))
continue;
//--- only deals that fix profits/losses
if(deal_entry!=DEAL_ENTRY_IN)
{
//--- write the trading result to the array and increase the counter of deals
pl_results[counter]=deal_profit;
volume+=deal_volume;
counter++;
}
}
}
//--- set the final size of the array
ArrayResize(pl_results,counter);
return (true);
}
//+------------------------------------------------------------------+
//| Calculate the linear regression y=a*x+b |
//+------------------------------------------------------------------+
bool CalculateLinearRegression(double &change[],double &chartline[],
double &a_coef,double &b_coef)
{
//--- check for data sufficiency
if(ArraySize(change)<3)
return (false);
//--- create a chart array with an accumulation
int N=ArraySize(change);
ArrayResize(chartline,N);
chartline[0]=change[0];
for(int i=1;i<N;i++)
chartline[i]=chartline[i-1]+change[i];
//--- now, calculate regression ratios
double x=0,y=0,x2=0,xy=0;
for(int i=0;i<N;i++)
{
x=x+i;

© 2000-2025, MetaQuotes Ltd.


1815 Event Handling

y=y+chartline[i];
xy=xy+i*chartline[i];
x2=x2+i*i;
}
a_coef=(N*xy-x*y)/(N*x2-x*x);
b_coef=(y-a_coef*x)/N;
//---
return (true);
}
//+------------------------------------------------------------------+
//| Calculate mean-square deviation error for specified a and b |
//+------------------------------------------------------------------+
bool CalculateStdError(double &data[],double a_coef,double b_coef,double &std_err)
{
//--- sum of error squares
double error=0;
int N=ArraySize(data);
if(N<=2)
return (false);
for(int i=0;i<N;i++)
error+=MathPow(a_coef*i+b_coef-data[i],2);
std_err=MathSqrt(error/(N-2));
//---
return (true);
}

See also

Testing trading strategies, TesterHideIndicators, W orking with optimization results,


TesterS tatistics, OnTesterInit, OnTesterDeinit, OnTesterPass, MQL_TES TER, MQL_OPTIMIZATION,
FileOpen, FileW rite, FileLoad, FileS ave

© 2000-2025, MetaQuotes Ltd.


1816 Event Handling

OnTesterInit
The function is called in EAs when the TesterInit event occurs to perform necessary actions before
optimization in the strategy tester. There are two function types.
The version that returns the result
int OnTesterInit(void);

Return Value

int type value, zero means successful initialization of an EA launched on a chart before optimization
starts.
The OnTesterInit() call that returns the execution result is recommended for use since it not only
allows for program initialization, but also returns an error code in case of an early optimization stop.
R eturn of any value other than INIT _SUCCEEDED (0) means an error, no optimization is launched.

The version without a result return is left only for compatibility with old codes. Not recommended
for use
void OnTesterInit(void);

Note

The TesterInit event is generated before EA optimization in the strategy tester starts. At this
event, an EA having OnTesterDeInit() or OnTesterPass() event handler is automatically downloaded
on a separate terminal chart. It has the symbol and the period that have been specified in the
tester.
S uch an event receives the TesterInit, TesterDeinit and TesterPass events, but not Init, Deinit and
NewTick ones. Accordingly, all necessary logic for processing the results of each pass during
optimization should be implemented in the OnTesterInit (), OnTesterDeinit () and OnTesterPass ()
handlers.
The result of each single pass during a strategy optimization can be passed via a frame from the
OnTester () handler using the FrameAdd () function.
The OnTesterInit() function is used to initiate an Expert Advisor before start of optimization for
further processing of optimization results. It is always used together with the OnTesterDeinit()
handler.
The time for OnTesterInit() execution is limited. If it is exceeded, the EA is forcibly stopped, while
the optimization itself is canceled. A message is displayed in the tester journal:
TesterOnTesterInit works too long. Tester cannot be initialized.

The example is taken from OnTick. The OnTesterInit() handler is added for setting optimization
parameters :
//+------------------------------------------------------------------+
//| OnTesterInit_Sample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1817 Event Handling

#property copyright "Copyright 2000-2024, MetaQuotes Ltd."


#property link "https://www.mql5.com"
#property version "1.00"
#property description "Sample EA with the OnTesterInit() handler,"
#property description "in which values and limitations of "
#property description "inputs during optimization are set"

input double lots=0. 1; // volume in lots


input double kATR=3; // signal candle length in ATR
input int ATRperiod=20; // ATR indicator period
input int holdbars=8; // number of bars to hold position on
input int slippage=10; // allowable slippage
input bool revers=false; // reverse the signal?
input ulong EXPERT_MAGIC=0; // EA's MagicNumber
//--- for storing the ATR indicator handle
int atr_handle;
//--- here we will store the last ATR values and the candle body
double last_atr,last_body;
datetime lastbar_timeopen;
double trade_lot;
//--- remember optimization start time
datetime optimization_start;
//--- for displaying duration on a chart after the end of optimization
string report;
//+------------------------------------------------------------------+
//| TesterInit function |
//+------------------------------------------------------------------+
void OnTesterInit()
{
//--- set the values of inputs for optimization
ParameterSetRange("lots",false,0.1,0,0,0);
ParameterSetRange("kATR",true,3.0,1.0,0.3,7.0);
ParameterSetRange("ATRperiod",true,10,15,1,30);
ParameterSetRange("holdbars",true,5,3,1,15);
ParameterSetRange("slippage",false,10,0,0,0);
ParameterSetRange("revers",true,false,false,1,true);
ParameterSetRange("EXPERT_MAGIC",false,123456,0,0,0);
Print("Initial values and optimization parameter limitations are set");
//--- remember optimization start
optimization_start=TimeLocal();
report=StringFormat("%s: optimization launched at %s",
__FUNCTION__,TimeToString(TimeLocal(),TIME_MINUTES|TIME_SECONDS));
//--- show messages on the chart and the terminal journal
Print(report);
Comment(report);
//---
}
//+------------------------------------------------------------------+
//| TesterDeinit function |

© 2000-2025, MetaQuotes Ltd.


1818 Event Handling

//+------------------------------------------------------------------+
void OnTesterDeinit()
{
//--- optimization duration
string log_message=StringFormat("%s: optimization took %d seconds",
__FUNCTION__,TimeLocal()-optimization_start);
PrintFormat(log_message);
report=report+"\r\n"+log_message;
Comment(report);
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- initialize global variables
last_atr=0;
last_body=0;
//--- set the correct volume
double min_lot=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
trade_lot=lots>min_lot? lots:min_lot;
//--- create ATR indicator handle
atr_handle=iATR(_Symbol,_Period,ATRperiod);
if(atr_handle==INVALID_HANDLE)
{
PrintFormat("%s: failed to create iATR, error code %d",__FUNCTION__,GetLastError());
return(INIT_FAILED);
}
//--- successful EA initialization
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- trading signal
static int signal=0; // +1 means a buy signal, -1 means a sell signal
//--- check and close old positions opened more than 'holdbars' bars ago
ClosePositionsByBars(holdbars,slippage,EXPERT_MAGIC);
//--- check for a new bar
if(isNewBar())
{
//--- check for a signal presence
signal=CheckSignal();
}
//--- if a netting position is opened, skip the signal - wait till it closes
if(signal!=0 && PositionsTotal()>0 && (ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGI
{

© 2000-2025, MetaQuotes Ltd.


1819 Event Handling

signal=0;
return; // exit the NewTick event handler and do not enter the market before a new bar appear
}
//--- for a hedging account, each position is held and closed separately
if(signal!=0)
{
//--- buy signal
if(signal>0)
{
PrintFormat("%s: Buy signal! Revers=%s",__FUNCTION__,string(revers));
if(Buy(trade_lot,slippage,EXPERT_MAGIC))
signal=0;
}
//--- sell signal
if(signal<0)
{
PrintFormat("%s: Sell signal! Revers=%s",__FUNCTION__,string(revers));
if(Sell(trade_lot,slippage,EXPERT_MAGIC))
signal=0;
}
}
//--- OnTick function end
}
//+------------------------------------------------------------------+
//| Check for a new trading signal |
//+------------------------------------------------------------------+
int CheckSignal()
{
//--- 0 means no signal
int res=0;
//--- get ATR value on a penultimate complete bar (the bar index is 2)
double atr_value[1];
if(CopyBuffer(atr_handle,0,2,1,atr_value)!=-1)
{
last_atr=atr_value[0];
//--- get data on the last closed bar to the MqlRates type array
MqlRates bar[1];
if(CopyRates(_Symbol,_Period,1,1,bar)!=-1)
{
//--- calculate the bar body size on the last complete bar
last_body=bar[0].close-bar[0].open;
//--- if the body of the last bar (with index 1) exceeds the previous ATR value (on the ba
if(MathAbs(last_body)>kATR*last_atr)
res=last_body>0?1:-1; // positive value for the upward candle
}
else
PrintFormat("%s: Failed to receive the last bar! Error",__FUNCTION__,GetLastError());
}
else

© 2000-2025, MetaQuotes Ltd.


1820 Event Handling

PrintFormat("%s: Failed to receive ATR indicator value! Error",__FUNCTION__,GetLastError());


//--- if reverse trading mode is enabled
res=revers?-res:res; // reverse the signal if necessary (return -1 instead of 1 and vice versa)
//--- return a trading signal value
return (res);
}
//+------------------------------------------------------------------+
//| Return 'true' when a new bar appears |
//+------------------------------------------------------------------+
bool isNewBar(const bool print_log=true)
{
static datetime bartime=0; // store open time of the current bar
//--- get open time of the zero bar
datetime currbar_time=iTime(_Symbol,_Period,0);
//--- if open time changes, a new bar has arrived
if(bartime!=currbar_time)
{
bartime=currbar_time;
lastbar_timeopen=bartime;
//--- display data on open time of a new bar in the log
if(print_log && !(MQLInfoInteger(MQL_OPTIMIZATION)||MQLInfoInteger(MQL_TESTER)))
{
//--- display a message with a new bar open time
PrintFormat("%s: new bar on %s %s opened at %s",__FUNCTION__,_Symbol,
StringSubstr(EnumToString(_Period),7),
TimeToString(TimeCurrent(),TIME_SECONDS));
//--- get data on the last tick
MqlTick last_tick;
if(!SymbolInfoTick(Symbol(),last_tick))
Print("SymbolInfoTick() failed, error = ",GetLastError());
//--- display the last tick time up to milliseconds
PrintFormat("Last tick was at %s.%03d",
TimeToString(last_tick.time,TIME_SECONDS),last_tick.time_msc%1000);
}
//--- we have a new bar
return (true);
}
//--- no new bar
return (false);
}
//+------------------------------------------------------------------+
//| Buy at a market price with a specified volume |
//+------------------------------------------------------------------+
bool Buy(double volume,ulong deviation=10,ulong magicnumber=0)
{
//--- buy at a market price
return (MarketOrder(ORDER_TYPE_BUY,volume,deviation,magicnumber));
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1821 Event Handling

//| Sell at a market price with a specified volume |


//+------------------------------------------------------------------+
bool Sell(double volume,ulong deviation=10,ulong magicnumber=0)
{
//--- sell at a market price
return (MarketOrder(ORDER_TYPE_SELL,volume,deviation,magicnumber));
}
//+------------------------------------------------------------------+
//| Close positions by hold time in bars |
//+------------------------------------------------------------------+
void ClosePositionsByBars(int holdtimebars,ulong deviation=10,ulong magicnumber=0)
{
int total=PositionsTotal(); // number of open positions
//--- iterate over open positions
for(int i=total-1; i>=0; i--)
{
//--- position parameters
ulong position_ticket=PositionGetTicket(i); // position
string position_symbol=PositionGetString(POSITION_SYMBOL); // symbol
ulong magic=PositionGetInteger(POSITION_MAGIC); // position
datetime position_open=(datetime)PositionGetInteger(POSITION_TIME); // position
int bars=iBarShift(_Symbol,PERIOD_CURRENT,position_open)+1; // how many

//--- if a position's lifetime is already large, while MagicNumber and a symbol match
if(bars>holdtimebars && magic==magicnumber && position_symbol==_Symbol)
{
int digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS); // number o
double volume=PositionGetDouble(POSITION_VOLUME); // position
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); // position
string str_type=StringSubstr(EnumToString(type),14);
StringToLower(str_type); // lower the text case for correct message formatting
PrintFormat("Close position #%I64u %s %s %.2f",
position_ticket,position_symbol,str_type,volume);
//--- set an order type and sending a trade request
if(type==POSITION_TYPE_BUY)
MarketOrder(ORDER_TYPE_SELL,volume,deviation,magicnumber,position_ticket);
else
MarketOrder(ORDER_TYPE_BUY,volume,deviation,magicnumber,position_ticket);
}
}
}
//+------------------------------------------------------------------+
//| Prepare and send a trade request |
//+------------------------------------------------------------------+
bool MarketOrder(ENUM_ORDER_TYPE type,double volume,ulong slip,ulong magicnumber,ulong pos_ticket=0
{
//--- declaring and initializing structures
MqlTradeRequest request={};
MqlTradeResult result={};

© 2000-2025, MetaQuotes Ltd.


1822 Event Handling

double price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
if(type==ORDER_TYPE_BUY)
price=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
//--- request parameters
request.action =TRADE_ACTION_DEAL; // trading operation type
request.position =pos_ticket; // position ticket if closing
request.symbol =Symbol(); // symbol
request.volume =volume; // volume
request.type =type; // order type
request.price =price; // trade price
request.deviation=slip; // allowable deviation from the price
request.magic =magicnumber; // order MagicNumber
//--- send a request
if(!OrderSend(request,result))
{
//--- display data on failure
PrintFormat("OrderSend %s %s %.2f at %.5f error %d",
request.symbol,EnumToString(type),volume,request.price,GetLastError());
return (false);
}
//--- inform of a successful operation
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
return (true);
}

See also

Testing trading strategies, W orking with optimization results, OnTesterDeinit, OnTesterPass,


ParameterGetRange, ParameterS etRange

© 2000-2025, MetaQuotes Ltd.


1823 Event Handling

OnTesterDeinit
The function is called in EAs when the TesterDeinit event occurs after EA optimization.
void OnTesterDeinit(void);

Return Value

No return value
Note

The TesterDeinit event is generated after the end of EA optimization in the strategy tester.
An EA having OnTesterDeInit() or OnTesterPass() event handler is automatically downloaded on a
separate terminal chart during the optimization start. It has the symbol and the period that have
been specified in the tester. The function is designed for the final processing of all optimization
results.
Keep in mind that optimization frames sent by test agents using the FrameAdd() function may come
in bundles and take time to deliver. Therefore, not all frames, as well as TesterPass events, may
arrive and be processed in OnTesterPass() before the end of optimization. If you want to receive all
belated frames in OnTesterDeinit(), place the code block using the FrameNext() function.
See also

Testing trading strategies, W orking with optimization results, TesterS tatistics, OnTesterInit,
OnTesterPass, ParameterGetRange, ParameterS etRange

© 2000-2025, MetaQuotes Ltd.


1824 Event Handling

OnTesterPass
The function is called in EAs when the TesterPass event occurs for handling a new data frame during
EA optimization.

void OnTesterPass(void);

Return Value

No return value
Note

The TesterPass event is generated automatically when receiving a frame during an Expert Advisor
optimization in the strategy tester.
An EA having OnTesterDeInit() or OnTesterPass() event handler is automatically downloaded on a
separate terminal chart during the optimization start. It has the symbol and the period that have
been specified in the tester. The function is meant for handling frames received from test agents
during optimization. The frame containing test results should be sent from the OnTester() handler
using the FrameAdd() function.
Keep in mind that optimization frames sent by test agents using the FrameAdd() function may come
in bundles and take time to deliver. Therefore, not all frames, as well as TesterPass events, may
arrive and be processed in OnTesterPass() before the end of optimization. If you want to receive all
belated frames in OnTesterDeinit(), place the code block using the FrameNext() function.
After completing OnTesterDeinit() optimization, it is possible to sort all received frames again using
the FrameFirst()/FrameFilter and FrameNext() functions.
See also

Testing trading strategies, W orking with optimization results, OnTesterInit, OnTesterDeinit,


FrameFirst, FrameFilter, FrameNext, FrameInputs

© 2000-2025, MetaQuotes Ltd.


1825 Market Info

Getting Market Information


These are functions intended for receiving information about the market state.

Function Action

S ymbolsTotal R eturns the number of available (selected in Market W atch or all)


symbols
S ymbolExist Checks if a symbol with a specified name exists
S ymbolName R eturns the name of a specified symbol
S ymbolS elect S elects
a symbol in the Market W atch window or removes a symbol
from the window
S ymbolIs S ynchronized Checks whether data of a selected symbol in the terminal are
synchronized with data on the trade server
S ymbolInfoDouble R eturns the double value of the symbol for the corresponding property
S ymbolInfoInteger R eturns a value of an integer type (long, datetime, int or bool) of a
specified symbol for the corresponding property
S ymbolInfoS tring R eturnsa value of the string type of a specified symbol for the
corresponding property
S ymbolInfoMarginR ate R eturns the margin rates depending on the order type and direction
S ymbolInfoTick R eturns the current prices for the specified symbol in a variable of the
M qlTick type
S ymbolInfoS essionQuote Allows receiving time of beginning and end of the specified quoting
sessions for a specified symbol and day of week.
S ymbolInfoS essionTrade Allows receiving time of beginning and end of the specified trading
sessions for a specified symbol and day of week.
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 R eturns a structure array M qlBook Info containing records of the Depth
of Market of a specified symbol

© 2000-2025, MetaQuotes Ltd.


1826 Market Info

SymbolsTotal
R eturns the number of available (selected in Market W atch or all) symbols.
int SymbolsTotal(
bool selected // True - only symbols in MarketWatch
);

Parameters
selected
[in] R equest mode. Can be true or false.

Return Value

If the 'selected' parameter is true, the function returns the number of symbols selected in
MarketW atch. If the value is false, it returns the total number of all symbols.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the number of available symbols
int total = SymbolsTotal(false); // all symbols on the server
int selected = SymbolsTotal(true); // all symbols added to the Market Watch window

//--- send the obtained data to the journal


PrintFormat("Number of available symbols on the server: %d\n"+
"Number of available symbols selected in MarketWatch: %d", total, selected);
/*
result:
Number of available symbols on the server: 140
Number of available symbols selected in MarketWatch: 11
*/
}

© 2000-2025, MetaQuotes Ltd.


1827 Market Info

SymbolExist
Checks if a symbol with a specified name exists.
bool SymbolExist(
const string name, // symbol name
bool& is_custom // custom symbol property
);

Parameters
name
[in] S ymbol name.

is_custom
[out] Custom symbol property set upon successful execution. If true, the detected symbol is a
custom one.

Return Value

If false, the symbol is not found among standard and custom ones.
Example:

#define SYMBOL_NAME "GBPUSDn"


//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare the custom symbol flag and check the presence of a symbol having its name specified i
bool custom = false;
bool result = SymbolExist(SYMBOL_NAME, custom);

//--- declare the default 'symbol not found' message text


string text = StringFormat("The symbol '%s' was not found among either the standard or custom sy

//--- if a symbol is found, create a message text depending on which list the symbol is found in
if(result)
{
//--- if this is a standard symbol
if(!custom)
text = StringFormat("The '%s' symbol is available on the server.", SYMBOL_NAME);
//--- if this is a custom symbol
else
text = StringFormat("The symbol '%s' was found in the list of custom symbols.", SYMBOL_NAM
}

//--- send the message about the check result to the journal
Print(text);
/*

© 2000-2025, MetaQuotes Ltd.


1828 Market Info

result for standard 'GBPUSD' symbol:


The 'GBPUSD' symbol is available on the server.

result for custom 'GBPUSDx' symbol:


The symbol 'GBPUSDx' was found in the list of custom symbols.

result for missing 'GBPUSDn' symbol:


The symbol 'GBPUSDn' was not found among either the standard or custom symbols.
*/
}

See also

S ymbolsTotal, S ymbolS elect, Custom symbols

© 2000-2025, MetaQuotes Ltd.


1829 Market Info

SymbolName
R eturns 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] R equest mode. If the value is true, the symbol is taken from the list of symbols selected in
MarketW atch. If the value is false, the symbol is taken from the general list.

Return Value

Value of string type with the symbol name.


Example:

#define SYMBOL_NAME "GBPHKD"

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set the flag of the server symbol search result
bool found = false;

//--- find the 'SYMBOL_NAME' symbol in the list of all server symbols
int total = SymbolsTotal(false);
for(int i=0; i<total; i++)
{
//--- get a symbol name in the list by loop index
string name = SymbolName(i, false);

//--- if this is the desired symbol, send its name and position in the list to the journal an
if(name == SYMBOL_NAME)
{
PrintFormat("The '%s' symbol was found in the list of server symbols at index %d", name, i
found = true;
break;
}
}

//--- if a symbol is not found on the server, report this before shutting down

© 2000-2025, MetaQuotes Ltd.


1830 Market Info

if(!found)
PrintFormat("The '%s' symbol was not found on the server.", SYMBOL_NAME);
}

© 2000-2025, MetaQuotes Ltd.


1831 Market Info

SymbolSelect
S elects a symbol in the Market W atch window or removes a symbol from the window.
bool SymbolSelect(
string name, // symbol name
bool select // add or remove
);

Parameters
name
[in] S ymbol name.

select
[in] S witch.If the value is false, a symbol should be removed from MarketW atch, 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.

Return Value

In case of failure returns false.


Example:

#define SYMBOL_NAME "GBPHKD"

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check for the presence of a symbol in the lists, if not found, report it and complete the wor
bool custom = false;
if(!SymbolExist(SYMBOL_NAME, custom))
{
PrintFormat("'%s' symbol not found in the lists", SYMBOL_NAME);
return;
}

//--- add a symbol to the Market Watch window


ResetLastError();
if(!SymbolSelect(SYMBOL_NAME, true))
{
Print("SymbolSelect() failed. Error ", GetLastError());
return;
}
//--- if a symbol is successfully added to the list, get its index in the Market Watch window and s
int index = SymbolIndex(SYMBOL_NAME);
PrintFormat("The '%s' symbol has been added to the MarketWatch list. Symbol index in the list: %

© 2000-2025, MetaQuotes Ltd.


1832 Market Info

//--- now remove the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(SYMBOL_NAME, false))
{
Print("SymbolSelect() failed. Error ", GetLastError());
return;
}
//--- if a symbol is successfully removed from the list, its index in the Market Watch window is -1
index = SymbolIndex(SYMBOL_NAME);
PrintFormat("The '%s' symbol has been removed from the MarketWatch list. Symbol index in the lis

/*
result:
The 'GBPHKD' symbol has been added to the MarketWatch list. Symbol index in the list: 12
The 'GBPHKD' symbol has been removed from the MarketWatch list. Symbol index in the list: -1
*/
}
//+------------------------------------------------------------------+
//| Return the symbol index in the Market Watch symbol list |
//+------------------------------------------------------------------+
int SymbolIndex(const string symbol)
{
int total = SymbolsTotal(true);
for(int i=0; i<total; i++)
{
string name = SymbolName(i, true);
if(name == symbol)
return i;
}
return(WRONG_VALUE);
}

© 2000-2025, MetaQuotes Ltd.


1833 Market Info

SymbolIsSynchronized
The function checks whether data of a selected symbol in the terminal are synchronized with data on
the trade server.
bool SymbolIsSynchronized(
string name, // symbol name
);

Parameters
name
[in] S ymbol name.

Return value

If data are synchronized, returns 'true'; otherwise returns 'false'.


Example:

#define SYMBOL_NAME "EURUSD"

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the flag for synchronizing data in the terminal using the 'SYMBOL_NAME' symbol with the s
bool sync = SymbolIsSynchronized(SYMBOL_NAME);

//--- create a message depending on the synchronization flag


string text = StringFormat("The data on the '%s' symbol in the terminal is synchronized with the
if(!sync)
text = StringFormat("The data for the '%s' symbol in the terminal is not synchronized with th

//--- send the obtained result to the journal


Print(text);

/*
result for synchronized data:
The data on the 'EURUSD' symbol in the terminal is synchronized with the data on the trading ser

result for data not yet synchronized:


The data for the 'GBPHKD' symbol in the terminal is not synchronized with the data on the tradin
*/
}

See also

S ymbolInfoInteger, Organizing Data Access

© 2000-2025, MetaQuotes Ltd.


1834 Market Info

SymbolInfoDouble
R eturns 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
ENUM_SYMBOL_INFO_DOUBLE prop_id // identifier of the property
);

2. R eturns
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
ENUM_SYMBOL_INFO_DOUBLE prop_id, // identifier of the property
double& double_var // here we accept the property value
);

Parameters
name
[in] S ymbol name.

prop_id
[in] Identifier of a symbol property. The value can be one of the values of the
ENUM _SYM BOL _INFO_DOUBL E enumeration.

double_var
[out] Variable of double type receiving the value of the requested property.

Return Value

The value of double type. In case of execution failure, information about the error can be obtained
using GetLastError() function:
· 5040 – invalid string parameter for specifying a symbol name,
· 4301 – unk nown symbol (financial instrument),
· 4302 – symbol is not selected in " Mark et W atch" (not found in the list of available ones),
· 4303 – invalid identifier of a symbol property.

Note

It is recommended to use S ymbolInfoTick() if the function is used for getting information about the
last tick. It may well be that not a single quote has appeared yet since the terminal is connected to a
trading account. In such a case, the requested value will be indefinite.
In most cases, it is enough to use S ymbolInfoTick() function allowing a user to receive the values of
As k , Bid, Last, Volume and the time of the last tick's arrival during a single call.

The S ymbolInfoMarginRate() function provides data on the amount of charged margin depending on
the order type and direction.

© 2000-2025, MetaQuotes Ltd.


1835 Market Info

Example:

void OnTick()
{
//--- obtain spread from the symbol properties
bool spreadfloat=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT);
string comm=StringFormat("Spread %s = %I64d points\r\n",
spreadfloat?"floating":"fixed",
SymbolInfoInteger(Symbol(),SYMBOL_SPREAD));
//--- now let's calculate the spread by ourselves
double ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
double bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
double spread=ask-bid;
int spread_points=(int)MathRound(spread/SymbolInfoDouble(Symbol(),SYMBOL_POINT));
comm=comm+"Calculated spread = "+(string)spread_points+" points";
Comment(comm);
}

© 2000-2025, MetaQuotes Ltd.


1836 Market Info

SymbolInfoInteger
R eturns 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
ENUM_SYMBOL_INFO_INTEGER prop_id // identifier of a property

);

2. R eturns
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
ENUM_SYMBOL_INFO_INTEGER prop_id, // identifier of a property
long& long_var // here we accept the property value
);

Parameters
name
[in] S ymbol name.

prop_id
[in] Identifier of a symbol property. The value can be one of the values of the
ENUM _SYM BOL _INFO_INT EGER enumeration.

long_var
[out] Variable of the long type receiving the value of the requested property.

Return Value

The value of long type. In case of execution failure, information about the error can be obtained
using GetLastError() function:
· 5040 – invalid string parameter for specifying a symbol name,
· 4301 – unk nown symbol (financial instrument),
· 4302 – symbol is not selected in " Mark et W atch" (not found in the list of available ones),
· 4303 – invalid identifier of a symbol property.

Note

It is recommended to use S ymbolInfoTick() if the function is used for getting information about the
last tick. It may well be that not a single quote has appeared yet since the terminal is connected to a
trading account. In such a case, the requested value will be indefinite.
In most cases, it is enough to use S ymbolInfoTick() function allowing a user to receive the values of
As k , Bid, Last, Volume and the time of the last tick's arrival during a single call.

Example:

© 2000-2025, MetaQuotes Ltd.


1837 Market Info

void OnTick()
{
//--- obtain spread from the symbol properties
bool spreadfloat=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT);
string comm=StringFormat("Spread %s = %I64d points\r\n",
spreadfloat?"floating":"fixed",
SymbolInfoInteger(Symbol(),SYMBOL_SPREAD));
//--- now let's calculate the spread by ourselves
double ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
double bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
double spread=ask-bid;
int spread_points=(int)MathRound(spread/SymbolInfoDouble(Symbol(),SYMBOL_POINT));
comm=comm+"Calculated spread = "+(string)spread_points+" points";
Comment(comm);
}

© 2000-2025, MetaQuotes Ltd.


1838 Market Info

SymbolInfoString
R eturns 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
ENUM_SYMBOL_INFO_STRING prop_id // Property identifier
);

2. R eturns true or false, depending on the success of a function. If successful, the value of the
property is placed in a placeholder variable passed by reference in the last parameter.
bool SymbolInfoString(
string name, // Symbol
ENUM_SYMBOL_INFO_STRING prop_id, // Property identifier
string& string_var // here we accept the property value
);

Parameters
name
[in] S ymbol name.

prop_id
[in] Identifier of a symbol property. The value can be one of the values of the
ENUM _SYM BOL _INFO_S T R ING enumeration.

string_var
[out] Variable of the string type receiving the value of the requested property.

Return Value

The value of string type. In case of execution failure, information about the error can be obtained
using GetLastError() function:
· 5040 – invalid string parameter for specifying a symbol name,
· 4301 – unk nown symbol (financial instrument),
· 4302 – symbol is not selected in " Mark et W atch" (not found in the list of available ones),
· 4303 – invalid identifier of a symbol property.

Note

It is recommended to use S ymbolInfoTick() if the function is used for getting information about the
last tick. It may well be that not a single quote has appeared yet since the terminal is connected to a
trading account. In such a case, the requested value will be indefinite.
In most cases, it is enough to use S ymbolInfoTick() function allowing a user to receive the values of
As k , Bid, Last, Volume and the time of the last tick's arrival during a single call.

Example:

#define SYMBOL_NAME "USDJPY"

© 2000-2025, MetaQuotes Ltd.


1839 Market Info

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get string data for SYMBOL_NAME symbol
string currency_base = SymbolInfoString(SYMBOL_NAME, SYMBOL_CURRENCY_BASE); // Base currenc
string currency_profit = SymbolInfoString(SYMBOL_NAME, SYMBOL_CURRENCY_PROFIT); // Profit curre
string currency_margin = SymbolInfoString(SYMBOL_NAME, SYMBOL_CURRENCY_MARGIN); // Margin curre
string symbol_descript = SymbolInfoString(SYMBOL_NAME, SYMBOL_DESCRIPTION); // String descr

//--- create a message text with the obtained data


string text=StringFormat("Symbol %s:\n"+
"- Currency Base: %s\n"+
"- Currensy Profit: %s\n"+
"- Currency Margin: %s\n"+
"- Symbol Description: %s",
SYMBOL_NAME, currency_base,
currency_profit, currency_margin,
symbol_descript);

//--- send the obtained data to the journal


Print(text);
/*
Symbol USDJPY:
- Currency Base: USD
- Currensy Profit: JPY
- Currency Margin: USD
- Symbol Description: US Dollar vs Yen
*/
}

© 2000-2025, MetaQuotes Ltd.


1840 Market Info

SymbolInfoMarginRate
R eturns the margin rates depending on the order type and direction.
bool SymbolInfoMarginRate(
string name, // symbol name
ENUM_ORDER_TYPE order_type, // order type
double& initial_margin_rate, // initial margin rate
double& maintenance_margin_rate // maintenance margin rate
);

Parameters
name
[in] S ymbol name.

order_type
[in] Order type.
initial_margin_rate
[in] A double type variable for receiving an initial margin rate. Initial margin is a security deposit
for 1 lot deal in the appropriate direction. Multiplying the rate by the initial margin, we receive the
amount of funds to be reserved on the account when placing an order of the specified type.
maintenance_margin_rate
[out] A double type variable for receiving a maintenance margin rate. Maintenance margin is a
minimum amount for maintaining an open position of 1 lot in the appropriate direction. Multiplying
the rate by the maintenance margin, we receive the amount of funds to be reserved on the
account after an order of the specified type is activated.

Return Value

R eturns true if request for properties is successful, otherwise false.


Example:

#define SYMBOL_NAME Symbol()

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare the variables the ratios are set into
double initial_margin_rate = 0; // initial margin rate
double maintenance_margin_rate = 0; // maintenance margin rate

//--- get and send the SYMBOL_NAME symbol ratios for the Buy market order to the journal
SymbolInfoMarginRatePrint(SYMBOL_NAME, ORDER_TYPE_BUY, initial_margin_rate, maintenance_margin_r

//--- get and send the SYMBOL_NAME symbol ratios for the Sell market order to the journal
SymbolInfoMarginRatePrint(SYMBOL_NAME, ORDER_TYPE_SELL, initial_margin_rate, maintenance_margin_

© 2000-2025, MetaQuotes Ltd.


1841 Market Info

/*
result:
Initial margin rate for symbol AFKS for the Buy market order: 0.225600
Maintenance margin rate for symbol AFKS for the Buy market order: 0.112800
Initial margin rate for symbol AFKS for the Sell market order: 0.254400
Maintenance margin rate for symbol AFKS for the Sell market order: 0.127200
*/
}
//+------------------------------------------------------------------+
//| Send the margin ratios to the journal |
//+------------------------------------------------------------------+
void SymbolInfoMarginRatePrint(const string symbol, const ENUM_ORDER_TYPE order_type, double &initi
{
//--- get the 'symbol' ratios for the order_type market order
ResetLastError();
if(!SymbolInfoMarginRate(symbol, order_type, initial_margin_rate, maintenance_margin_rate))
{
Print("SymbolInfoMarginRate() failed. Error ", GetLastError());
return;
}
//--- print the obtained ratio values
string type=(order_type==ORDER_TYPE_BUY ? "Buy" : order_type==ORDER_TYPE_SELL ? "Sell" : "Unknow
PrintFormat("Initial margin rate for symbol %s for the %s market order: %f\n"+
"Maintenance margin rate for symbol %s for the %s market order: %f",
SYMBOL_NAME, type, initial_margin_rate,
SYMBOL_NAME, type, maintenance_margin_rate);
}

© 2000-2025, MetaQuotes Ltd.


1842 Market Info

SymbolInfoTick
The function returns current prices of a specified symbol in a variable of the M qlTick type.
bool SymbolInfoTick(
string symbol, // symbol name
MqlTick& tick // reference to a structure
);

Parameters
symbol
[in] S ymbol name.

tick
[out] Link to the structure of the M qlTick type, to which the current prices and time of the last
price update will be placed.

Return Value

The function returns true if successful, otherwise returns false.


Example:

#define SYMBOL_NAME "EURUSD"

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare an array with the MqlTick structure type of dimension 1
MqlTick tick[1]={};

//--- get the latest prices for the SYMBOL_NAME symbol into the MqlTick structure
if(!SymbolInfoTick(SYMBOL_NAME, tick[0]))
{
Print("SymbolInfoTick() failed. Error ", GetLastError());
return;
}

//--- send the obtained data to the journal


PrintFormat("Latest price data for the '%s' symbol:", SYMBOL_NAME);
ArrayPrint(tick);
/*
result:
Latest price data for the 'EURUSD' symbol:
[time] [bid] [ask] [last] [volume] [time_msc] [flags] [volume_real]
[0] 2024.05.17 23:58:54 1.08685 1.08695 0.0000 0 1715990334319 6 0.00000
*/
}

© 2000-2025, MetaQuotes Ltd.


1843 Market Info

SymbolInfoSessionQuote
Allowsreceiving time of beginning and end of the specified quoting sessions for a specified symbol
and day of week.
bool SymbolInfoSessionQuote(
string name, // symbol name
ENUM_DAY_OF_WEEK day_of_week, // day of the week
uint session_index, // session index
datetime& from, // time of the session beginning
datetime& to // time of the session end
);

Parameters
name
[in] S ymbol name.

ENUM_DAY_OF_WEEK
[in] Day of the week, value of enumeration ENUM _DAY_OF_WEEK.
uint
[in] Ordinal number of a session, whose beginning and end time we want to receive. Indexing of
sessions starts with 0.
from
[out] S ession beginning time in seconds from 00 hours 00 minutes, in the returned value date
should be ignored.
to
[out] S ession end time in seconds from 00 hours 00 minutes, in the returned value date should be
ignored.

Return Value

If data for the specified session, symbol and day of the week are received, returns true, otherwise
returns false.
Example:

#define SYMBOL_NAME Symbol()


#define SESSION_INDEX 0

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the header with a symbol and SESSION_INDEX and
//--- in a loop by day of the week from Mon to Fri, print the start and end times of the quote sess
PrintFormat("Symbol %s, Quote session %d:", SYMBOL_NAME, SESSION_INDEX);
for(int i=MONDAY; i<SATURDAY; i++)

© 2000-2025, MetaQuotes Ltd.


1844 Market Info

SymbolInfoSessionQuotePrint(SYMBOL_NAME, (ENUM_DAY_OF_WEEK)i, SESSION_INDEX);


/*
result:
Symbol RU000A103661, Quote session 0:
- Monday 06:45 - 00:00
- Tuesday 06:45 - 00:00
- Wednesday 06:45 - 00:00
- Thursday 06:45 - 00:00
- Friday 06:45 - 00:00
*/
}
//+------------------------------------------------------------------+
//| Send the start and end times of the specified quote session |
//| for the specified symbol and day of the week to the journal |
//+------------------------------------------------------------------+
void SymbolInfoSessionQuotePrint(const string symbol, const ENUM_DAY_OF_WEEK day_of_week, const uin
{
//--- declare variables to record the beginning and end of the quote session
datetime date_from; // session start time
datetime date_to; // session end time

//--- get data from the quotation session by symbol and day of the week
if(!SymbolInfoSessionQuote(symbol, day_of_week, session_index, date_from, date_to))
{
Print("SymbolInfoSessionQuote() failed. Error ", GetLastError());
return;
}

//--- create the week day name from the enumeration constant
string week_day=EnumToString(day_of_week);
if(week_day.Lower())
week_day.SetChar(0, ushort(week_day.GetChar(0)-32));

//--- send data for the specified quote session to the journal
PrintFormat("- %-10s %s - %s", week_day, TimeToString(date_from, TIME_MINUTES), TimeToString(dat
}

See also

S ymbol Properties, TimeToS truct, Data S tructures

© 2000-2025, MetaQuotes Ltd.


1845 Market Info

SymbolInfoSessionTrade
Allows receiving time of beginning and end of the specified trading sessions for a specified symbol and
day of week.
bool SymbolInfoSessionTrade(
string name, // symbol name
ENUM_DAY_OF_WEEK day_of_week, // day of the week
uint session_index, // session index
datetime& from, // session beginning time
datetime& to // session end time
);

Parameters
name
[in] S ymbol name.

ENUM_DAY_OF_WEEK
[in] Day of the week, value of enumeration ENUM _DAY_OF_WEEK.
uint
[in] Ordinal number of a session, whose beginning and end time we want to receive. Indexing of
sessions starts with 0.
from
[out] S ession beginning time in seconds from 00 hours 00 minutes, in the returned value date
should be ignored.
to
[out] S ession end time in seconds from 00 hours 00 minutes, in the returned value date should be
ignored.

Return value

If data for the specified session, symbol and day of the week are received, returns true, otherwise
returns false.
Example:

#define SYMBOL_NAME Symbol()


#define SESSION_INDEX 0

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the header with a symbol and SESSION_INDEX and
//--- in a loop by day of the week from Mon to Fri, print the start and end times of the trading se
PrintFormat("Symbol %s, Trade session %d:", SYMBOL_NAME, SESSION_INDEX);
for(int i=MONDAY; i<SATURDAY; i++)

© 2000-2025, MetaQuotes Ltd.


1846 Market Info

SymbolInfoSessionTradePrint(SYMBOL_NAME, (ENUM_DAY_OF_WEEK)i, SESSION_INDEX);


/*
result:
Symbol GBPUSD, Trade session 0:
- Monday 00:15 - 23:55
- Tuesday 00:15 - 23:55
- Wednesday 00:15 - 23:55
- Thursday 00:15 - 23:55
- Friday 00:15 - 23:55
*/
}
//+------------------------------------------------------------------+
//| Send the start and end times of the specified trade session |
//| for the specified symbol and day of the week to the journal |
//+------------------------------------------------------------------+
void SymbolInfoSessionTradePrint(const string symbol, const ENUM_DAY_OF_WEEK day_of_week, const uin
{
//--- declare variables to record the beginning and end of the trading session
datetime date_from; // session start time
datetime date_to; // session end time

//--- get data from the trading session by symbol and day of the week
if(!SymbolInfoSessionTrade(symbol, day_of_week, session_index, date_from, date_to))
{
Print("SymbolInfoSessionTrade() failed. Error ", GetLastError());
return;
}

//--- create the week day name from the enumeration constant
string week_day=EnumToString(day_of_week);
if(week_day.Lower())
week_day.SetChar(0, ushort(week_day.GetChar(0)-32));

//--- send data for the specified trading session to the journal
PrintFormat("- %-10s %s - %s", week_day, TimeToString(date_from, TIME_MINUTES), TimeToString(dat
}

See also

S ymbol Properties, TimeToS truct, Data S tructures

© 2000-2025, MetaQuotes Ltd.


1847 Market Info

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.

Return 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).
Example:

#define SYMBOL_NAME "GBPUSD"

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- open the market depth for SYMBOL_NAME symbol
if(!MarketBookAdd(SYMBOL_NAME))
{
PrintFormat("MarketBookAdd(%s) failed. Error ", SYMBOL_NAME, GetLastError());
return;
}

//--- send the message about successfully opening the market depth to the journal
PrintFormat("The MarketBook for the '%s' symbol was successfully opened and a subscription to ch

//--- wait 2 seconds


Sleep(2000);

//--- upon completion, unsubscribe from the open market depth


ResetLastError();
if(MarketBookRelease(SYMBOL_NAME))
PrintFormat("MarketBook for the '%s' symbol was successfully closed", SYMBOL_NAME);
else
PrintFormat("Error %d occurred when closing MarketBook using the '%s' symbol", GetLastError()

© 2000-2025, MetaQuotes Ltd.


1848 Market Info

/*
result:
The MarketBook for the 'GBPUSD' symbol was successfully opened and a subscription to change it w
MarketBook for the 'GBPUSD' symbol was successfully closed
*/
}

See also

S tructure of Depth of Market, S tructures and Classes

© 2000-2025, MetaQuotes Ltd.


1849 Market Info

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] S ymbol name.

Return 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.
Example:

#define SYMBOL_NAME "GBPUSD"

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- open the market depth for SYMBOL_NAME symbol
if(!MarketBookAdd(SYMBOL_NAME))
{
PrintFormat("MarketBookAdd(%s) failed. Error ", SYMBOL_NAME, GetLastError());
return;
}

//--- send the message about successfully opening the market depth to the journal
PrintFormat("The MarketBook for the '%s' symbol was successfully opened and a subscription to ch

//--- wait 2 seconds


Sleep(2000);

//--- upon completion, unsubscribe from the open market depth


//--- send the message about successfully unsubscribing from the market depth or about the error to
ResetLastError();
if(MarketBookRelease(SYMBOL_NAME))
PrintFormat("MarketBook for the '%s' symbol was successfully closed", SYMBOL_NAME);

© 2000-2025, MetaQuotes Ltd.


1850 Market Info

else
PrintFormat("Error %d occurred when closing MarketBook using the '%s' symbol", GetLastError()

/*
result:
The MarketBook for the 'GBPUSD' symbol was successfully opened and a subscription to change it w
MarketBook for the 'GBPUSD' symbol was successfully closed
*/
}

See also

S tructure of Depth of Market, S tructures and Classes

© 2000-2025, MetaQuotes Ltd.


1851 Market Info

MarketBookGet
R eturns a structure array M qlBookInfo 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] S ymbol name.

book[]
[in] R eferenceto 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.

Return Value

R eturns 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 for ",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
S tructure of Depth of Market, S tructures and Classes

© 2000-2025, MetaQuotes Ltd.


1852 Economic Calendar

Economic calendar functions


This section describes the functions for working with the economic calendar available directly in the
MetaTrader platform. The economic calendar is a ready-made encyclopedia featuring descriptions of
macroeconomic indicators, their release dates and degrees of importance. Relevant values of
macroeconomic indicators are sent to the MetaTrader platform right at the moment of publication and
are displayed on a chart as tags allowing you to visually track the required indicators by countries,
currencies and importance.
Allfunctions for working with the economic calendar use the trade server time (TimeTradeS erver).
This means that the time in the M qlCalendarValue structure and the time inputs in the
CalendarValueHistoryByEvent/CalendarValueHistory functions are set in a trade server timezone,
rather than a user's local time.
Economic calendar functions allow conducting the auto analysis of incoming events according to
custom importance criteria from a perspective of necessary countries /currencies.

Function Action

CalendarCountryById Get a country description by its ID


CalendarEventById Get an event description by its ID

CalendarValueById Get an event value description by its ID

CalendarCountries Get the array of country names available in the calendar


CalendarEventByCountry Get the array of descriptions of all events available in the calendar
by a specified country code
CalendarEventByCurrency Get the array of descriptions of all events available in the calendar
by a specified currency
CalendarValueHistoryByEvent Get the array of values for all events in a specified time range by
an event ID
CalendarValueHistory Get the array of values for all events in a specified time range
with the ability to sort by country and/or currency
CalendarValueLastByEvent Get the array of event values by its ID since the calendar database
status with a specified change_id
CalendarValueLast Get the array of values for all events with the ability to sort by
country and/or currency since the calendar database status with a
specified change_id

© 2000-2025, MetaQuotes Ltd.


1853 Economic Calendar

CalendarCountryById
Get a country description by its ID.
bool CalendarCountryById(
const long country_id, // country ID
MqlCalendarCountry& country // variable for receiving a country description
);

Parameters
country_id
[in] Country ID (IS O 3166-1).
country
[out] M qlCalendarCountry type variable for receiving a country description.

Return Value

R eturns true if successful, otherwise - false. To get information about an error, call the
GetLastError() function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR(general runtime error),
· 5402 – ERR_CALENDAR_NO_DATA (country is not found),
· 5401 – ERR_CALENDAR_TIM EOUT (request time limit exceeded).
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the list of countries from the economic calendar
MqlCalendarCountry countries[];
int count=CalendarCountries(countries);
//--- check the result
if(count==0)
PrintFormat("CalendarCountries() returned 0! Error %d",GetLastError());
//--- if there are two or more countries
if(count>=2)
{
MqlCalendarCountry country;
//--- now get a country description by its ID
if(CalendarCountryById(countries[1].id, country))
{
//--- prepare a country description
string descr="id = "+IntegerToString(country.id)+"\n";
descr+=("name = " + country.name+"\n");
descr+=("code = " + country.code+"\n");
descr+=("currency = " + country.currency+"\n");
descr+=("currency_symbol = " + country.currency_symbol+"\n");

© 2000-2025, MetaQuotes Ltd.


1854 Economic Calendar

descr+=("url_name = " + country.url_name);


//--- display a country description
Print(descr);
}
else
Print("CalendarCountryById() failed. Error ",GetLastError());
}
//---
}
/*
Result:
id = 999
name = European Union
code = EU
currency = EUR
currency_symbol = €
url_name = european-union
*/

See also
CalendarCountries, CalendarEventByCountry

© 2000-2025, MetaQuotes Ltd.


1855 Economic Calendar

CalendarEventById
Get an event description by its ID.

bool CalendarEventById(
ulong event_id, // event ID
MqlCalendarEvent& event // variable for receiving an event description
);

Parameters
event_id
[in] Event ID.

event
[out] M qlCalendarEvent type variable for receiving an event description.

Return Value

R eturns true if successful, otherwise - false. To get information about an error, call the
GetLastError() function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR(general runtime error),
· 5402 – ERR_CALENDAR_NO_DATA (country is not found),
· 5401 – ERR_CALENDAR_TIM EOUT (request time limit exceeded).
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- country code for Germany (ISO 3166-1 Alpha-2)
string germany_code="DE";
//--- get Germany events
MqlCalendarEvent events[];
int events_count=CalendarEventByCountry(germany_code,events);
//--- display Germany events in the Journal
if(events_count>0)
{
PrintFormat("Germany events: %d",events_count);
ArrayPrint(events);
}
else
{
PrintFormat("Failed to receive events for the country code %s, error %d",
germany_code,GetLastError());
//--- script early completion
return;
}
//--- get description of the last event from the events[] array

© 2000-2025, MetaQuotes Ltd.


1856 Economic Calendar

MqlCalendarEvent event;
ulong event_id=events[events_count-1].id;
if(CalendarEventById(event_id,event))
{
MqlCalendarCountry country;
CalendarCountryById(event.country_id,country);
PrintFormat("Event description with event_id=%d received",event_id);
PrintFormat("Country: %s (country code = %d)",country.name,event.country_id);
PrintFormat("Event name: %s",event.name);
PrintFormat("Event code: %s",event.event_code);
PrintFormat("Event importance: %s",EnumToString((ENUM_CALENDAR_EVENT_IMPORTANCE)event.importa
PrintFormat("Event type: %s",EnumToString((ENUM_CALENDAR_EVENT_TYPE)event.type));
PrintFormat("Event sector: %s",EnumToString((ENUM_CALENDAR_EVENT_SECTOR)event.sector));
PrintFormat("Event frequency: %s",EnumToString((ENUM_CALENDAR_EVENT_FREQUENCY)event.frequency
PrintFormat("Event release mode: %s",EnumToString((ENUM_CALENDAR_EVENT_TIMEMODE)event.time_mo
PrintFormat("Event measurement unit: %s",EnumToString((ENUM_CALENDAR_EVENT_UNIT)event.unit));
PrintFormat("Number of decimal places: %d",event.digits);
PrintFormat("Event multiplier: %s",EnumToString((ENUM_CALENDAR_EVENT_MULTIPLIER)event.multipl
PrintFormat("Source URL: %s",event.source_url);
}
else
PrintFormat("Failed to get event description for event_d=%s, error %d",
event_id,GetLastError());
}
/*
Result:
Germany events: 50
[id] [type] [sector] [frequency] [time_mode] [country_id] [unit] [importance] [multipl
[ 0] 276010001 1 6 2 0 276 1 1
[ 1] 276010002 1 6 2 0 276 1 1
[ 2] 276010003 1 4 2 0 276 1 1
[ 3] 276010004 1 4 2 0 276 1 1
....
[47] 276500001 1 8 2 0 276 0 2
[48] 276500002 1 8 2 0 276 0 2
[49] 276500003 1 8 2 0 276 0 2
Event description with event_id=276500003 received
Country: Germany (country code = 276)
Event name: Markit Composite PMI
Event code: markit-composite-pmi
Event importance: CALENDAR_IMPORTANCE_MODERATE
Event type: CALENDAR_TYPE_INDICATOR
Event sector: CALENDAR_SECTOR_BUSINESS
Event frequency: CALENDAR_FREQUENCY_MONTH
Event release mode: CALENDAR_TIMEMODE_DATETIME
Event measurement unit: CALENDAR_UNIT_NONE
Number of decimal places: 1
Value multiplier: CALENDAR_MULTIPLIER_NONE
Source URL: https://www.markiteconomics.com

© 2000-2025, MetaQuotes Ltd.


1857 Economic Calendar

*/

See also
CalendarEventByCountry, CalendarEventByCurrency, CalendarValueById

© 2000-2025, MetaQuotes Ltd.


1858 Economic Calendar

CalendarValueById
Get an event value description by its ID.

bool CalendarValueById(
ulong value_id, // event value ID
MqlCalendarValue& value // variable for receiving an event value
);

Parameters
value_id
[in] Event value ID.

value
[out] M qlCalendarValue type variable for receiving an event description. S ee the example of
handling calendar events.

Return Value

R eturns true if successful, otherwise - false. To get information about an error, call the
GetLastError() function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR(general runtime error),
· 5402 – ERR_CALENDAR_NO_DATA (country is not found),
· 5401 – ERR_CALENDAR_TIM EOUT (request time limit exceeded).
Note

All functionsfor working with the economic calendar use the trade server time (TimeTradeS erver).
This means that the time in the M qlCalendarValue structure and the time inputs in the
CalendarValueHistoryByEvent/CalendarValueHistory functions are set in a trade server timezone,
rather than a user's local time.
The M qlCalendarValue structure provides methods for checking and setting values from the
actual_value, forecast_value, prev _value and revised_prev _value fields. If no value is specified, the
field stores LONG_MIN (-9223372036854775808).
Please note that the values stored in these field are multiplied by one million. It means that when
you receive values in M qlCalendarValue using functions CalendarValueById,
CalendarValueHistoryByEvent, CalendarValueHistory, CalendarValueLastByEvent and
CalendarValueLast, you should check if the field values are equal to LONG_MIN; if a value is
specified in a field, then you should divide the value by 1,000,000 in order to get the value. Another
method to get the values is to check and to get values using the functions of the M qlCalendarValue
structure.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- country code for Japan (ISO 3166-1 Alpha-2)

© 2000-2025, MetaQuotes Ltd.


1859 Economic Calendar

string japan_code="JP";
//--- set the boundaries of the interval we take the events from
datetime date_from=D'01.01.2018'; // take all events from 2018
datetime date_to=0; // 0 means all known events, including the ones that have not
//--- get the array of the Japan event values
MqlCalendarValue values[];
int values_count=CalendarValueHistory(values,date_from,date_to,japan_code);
//--- move along the detected event values
if(values_count>0)
{
PrintFormat("Number of values for Japan events: %d",values_count);
//--- delete all "empty" values (actual_value==-9223372036854775808)
for(int i=values_count-1;i>=0;i--)
{
if(values[i].actual_value==-9223372036854775808)
ArrayRemove(values,i,1);
}
PrintFormat("Number of values after deleting empty ones: %d",ArraySize(values));
}
else
{
PrintFormat("Failed to receive events for the country code %s, error %d",
japan_code,GetLastError());
//--- script early completion
return;
}
//--- leave no more than 10 values in the values[] array
if(ArraySize(values)>10)
{
PrintFormat("Reduce the list of values to 10 and display them");
ArrayRemove(values,0,ArraySize(values)-10);
}
ArrayPrint(values);

//--- now let's display how to get an event value description based on the known value_id
for(int i=0;i<ArraySize(values);i++)
{
MqlCalendarValue value;
CalendarValueById(values[i].id,value);
PrintFormat("%d: value_id=%d value=%d impact=%s",
i,values[i].id,value.actual_value,EnumToString(ENUM_CALENDAR_EVENT_IMPACT(value.i
}
//---
}
/*
Result:
Number of values for Japan events: 1734
Number of values after deleting empty ones: 1017
Reduce the list of values to 10 and display them

© 2000-2025, MetaQuotes Ltd.


1860 Economic Calendar

[id] [event_id] [time] [period] [revision] [actual_value] [prev_val


[0] 56500 392030004 2019.03.28 23:30:00 2019.03.01 00:00:00 0 900000 600
[1] 56501 392030005 2019.03.28 23:30:00 2019.03.01 00:00:00 0 700000 700
[2] 56502 392030006 2019.03.28 23:30:00 2019.03.01 00:00:00 0 1100000 1100
[3] 56544 392030007 2019.03.28 23:30:00 2019.02.01 00:00:00 0 2300000 2500
[4] 56556 392050002 2019.03.28 23:30:00 2019.02.01 00:00:00 0 1630000 1630
[5] 55887 392020003 2019.03.28 23:50:00 2019.02.01 00:00:00 0 400000 600
[6] 55888 392020004 2019.03.28 23:50:00 2019.02.01 00:00:00 0 -1800000 -3300
[7] 55889 392020002 2019.03.28 23:50:00 2019.02.01 00:00:00 0 200000 -2300
[8] 55948 392020006 2019.03.28 23:50:00 2019.02.01 00:00:00 1 1400000 -3400
[9] 55949 392020007 2019.03.28 23:50:00 2019.02.01 00:00:00 1 -1000000 300
Display brief data on event values based on value_id
0: value_id=56500 value=900000 impact=CALENDAR_IMPACT_POSITIVE
1: value_id=56501 value=700000 impact=CALENDAR_IMPACT_NA
2: value_id=56502 value=1100000 impact=CALENDAR_IMPACT_POSITIVE
3: value_id=56544 value=2300000 impact=CALENDAR_IMPACT_NEGATIVE
4: value_id=56556 value=1630000 impact=CALENDAR_IMPACT_POSITIVE
5: value_id=55887 value=400000 impact=CALENDAR_IMPACT_NEGATIVE
6: value_id=55888 value=-1800000 impact=CALENDAR_IMPACT_POSITIVE
7: value_id=55889 value=200000 impact=CALENDAR_IMPACT_NEGATIVE
8: value_id=55948 value=1400000 impact=CALENDAR_IMPACT_POSITIVE
9: value_id=55949 value=-1000000 impact=CALENDAR_IMPACT_NEGATIVE
*/

See also
CalendarValueHistoryByEvent, CalendarValueHistory, CalendarValueLastByEvent, CalendarValueLast

© 2000-2025, MetaQuotes Ltd.


1861 Economic Calendar

CalendarCountries
Get the array of country names available in the Calendar.
int CalendarCountries(
MqlCalendarCountry& countries[] // array for receiving a list of Calendar countries' de
);

Parameters
countries[]
[out] An array of M qlCalendarCountry type for receiving all Calendar countries ' descriptions.

Return Value

Number of received descriptions. To get information about an error, call the GetLastError()
function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR (general runtime error),
· 5401 – ERR_CAL ENDAR_TIM EOUT (request time limit exceeded),
· 5400 – ERR_CAL ENDAR_MORE_DAT A (array size is insufficient for receiving descriptions of all
countries, only the ones that managed to fit in were received).

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the list of countries from the economic calendar
MqlCalendarCountry countries[];
int count=CalendarCountries(countries);
//--- display the array in the Journal
if(count>0)
ArrayPrint(countries);
else
PrintFormat("CalendarCountries() returned 0! Error %d",GetLastError());
/*
Result:
[id] [name] [code] [currency] [currency_symbol] [url_name] [reserved]
[ 0] 0 "Worldwide" "WW" "ALL" "" "worldwide" 0
[ 1] 999 "European Union" "EU" "EUR" "€" "european-union" 0
[ 2] 840 "United States" "US" "USD" "$" "united-states" 0
[ 3] 124 "Canada" "CA" "CAD" "$" "canada" 0
[ 4] 36 "Australia" "AU" "AUD" "$" "australia" 0
[ 5] 554 "New Zealand" "NZ" "NZD" "$" "new-zealand" 0
[ 6] 392 "Japan" "JP" "JPY" "Ґ" "japan" 0
[ 7] 156 "China" "CN" "CNY" "Ґ" "china" 0
[ 8] 826 "United Kingdom" "GB" "GBP" "Ј" "united-kingdom" 0
[ 9] 756 "Switzerland" "CH" "CHF" "₣" "switzerland" 0

© 2000-2025, MetaQuotes Ltd.


1862 Economic Calendar

[10] 276 "Germany" "DE" "EUR" "€" "germany" 0


[11] 250 "France" "FR" "EUR" "€" "france" 0
[12] 380 "Italy" "IT" "EUR" "€" "italy" 0
[13] 724 "Spain" "ES" "EUR" "€" "spain" 0
[14] 76 "Brazil" "BR" "BRL" "R$" "brazil" 0
[15] 410 "South Korea" "KR" "KRW" "₩" "south-korea" 0
*/
}

See also
CalendarEventByCountry, CalendarCountryById

© 2000-2025, MetaQuotes Ltd.


1863 Economic Calendar

CalendarEventByCountry
Get the array of descriptions of all events available in the Calendar by a specified country code.
int CalendarEventByCountry(
string country_code, // country code name (ISO 3166-1 alpha-2)
MqlCalendarEvent& events[] // variable for receiving the description array
);

Parameters
country_code
[in] Country code name (IS O 3166-1 alpha-2)
events[]
[out] M qlCalendarEvent type array for receiving descriptions of all events for a specified country.

Return Value

Number of received descriptions. To get information about an error, call the GetLastError()
function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR (general runtime error),
· 4004 – ERR_NOT _ENOUGH_M EMORY (not enough memory for executing a request),
· 5401 – ERR_CAL ENDAR_TIM EOUT (request time limit exceeded),
· errors of failed execution of ArrayR esize()

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- country code for EU (ISO 3166-1 Alpha-2)
string EU_code="EU";
//--- get EU events
MqlCalendarEvent events[];
int events_count=CalendarEventByCountry(EU_code,events);
//--- display EU events in the Journal
if(events_count>0)
{
PrintFormat("EU events: %d",events_count);
ArrayPrint(events);
}
//---
}
/*
Result:
EU events: 56
[id] [type] [country_id] [unit] [importance] [multiplier] [digits] [event_code]
[ 0] 999010001 0 999 0 2 0 0 "ECB Non-monetary

© 2000-2025, MetaQuotes Ltd.


1864 Economic Calendar

[ 1] 999010002 0 999 0 2 0 0 "ECB Monetary Poli


[ 2] 999010003 0 999 0 3 0 0 "ECB Monetary Poli
[ 3] 999010004 0 999 0 3 0 0 "ECB President Dra
[ 4] 999010005 0 999 0 2 0 0 "ECB Vice Presiden
[ 5] 999010006 1 999 1 3 0 2 "ECB Deposit Facil
[ 6] 999010007 1 999 1 3 0 2 "ECB Interest Rate
[ 7] 999010008 0 999 0 2 0 0 "ECB Economic Bull
[ 8] 999010009 1 999 2 2 3 3 "ECB Targeted LTRO
[ 9] 999010010 0 999 0 2 0 0 "ECB Executive Boa
[10] 999010011 0 999 0 2 0 0 "ECB Executive Boa
...

*/

See also
CalendarCountries, CalendarCountryById

© 2000-2025, MetaQuotes Ltd.


1865 Economic Calendar

CalendarEventByCurrency
Get the array of descriptions of all events available in the Calendar by a specified currency.
int CalendarEventByCurrency(
const string currency, // country currency code name
MqlCalendarEvent& events[] // variable for receiving the description array
);

Parameters
currency
[in] Country currency code name.
events[]
[out] M qlCalendarEvent type array for receiving descriptions of all events for a specified currency.

Return Value

Number of received descriptions. To get information about an error, call the GetLastError()
function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR (general runtime error),
· 4004 – ERR_NOT _ENOUGH_M EMORY (not enough memory for executing a request),
· 5401 – ERR_CAL ENDAR_TIM EOUT (request time limit exceeded),
· errors of failed execution of ArrayR esize()

Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare the array for receiving economic calendar events
MqlCalendarEvent events[];
//--- get EU currency events
int count = CalendarEventByCurrency("EUR",events);
Print("count = ", count);
//--- 10 events are sufficient for the current example
if(count>10)
ArrayResize(events,10);
//--- display events in the Journal
ArrayPrint(events);
}
/*
Result:
[id] [type] [country_id] [unit] [importance] [s
[0] 999010001 0 999 0 2 "https://www.ecb.europa.eu/home/html/index
[1] 999010002 0 999 0 2 "https://www.ecb.europa.eu/home/html/index
[2] 999010003 0 999 0 3 "https://www.ecb.europa.eu/home/html/index

© 2000-2025, MetaQuotes Ltd.


1866 Economic Calendar

[3] 999010004 0 999 0 3 "https://www.ecb.europa.eu/home/html/index


[4] 999010005 0 999 0 2 "https://www.ecb.europa.eu/home/html/index
[5] 999010006 1 999 1 3 "https://www.ecb.europa.eu/home/html/index
[6] 999010007 1 999 1 3 "https://www.ecb.europa.eu/home/html/index
[7] 999010008 0 999 0 2 "https://www.ecb.europa.eu/home/html/index
[8] 999010009 1 999 2 2 "https://www.ecb.europa.eu/home/html/index
[9] 999010010 0 999 0 2 "https://www.ecb.europa.eu/home/html/index
*/

See also
CalendarEventById, CalendarEventByCountry

© 2000-2025, MetaQuotes Ltd.


1867 Economic Calendar

CalendarValueHistoryByEvent
Get the array of values for all events in a specified time range by an event ID.
int CalendarValueHistoryByEvent(
ulong event_id, // event ID
MqlCalendarValue& values[], // array for value descriptions
datetime datetime_from, // left border of a time range
datetime datetime_to=0 // right border of a time range
);

Parameters
event_id
[in] Event ID.

values[]
[out] M qlCalendarValue type array for receiving event values. S ee the example of handling
calendar events.
datetime_from
[in] Initial date of a time range events are selected from by a specified ID, while datetime_from <
datetime_to.

datetime_to=0
[in] End date of a time range events are selected from by a specified ID. If the datetime_to is not
set (or is 0), all event values beginning from the specified datetime_from date in the Calendar
database are returned (including the values of future events).

Return Value

If successful, return the number of available values in the 'values ' array, otherwise -1. To get
information about an error, call the GetLastError() function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR (general runtime error),
· 4004 – ERR_NOT _ENOUGH_M EMORY (not enough memory for executing a request),
· 5401 – ERR_CAL ENDAR_TIM EOUT (request time limit exceeded),
· 5400 – ERR_CAL ENDAR_MORE_DAT A (array size is insufficient for receiving descriptions of all
values, only the ones that managed to fit in were received),
· errors of failed execution of ArrayR esize()

The M qlCalendarValue structure provides methods for checking and setting values from the
actual_value, forecast_value, prev _value and revised_prev _value fields. If no value is specified, the
field stores LONG_MIN (-9223372036854775808).
Please note that the values stored in these field are multiplied by one million. It means that when
you receive values in M qlCalendarValue using functions CalendarValueById,
CalendarValueHistoryByEvent, CalendarValueHistory, CalendarValueLastByEvent and
CalendarValueLast, you should check if the field values are equal to LONG_MIN; if a value is
specified in a field, then you should divide the value by 1,000,000 in order to get the value. Another
method to get the values is to check and to get values using the functions of the M qlCalendarValue
structure.
Note

© 2000-2025, MetaQuotes Ltd.


1868 Economic Calendar

All functionsfor working with the economic calendar use the trade server time (TimeTradeS erver).
This means that the time in the M qlCalendarValue structure and the time inputs in the
CalendarValueHistoryByEvent/CalendarValueHistory functions are set in a trade server timezone,
rather than a user's local time.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- country code for EU (ISO 3166-1 Alpha-2)
string EU_code="EU";
//--- get EU events
MqlCalendarEvent events[];
int events_count=CalendarEventByCountry(EU_code,events);
//--- display EU events in the Journal
if(events_count>0)
{
PrintFormat("EU events: %d",events_count);
//--- reduce the event list, 10 events are sufficient for analysis
ArrayResize(events,10);
ArrayPrint(events);
}
//--- see that the "ECB Interest Rate Decision" event has event_id=999010007
ulong event_id=events[6].id; // the event's ID may change in the Calendar, so be sure to
string event_name=events[6].name; // name of a Calendar event
PrintFormat("Get values for event_name=%s event_id=%d",event_name,event_id);
//--- get all values of the "ECB Interest Rate Decision" event
MqlCalendarValue values[];
//--- set the boundaries of the interval we take the events from
datetime date_from=0; // take all events from the beginning of the available history
datetime date_to=D'01.01.2016'; // take events not older than 2016
if(CalendarValueHistoryByEvent(event_id,values,date_from,date_to))
{
PrintFormat("Received values for %s: %d",
event_name,ArraySize(values));
//--- reduce the value list, 10 events are sufficient for analysis
ArrayResize(values,10);
ArrayPrint(values);
}
else
{
PrintFormat("Error! Failed to get values for event_id=%d",event_id);
PrintFormat("Error code: %d",GetLastError());
}
}
//---

© 2000-2025, MetaQuotes Ltd.


1869 Economic Calendar

/*
Result:
EU events: 56
[id] [type] [sector] [frequency] [time_mode] [country_id] [unit] [importance] [multipli
[0] 999010001 0 5 0 0 999 0 2
[1] 999010002 0 5 0 0 999 0 2
[2] 999010003 0 5 0 0 999 0 3
[3] 999010004 0 5 0 0 999 0 3
[4] 999010005 0 5 0 0 999 0 2
[5] 999010006 1 5 0 0 999 1 3
[6] 999010007 1 5 0 0 999 1 3
[7] 999010008 0 5 0 0 999 0 2
[8] 999010009 1 5 0 0 999 2 2
[9] 999010010 0 5 0 0 999 0 2
Get values for event_name=ECB Interest Rate Decision event_id=999010007
Received ECB Interest Rate Decision event values: 102
[id] [event_id] [time] [period] [revision] [actual_value] [prev_valu
[0] 2776 999010007 2007.03.08 11:45:00 1970.01.01 00:00:00 0 3750000 42500
[1] 2777 999010007 2007.05.10 11:45:00 1970.01.01 00:00:00 0 3750000 37500
[2] 2778 999010007 2007.06.06 11:45:00 1970.01.01 00:00:00 0 4000000 37500
[3] 2779 999010007 2007.07.05 11:45:00 1970.01.01 00:00:00 0 4000000 40000
[4] 2780 999010007 2007.08.02 11:45:00 1970.01.01 00:00:00 0 4000000 40000
[5] 2781 999010007 2007.09.06 11:45:00 1970.01.01 00:00:00 0 4000000 40000
[6] 2782 999010007 2007.10.04 11:45:00 1970.01.01 00:00:00 0 4000000 40000
[7] 2783 999010007 2007.11.08 12:45:00 1970.01.01 00:00:00 0 4000000 40000
[8] 2784 999010007 2007.12.06 12:45:00 1970.01.01 00:00:00 0 4000000 40000
[9] 2785 999010007 2008.01.10 12:45:00 1970.01.01 00:00:00 0 4000000 40000
*/

See also
CalendarCountries, CalendarEventByCountry, CalendarValueHistory, CalendarEventById,
CalendarValueById

© 2000-2025, MetaQuotes Ltd.


1870 Economic Calendar

CalendarValueHistory
Get the array of values for all events in a specified time range with the ability to sort by country
and/or currency.
int CalendarValueHistory(
MqlCalendarValue& values[], // array for value descriptions
datetime datetime_from, // left border of a time range
datetime datetime_to=0 // right border of a time range
const string country_code=NULL, // country code name (ISO 3166-1 alpha-2)
const string currency=NULL // country currency code name
);

Parameters
values[]
[out] M qlCalendarValue type array for receiving event values. S ee the example of handling
calendar events.
datetime_from
[in] Initial date of a time range events are selected from by a specified ID, while datetime_from <
datetime_to .
datetime_to=0
[in] End date of a time range events are selected from by a specified ID. If the datetime_to is not
set (or is 0), all event values beginning from the specified datetime_from date in the Calendar
database are returned (including the values of future events).
country_code=NULL
[in] Country code name (IS O 3166-1 alpha-2)
currency=NULL
[in] Country currency code name.

Return Value

If successful, return the number of available values in the 'values ' array, otherwise -1. To get
information about an error, call the GetLastError() function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR (general runtime error),
· 4004 – ERR_NOT _ENOUGH_M EMORY (not enough memory for executing a request),
· 5401 – ERR_CAL ENDAR_TIM EOUT (request time limit exceeded),
· 5400 – ERR_CAL ENDAR_MORE_DAT A (array size is insufficient for receiving descriptions of all
values, only the ones that managed to fit in were received),
· errors of failed execution of ArrayR esize()

Note

All functionsfor working with the economic calendar use the trade server time (TimeTradeS erver).
This means that the time in the M qlCalendarValue structure and the time inputs in the
CalendarValueHistoryByEvent/CalendarValueHistory functions are set in a trade server timezone,
rather than a user's local time.

© 2000-2025, MetaQuotes Ltd.


1871 Economic Calendar

If the events[] array of fixed length was passed to the function and there was not enough space to
save the entire result, the ERR_CALENDAR_MORE_DATA (5400) error is activated.
If the datetime_to is not set (or is 0), all event values beginning from the specified datetime_from
date in the Calendar database are returned (including the values of future events).
For the country_code and currency filters, NULL and "" values are equivalent and mean the absence
of the filter.
For country_code, the code field of the M qlCalendarCountry structure, for example "US" , "RU" or
"EU" , should be used.

For currency, the currency field of the M qlCalendarCountry structure, for example "USD" , "RUB" or
"EUR" , should be used.

The filters are applied by conjunction, i.e. logical 'AND' is used to select only the values of events
both conditions (country and currency) are simultaneously met for.
The M qlCalendarValue structure provides methods for checking and setting values from the
actual_value, forecast_value, prev _value and revised_prev _value fields. If no value is specified, the
field stores LONG_MIN (-9223372036854775808).
Please note that the values stored in these field are multiplied by one million. It means that when
you receive values in M qlCalendarValue using functions CalendarValueById,
CalendarValueHistoryByEvent, CalendarValueHistory, CalendarValueLastByEvent and
CalendarValueLast, you should check if the field values are equal to LONG_MIN; if a value is
specified in a field, then you should divide the value by 1,000,000 in order to get the value. Another
method to get the values is to check and to get values using the functions of the M qlCalendarValue
structure.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- country code for EU (ISO 3166-1 Alpha-2)
string EU_code="EU";
//--- get all EU event values
MqlCalendarValue values[];
//--- set the boundaries of the interval we take the events from
datetime date_from=D'01.01.2018'; // take all events from 2018
datetime date_to=0; // 0 means all known events, including the ones that have not
//--- request EU event history since 2018 year
if(CalendarValueHistory(values,date_from,date_to,EU_code))
{
PrintFormat("Received event values for country_code=%s: %d",
EU_code,ArraySize(values));
//--- decrease the size of the array for outputting to the Journal
ArrayResize(values,10);
//--- display event values in the Journal
ArrayPrint(values);

© 2000-2025, MetaQuotes Ltd.


1872 Economic Calendar

}
else
{
PrintFormat("Error! Failed to receive events for country_code=%s",EU_code);
PrintFormat("Error code: %d",GetLastError());
}
//---
}
/*
Result:
Received event values for country_code=EU: 1384
[id] [event_id] [time] [period] [revision] [actual_value] [prev_v
[0] 54215 999500001 2018.01.02 09:00:00 2017.12.01 00:00:00 3 60600000 60600
[1] 54221 999500002 2018.01.04 09:00:00 2017.12.01 00:00:00 3 56600000 56500
[2] 54222 999500003 2018.01.04 09:00:00 2017.12.01 00:00:00 3 58100000 58000
[3] 45123 999030005 2018.01.05 10:00:00 2017.11.01 00:00:00 0 600000 400
[4] 45124 999030006 2018.01.05 10:00:00 2017.11.01 00:00:00 0 2800000 2500
[5] 45125 999030012 2018.01.05 10:00:00 2017.12.01 00:00:00 1 900000 900
[6] 45126 999030013 2018.01.05 10:00:00 2017.12.01 00:00:00 1 1400000 1500
[7] 54953 999520001 2018.01.05 20:30:00 2018.01.02 00:00:00 0 127900000 92100
[8] 22230 999040003 2018.01.08 10:00:00 2017.12.01 00:00:00 0 9100000 8200
[9] 22231 999040004 2018.01.08 10:00:00 2017.12.01 00:00:00 0 18400000 16300
*/

See also
CalendarCountries, CalendarEventByCountry, CalendarValueHistoryByEvent, CalendarEventById,
CalendarValueById

© 2000-2025, MetaQuotes Ltd.


1873 Economic Calendar

CalendarValueLastByEvent
Get the array of event values by its ID since the Calendar database status with a specified change_id.
int CalendarValueLastByEvent(
ulong event_id, // event ID
ulong& change_id, // Calendar change ID
MqlCalendarValue& values[] // array for value descriptions
);

Parameters
event_id
[in] Event ID.

change_id
[in][out] Change ID.
values[]
[out] M qlCalendarValue type array for receiving event values. S ee the example of handling
calendar events.

Return Value

Number of received event values. To get information about an error, call the GetLastError()
function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR (general runtime error),
· 4004 – ERR_NOT _ENOUGH_M EMORY (not enough memory for executing a request),
· 5401 – ERR_CAL ENDAR_TIM EOUT (request time limit exceeded),
· 5400 – ERR_CAL ENDAR_MORE_DAT A (array size is insufficient for receiving descriptions of all
values, only the ones that managed to fit in were received),
· errors of failed execution of ArrayR esize()

Note

All functionsfor working with the economic calendar use the trade server time (TimeTradeS erver).
This means that the time in the M qlCalendarValue structure and the time inputs in the
CalendarValueHistoryByEvent/CalendarValueHistory functions are set in a trade server timezone,
rather than a user's local time.
If the events[] array of fixed length was passed to the function and there was not enough space to
save the entire result, the ERR_CALENDAR_MORE_DATA (5400) error is activated.
If change_id = 0 is passed to the function, the function always returns zero but the current calendar
database is returned to change_id.
The function returns the array for a specified news and a new change_id that can be used for
subsequent calls of the function to receive the new values of the news. Thus, it is possible to update
values for a specified news by calling this function with the last known change_id.
The M qlCalendarValue structure provides methods for checking and setting values from the
actual_value, forecast_value, prev _value and revised_prev _value fields. If no value is specified, the
field stores LONG_MIN (-9223372036854775808).

© 2000-2025, MetaQuotes Ltd.


1874 Economic Calendar

Please note that the values stored in these field are multiplied by one million. It means that when
you receive values in M qlCalendarValue using functions CalendarValueById,
CalendarValueHistoryByEvent, CalendarValueHistory, CalendarValueLastByEvent and
CalendarValueLast, you should check if the field values are equal to LONG_MIN; if a value is
specified in a field, then you should divide the value by 1,000,000 in order to get the value. Another
method to get the values is to check and to get values using the functions of the M qlCalendarValue
structure.
The sample EA listening for the Nonfarm payrolls report release:

#property description "Example of using the CalendarValueLastByEvent function"


#property description " for tracking the release of the Nonfarm Payrolls report."
#property description "To achieve this, get the current change ID"
#property description " of the Calendar database. Then, use this ID to receive"
#property description " only new events via the timer survey"
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create timer
EventSetTimer(60);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy timer
EventKillTimer();
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---

}
//+------------------------------------------------------------------+
//| Timer function |
//+------------------------------------------------------------------+
void OnTimer()
{
//--- Calendar database change ID
static ulong calendar_change_id=0;
//--- first launch attribute
static bool first=true;

© 2000-2025, MetaQuotes Ltd.


1875 Economic Calendar

//--- event ID
static ulong event_id=0;
//--- event name
static string event_name=NULL;
//--- event value array
MqlCalendarValue values[];
//--- perform initialization - get the current calendar_change_id
if(first)
{
MqlCalendarEvent events[];
//--- country code for USA (ISO 3166-1 Alpha-2)
string USA_code="US";
//--- get events for USA
int events_count=CalendarEventByCountry(USA_code,events);
//--- position of a necessary event in the 'events' array
int event_pos=-1;
//--- display USA events in the Journal
if(events_count>0)
{
PrintFormat("%s: USA events: %d",__FUNCTION__,events_count);
for(int i=0;i<events_count;i++)
{
string event_name_low=events[i].name;
//--- change an event name to lower case
if(!StringToLower(event_name_low))
{
PrintFormat("StringToLower() returned %d error",GetLastError());
//--- exit the function ahead of time
return;
}
//--- look for the "Nonfarm Payrolls" event
if(StringFind(event_name_low,"nonfarm payrolls")!=-1)
{
//--- event found, remember its ID
event_id=events[i].id;
//--- write the "Nonfarm Payrolls" event name
event_name=events[i].name;
//--- remember the events' position in the 'events[]' array
event_pos=i;
//--- keep in mind that the Calendar features several events containing "nonfarm pay
PrintFormat("Event \"Nonfarm Payrolls\" found: event_id=%d event_name=%s",event_id,
//--- view all the events by commenting out the 'break' operator to better understan
break;
}
}
//--- reduce the list by deleting events after "Nonfarm Payrolls"
ArrayRemove(events,event_pos+1);
//--- leave 9 events before "Nonfarm Payrolls" for more convenient analysis
ArrayRemove(events,0,event_pos-9);

© 2000-2025, MetaQuotes Ltd.


1876 Economic Calendar

ArrayPrint(events);
}
else
{
PrintFormat("%s: CalendarEventByCountry(%s) returned 0 events, error code=%d",
USA_code,__FUNCTION__,GetLastError());
//--- operation completed in a failure, try again during the next call of the timer
return;
}

//--- get the Calendar database change ID for the specified event
if(CalendarValueLastByEvent(event_id,calendar_change_id,values)>0)
{
//--- this code block cannot be executed during the first launch but let's add it anyway
PrintFormat("%s: Received the Calendar database current ID: change_id=%d",
__FUNCTION__,calendar_change_id);
//--- set the flag and exit before the timer's next event
first=false;
return;
}
else
{
//--- data are not received (this is normal for the first launch), check for an error
int error_code=GetLastError();
if(error_code==0)
{
PrintFormat("%s: Received the Calendar database current ID: change_id=%d",
__FUNCTION__,calendar_change_id);
//--- set the flag and exit before the timer's next event
first=false;
//--- now we have the calendar_change_id value
return;
}
else
{
//--- and this is really an error
PrintFormat("%s: Failed to get values for event_id=%d",__FUNCTION__,event_id);
PrintFormat("Error code: %d",error_code);
//--- operation completed in a failure, try again during the next call of the timer
return;
}
}
}

//--- we have the last known value of the Calendar change ID (change_id)
ulong old_change_id=calendar_change_id;
//--- check for a new Nonfarm Payrolls event value
if(CalendarValueLastByEvent(event_id,calendar_change_id,values)>0)
{

© 2000-2025, MetaQuotes Ltd.


1877 Economic Calendar

PrintFormat("%s: Received new events for \"%s\": %d",


__FUNCTION__,event_name,ArraySize(values));
//--- display data from the 'values' array in the Journal
ArrayPrint(values);
//--- display the values of the previous and new Calendar IDs in the Journal
PrintFormat("%s: Previous change_id=%d, new change_id=%d",
__FUNCTION__,old_change_id,calendar_change_id);
/*
write your code that is to handle "Nonfarm Payrolls" data release here
*/
}
//---
}
/*
Result:
OnTimer: USA events: 202
Event "Nonfarm Payrolls" found: event_id=840030016 event_name=Nonfarm Payrolls
[id] [type] [sector] [frequency] [time_mode] [country_id] [unit] [importance] [multipli
[0] 840030007 1 4 2 0 840 1 1
[1] 840030008 1 4 2 0 840 1 1
[2] 840030009 1 4 2 0 840 0 1
[3] 840030010 1 4 2 0 840 0 1
[4] 840030011 1 4 2 0 840 1 1
[5] 840030012 1 4 2 0 840 1 1
[6] 840030013 1 4 2 0 840 1 1
[7] 840030014 1 4 2 0 840 1 1
[8] 840030015 1 3 2 0 840 1 2
[9] 840030016 1 3 2 0 840 4 3
OnTimer: Received the Calendar database current ID: change_id=33986560

*/

See also
CalendarValueLast, CalendarValueHistory, CalendarValueHistoryByEvent, CalendarValueById

© 2000-2025, MetaQuotes Ltd.


1878 Economic Calendar

CalendarValueLast
Get the array of values for all events with the ability to sort by country and/or currency since the
calendar database status with a specified change_id.
int CalendarValueLast(
ulong& change_id, // change ID
MqlCalendarValue& values[], // array for value descriptions
const string country_code=NULL, // country code name (ISO 3166-1 alpha-2)
const string currency=NULL // country currency code name
);

Parameters
change_id
[in][out] Change ID.
values[]
[out] M qlCalendarValue type array for receiving event values. S ee the example of handling
calendar events.
country_code=NULL
[in] Country code name (IS O 3166-1 alpha-2)
currency=NULL
[in] Country currency code name.

Return Value

Number of received event values. To get information about an error, call the GetLastError()
function. Possible errors :
· 4001 – ERR_I NT ERNAL _ERR OR (general runtime error),
· 4004 – ERR_NOT _ENOUGH_M EMORY (not enough memory for executing a request),
· 5401 – ERR_CAL ENDAR_TIM EOUT (request time limit exceeded),
· 5400 – ERR_CAL ENDAR_MORE_DAT A (array size is insufficient for receiving descriptions of all
values, only the ones that managed to fit in were received),
· errors of failed execution of ArrayR esize()

Note

All functionsfor working with the economic calendar use the trade server time (TimeTradeS erver).
This means that the time in the M qlCalendarValue structure and the time inputs in the
CalendarValueHistoryByEvent/CalendarValueHistory functions are set in a trade server timezone,
rather than a user's local time.
If the events[] array of fixed length was passed to the function and there was not enough space to
save the entire result, the ERR_CALENDAR_MORE_DATA (5400) error is activated.
If change_id = 0 is passed to the function, you will get the current change_id of the calendar
database to that parameter; and the function returns 0
For the country_code and currency filters, NULL and "" values are equivalent and mean the absence
of the filter.

© 2000-2025, MetaQuotes Ltd.


1879 Economic Calendar

For country_code, the code field of the M qlCalendarCountry structure, for example "US" , "RU" or
"EU" , should be used.

For currency, the currency field of the M qlCalendarCountry structure, for example "USD" , "RUB" or
"EUR" , should be used.

The filters are applied by conjunction, i.e. logical 'AND' is used to select only the values of events
both conditions (country and currency) are simultaneously met for
The function returns the array for a specified news and a new change_id that can be used for
subsequent calls of the function to receive the new values of the news. Thus, it is possible to update
values for a specified news by calling this function with the last known change_id.
The M qlCalendarValue structure provides methods for checking and setting values from the
actual_value, forecast_value, prev _value and revised_prev _value fields. If no value is specified, the
field stores LONG_MIN (-9223372036854775808).
Please note that the values stored in these field are multiplied by one million. It means that when
you receive values in M qlCalendarValue using functions CalendarValueById,
CalendarValueHistoryByEvent, CalendarValueHistory, CalendarValueLastByEvent and
CalendarValueLast, you should check if the field values are equal to LONG_MIN; if a value is
specified in a field, then you should divide the value by 1,000,000 in order to get the value. Another
method to get the values is to check and to get values using the functions of the M qlCalendarValue
structure.
The sample EA listening for the economic calendar events:

#property description "Example of using the CalendarValueLast function"


#property description " to develop the economic calendar events listener."
#property description "To achieve this, get the current change ID"
#property description " of the Calendar database. Then, use this ID to receive"
#property description " only new events via the timer survey"
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create timer
EventSetTimer(60);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy timer
EventKillTimer();
}
//+------------------------------------------------------------------+
//| Expert tick function |

© 2000-2025, MetaQuotes Ltd.


1880 Economic Calendar

//+------------------------------------------------------------------+
void OnTick()
{
//---

}
//+------------------------------------------------------------------+
//| Timer function |
//+------------------------------------------------------------------+
void OnTimer()
{
//--- Calendar database change ID
static ulong calendar_change_id=0;
//--- first launch attribute
static bool first=true;
//--- event value array
MqlCalendarValue values[];
//--- perform initialization - get the current calendar_change_id
if(first)
{
//--- get the Calendar database change ID
if(CalendarValueLast(calendar_change_id,values)>0)
{
//--- this code block cannot be executed during the first launch but let's add it anyway
PrintFormat("%s: Received the Calendar database current ID: change_id=%d",
__FUNCTION__,calendar_change_id);
//--- set the flag and exit before the timer's next event
first=false;
return;
}
else
{
//--- data are not received (this is normal for the first launch), check for an error
int error_code=GetLastError();
if(error_code==0)
{
PrintFormat("%s: Received the Calendar database current ID: change_id=%d",
__FUNCTION__,calendar_change_id);
//--- set the flag and exit before the timer's next event
first=false;
//--- now we have the calendar_change_id value
return;
}
else
{
//--- and this is really an error
PrintFormat("%s: Failed to get events in CalendarValueLast. Error code: %d",
__FUNCTION__,error_code);
//--- operation completed in a failure, re-initialize during the next call of the timer

© 2000-2025, MetaQuotes Ltd.


1881 Economic Calendar

return;
}
}
}

//--- we have the last known value of the Calendar change ID (change_id)
ulong old_change_id=calendar_change_id;
//--- check if there are new Calendar events
if(CalendarValueLast(calendar_change_id,values)>0)
{
PrintFormat("%s: Received new Calendar events: %d",
__FUNCTION__,ArraySize(values));
//--- display data from the 'values' array in the Journal
ArrayPrint(values);
//--- display the values of the previous and new Calendar IDs in the Journal
PrintFormat("%s: Previous change_id=%d, new change_id=%d",
__FUNCTION__,old_change_id,calendar_change_id);
//--- display new events in the Journal
ArrayPrint(values);
/*
write your code that is to handle occurrence of events here
*/
}
//---
}
/*
Example of the listener operation:
OnTimer: Received the Calendar database current ID: change_id=33281792
OnTimer: Received new events for the Calendar: 1
[id] [event_id] [time] [period] [revision] [actual_value] [prev_val
[0] 91040 76020013 2019.03.20 15:30:00 1970.01.01 00:00:00 0 -5077000 -1913
OnTimer: Previous change_id=33281792, new change_id=33282048
[id] [event_id] [time] [period] [revision] [actual_value] [prev_val
[0] 91040 76020013 2019.03.20 15:30:00 1970.01.01 00:00:00 0 -5077000 -1913
OnTimer: Received new events for the Calendar: 1
[id] [event_id] [time] [period] [revision] [actual_value] [pr
[0] 91041 76020013 2019.03.27 15:30:00 1970.01.01 00:00:00 0 -9223372036854775808
OnTimer: Previous change_id=33282048, new change_id=33282560
[id] [event_id] [time] [period] [revision] [actual_value] [pr
[0] 91041 76020013 2019.03.27 15:30:00 1970.01.01 00:00:00 0 -9223372036854775808

*/

See also
CalendarValueLast, CalendarValueHistory, CalendarValueHistoryByEvent, CalendarValueById

© 2000-2025, MetaQuotes Ltd.


1882 Economic Calendar

© 2000-2025, MetaQuotes Ltd.


1883 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.
There is an important exception to this rule: if timeseries and indicator values need to be copied
often, for example at each call of OnTick() in Expert Advisors or at each call of OnCalculate() in
indicators, in this case one should better use statically distributed arrays, because operations of
memory allocation for dynamic arrays require additional time, and this will have effect during
testing and optimization.
W hen using functions accessing timeseries and indicator values, indexing direction should be taken
into account. This is described in the Indexing Direction in Arrays, Buffers and Timeseries section.
Access to indicator and timeseries data is implemented irrespective of the fact whether the requested
data are ready (the so called asynchronous access). This is critically important for the calculation of
custom indicator, so if there are no data, functions of Copy...() type immediately return an error.
H owever, when accessing form Expert Advisors and scripts, several attempts to receive data are made
in a small pause, which is aimed at providing some time necessary to download required timeseries or
to calculate indicator values.
The Organizing Data Access section describes details of receiving, storing and requesting price data in
the MetaTrader 5 client terminal.

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

© 2000-2025, MetaQuotes Ltd.


1884 Timeseries and Indicators Access

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

S eriesInfoInteger R eturns information about the state of historical data


Bars R eturns the number of bars count in the history for a specified symbol and
period
BarsCalculated R eturns the number of calculated data in an indicator buffer or -1 in the
case of error (data hasn't been calculated yet)
IndicatorCreate R eturns the handle to the specified technical indicator created by an array
of M qlParam type parameters
IndicatorParameters Based on the specified handle, returns the number of input parameters of
the indicator, as well as the values and types of the parameters
IndicatorRelease R emoves an indicator handle and releases the calculation block of the
indicator, if it's not used by anyone else
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
CopyS eries Gets the synchronized timeseries from the Rates structure for the
specified symbol-period and the specified amount
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
CopyS pread Gets history data on spreads for a specified symbol and period into an
array

© 2000-2025, MetaQuotes Ltd.


1885 Timeseries and Indicators Access

Function Action

CopyTicks Gets ticks in the M qlTick format into ticks _array


CopyTicks Range Gets tick s in the M qlTick format within the specified date range to
ticks _array
iBars R eturns the number of bars of a corresponding symbol and period,
available in history
iBarS hift R eturns the index of the bar corresponding to the specified time
iClose R eturns the Close price of the bar (indicated by the 'shift' parameter) on
the corresponding chart
iHigh R eturnsthe High price of the bar (indicated by the 'shift' parameter) on the
corresponding chart
iHighest R eturns the index of the highest value found on the corresponding chart
(shift relative to the current bar)
iLow R eturnsthe Low price of the bar (indicated by the 'shift' parameter) on the
corresponding chart
iLowest R eturns the index of the smallest value found on the corresponding chart
(shift relative to the current bar)
iOpen R eturns the Open price of the bar (indicated by the 'shift' parameter) on
the corresponding chart
iTime R eturnsthe opening time of the bar (indicated by the 'shift' parameter) on
the corresponding chart
iTickVolume R eturns the tick volume of the bar (indicated by the 'shift' parameter) on
the corresponding chart
iRealVolume R eturns the real volume of the bar (indicated by the 'shift' parameter) on
the corresponding chart
iVolume R eturns the tick volume of the bar (indicated by the 'shift' parameter) on
the corresponding chart
iS pread R eturnsthe spread value of the bar (indicated by the 'shift' parameter) on
the corresponding chart

Despite the fact that by using the ArrayS etAs S eries() 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)

© 2000-2025, MetaQuotes Ltd.


1886 Timeseries and Indicators Access

{
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

© 2000-2025, MetaQuotes Ltd.


1887 Timeseries and Indicators Access

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 TimeAs S eries array increases, the time value of the index
decreases, i.e. we move from the present to the past. For the common array ArrayNotS eries the result
is different - as index grows, we move from past to present.
See Also
ArrayIs Dynamic, ArrayGetAs S eries, ArrayS etAs S eries, ArrayIs S eries

© 2000-2025, MetaQuotes Ltd.


1888 Timeseries and Indicators Access

Indexing Direction in Arrays, Buffers and Timeseries


The default indexing of all arrays and indicator buffers is left to right. The index of the first element
is always equal to zero. Thus, the very first element of an array or indicator buffer with index 0 is by
default on the extreme left position, while the last element is on the extreme right position.
An indicator buffer is a dynamic array of type double, whose size is managed by the client terminals,
so that it always corresponds to the number of bars the indicator is calculated on. A usual dynamic
array of type double is assigned as an indicator buffer using the S etIndexBuffer() function. Indicator
buffers do not require setting of their size using function ArrayResize() - this will be done by the
executing system of the terminal.
Timeseries are arrays with reverse indexing, i.e. the first element of a timeseries is in the extreme
right position, and the last element is in the extreme left position. Timeseries being used for storing
history price data and contain the time information, we can say that the newest data are placed in the
extreme right position of the timeseries, while the oldest data are in the extreme left position.
So the timeseries element with index 0 contains the information about the latest quote of a symbol. If
a timeseries contains data on a daily timeframe, data of the current yet uncompleted day are located
on the zero position, and the position with index 1 contains yesterday data.

Changing the Indexing Direction

Function ArrayS etAs S eries()


allows changing the method of accessing elements of a dynamic array; the
physical order of data storing in the computer memory is not changed at that. This function simply
changes the method of addressing array elements, so when copying one array to another using
function ArrayCopy(), the contents of the recipient array will not depend on the indexing direction in
the source array.
Direction of
indexing cannot be changed for statically distributed arrays. Even if an array was passed
as a parameter to a function, attempts to change the indexing direction inside this function will bring
no effect.
For indicator buffers, like for usual arrays, indexing direction can also be set as backward (like in
timeseries), i.e. reference to the zero position in the indicator buffer will mean reference to the last
value on the corresponding indicator buffer and this will correspond to the value of the indicator on the
latest bar. S till, the physical location of indicator bars will be unchanged.

Receiving Price Data in Indicators

Each custom indicator must necessarily contain the OnCalculate() function, to which price data
required for calculating values in indicator buffers are passed. Indexing direction in these passed
arrays can be found out using function ArrayGetAs S eries().
Arrays passed to the function reflect price data, i.e. these arrays have the sign of a timeseries and
function ArrayIs S eries() will return true when checking these arrays. However, in any case indexing
direction should be checked only by function ArrayGetAs S eries().
In order not to be dependent on default values, ArrayS etAs S eries() should be unconditionally called for
the arrays you are going to work with, and set the required direction.

Receiving Price Data and Indicator Values

© 2000-2025, MetaQuotes Ltd.


1889 Timeseries and Indicators Access

Default indexing direction of all arrays in Expert Advisors, indicators and scripts is left-to-right. If
necessary, in any mql5 program you can request timeseries values on any symbol and timeframe, as
well as values of indicators calculated on any symbol and timeframe.
Use functions Copy...() for these purposes :
· CopyBuffer – copy values of an indicator buffer to an array of double type;
· CopyRates – copy price history to an array of structures M qlRates ;
· CopyTime – copy Time values to an array of datetime type;
· CopyOpen – copy Open values to an array of double type;
· CopyHigh – copy High values to an array of double type;
· CopyLow – copy Low values to an array of double type;
· CopyClose – copy Close values to an array of double type;
· CopyTickVolume – copy tick volumes to an array of long type;
· CopyRealVolume – copy equity volumes to a long type array;
· CopyS pread – copy the spread history to an array of int type;

All these functions work in a similar way. Let's consider the data obtaining mechanism on the example
of CopyBuffer(). It is implied that the indexing direction of requested data is that of timeseries, and
the position with index 0 (zero) stores data of the current yet uncompleted bar. In order to get access
to these data we need to copy the necessary volume of data into the recipient array, e.g. into array
buffer.

W hen copying we need to specify the starting position in the source array, starting from which data
will be copied to the recipient array. In case of success, the specified number of elements will be
copied to the recipient array from the source array (from the indicator buffer in this case).
Irrespective of the indexing value set in the recipient array, copying is always performed as is shown
in the above figure.
If it is expected that price data will be handled in a loop with a large number of iterations, it is
advisable that you check the fact of forced program termination using the Is S topped() function:
int copied=CopyBuffer(ma_handle,// Indicator handle
0, // The index of the indicator buffer
0, // Start position for copying
number, // Number of values to copy
Buffer // The array that receives the values

© 2000-2025, MetaQuotes Ltd.


1890 Timeseries and Indicators Access

);
if(copied<0) return;
int k=0;
while(k<copied && !IsStopped())
{
//--- Get the value for the k index
double value=Buffer[k];
// ...
// work with value
k++;
}

Example:

input int per=10; // period of the exponent


int ma_handle; // indicator handle
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
ma_handle=iMA(_Symbol,0,per,0,MODE_EMA,PRICE_CLOSE);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
double ema[10];
int copied=CopyBuffer(ma_handle,// indicator handle
0, // index of the indicator buffer
0, // starting position to copy from
10, // number of values for copying
ema // value receiving array
);
if(copied<0) return;
// .... further code
}

See also
Organizing Data Access

© 2000-2025, MetaQuotes Ltd.


1891 Timeseries and Indicators Access

Organizing Data Access


In this section questions connected with obtaining, storing and requesting price data (timeseries) are
considered.

Receiving Data from a Trade Server

Before price data become available in the MetaTrader 5 terminal, they must be received and
processed. To receive data, connection to the MetaTrader 5 trade server must be established. Data
are received in the form of packed blocks of minute bars from the server upon the request of a
terminal.
The mechanism of server reference for data doesn't depend on how the request has been initiated - by
a user when navigating in a chart or in a program way in the MQL5 language.

Storing Intermediate Data

Data received from a server are automatically unpacked and saved in the HCC intermediate format.
Data on each symbol are written into a separate folder:
terminal_directory\ bases \ server_name\ history\ symbol_name. For example, data on EURUSD received

from the MetaQuotes-Demo server will be stored in terminal_directory\bases \MetaQuotes-


Demo\history\EURUSD\.

Dataare written into files with .hcc extension. Each file stores data of minute bars for one year. For
example, the file named 2009.hcc in the EURUSD folder contains minute bars of EURUSD for year 2009.
These files are used for preparing price data for all timeframes and are not intended for direct access.

Obtaining Data on a Necessary Timeframe out of Intermediate Data

Intermediate HCC files are used as the data source for building price data for requested timeframes in
the HC format. Data of HC format are timeseries that are maximally prepared for a quick access. They
are created upon a request of a chart or a MQL5 program. The volume of data should not exceed the
value of the " Max bars in charts " parameter. Data are stored for further using in files with hc
extension.
To save resources, data on a timeframe are stored and saved in RAM only if necessary. If not called
for a long time, they are released from RAM and saved into a file. For each timeframe, data are
prepared regardless of whether there are ready data for other timeframes or not. Rules of forming and
accessing data are the same for all timeframes. I.e., despite the fact that the unit data stored in HCC
is one minute (M 1), the availability of HCC data doesn't mean the availability of data on M 1 timeframe
as HC in the same volume.
R eceipt of new data from a server calls automatic update of used price data in HC format of all
timeframes. It also leads to the recalculation of all indicators that implicitly use them as input data for
calculations.

Parameter "Max bars in chart"

The " Max bars in charts " parameter restricts number of bars in HC format available to charts,
indicators and mql5 programs. This is valid for all available timeframes and serves, first of all, to save
computer resources.

© 2000-2025, MetaQuotes Ltd.


1892 Timeseries and Indicators Access

W hen setting a large value of this parameter, it should be remembered, that if deep history price data
for small timeframes are available, memory used for storing timeseries and indicator buffers can
become hundreds of megabytes and reach the RAM restriction for the client terminal program (2Gb for
32-bit applications of M S W indows).

Change of the " Max bars in charts " comes into effect after the client terminal is restarted. Change of
this parameter causes neither automatic referring to a server for additional data, nor forming of
additional bars of timeseries. Additional price data are requested from the server, and timeseries are
updated taking into account the new limitation, in case of either chart scroll to the area with no data,
or when data are requested by a mql5 program.
Volume of data requested from the server corresponds to the required number of bars of this
timeframe with the " Max bars in charts " parameter taken into account. The restriction set by this
parameter is not strict, and in some cases the number of available bars for a timeframe can be a little
more than the current parameter value.

Data Availability

Presence of data on HCC format or even in the prepared for using HC format does not always denote
the absolute availability of these data to be shown in a chart or to be used in MQL5 programs.
W hen accessing to price data or indicator values from a mql5 program it should be remembered that
their availability in a certain moment of time or starting from a certain moment of time is not
guaranteed. It is connected with the fact that with the purpose of saving resources, the full copy of
data necessary for a mql5 program isn't stored in MetaTrader 5; only direct access to the terminal
database is given.
The price history for all timeframes is built from common data of HCC format, and any update of data
from a server leads to the update of data for all timeframes and to the recalculation of indicators. Due
to this access to data can be closed, even if these data were available a moment ago.

Synchronization of the Terminal Data and Server Data

S ince a
mql5 program can call data from any symbol and timeframe, there is a possibility that data of
a necessary timeseries are not formed yet in the terminal or the necessary price data aren't
synchronized with the trade server. In this case it's hard to predict the latency time.
Algorithms using " do-nothing" loops are not the best solution. The only exception in this case are
scripts, because they do not have any alternative algorithm choice due to not having event handling.
For custom indicators such algorithms, as well as any other " do-nothing " loops are strongly not
recommended, because they lead to termination of calculation of all indicators and any other handling
of price data of the symbol.
For Expert Advisors and indicators, it is better to use the event model of handling. If during handling
of OnTick() or OnCalculate() event, data receipt for the required timeseries failed, you should exit the
event handler, relying on the access availability during the next call of the handler.

Example of a Script for Adding History


Let's consider the example of a script that executes a request to receive history for the selected
symbol from a trade server. The script is intended for running in a chart of a selected symbol;

© 2000-2025, MetaQuotes Ltd.


1893 Timeseries and Indicators Access

timeframe doesn't matter, because, as it was mentioned above, price data are received from a trade
server as packed one minute data, from which any predefined timeseries is constructed then.
W rite all actions concerning data receipt as a separate function CheckLoadHistory(symbol, timeframe,
start_date):
int CheckLoadHistory(string symbol,ENUM_TIMEFRAMES period,datetime start_date)
{
}

The CheckLoadHistory() function is designed as a universal function that can be called from any
program (Expert Advisor, script or indicator); and therefore it requires three input parameters : symbol
name, period and start date to indicate the beginning of price history you need.
Insert necessary checks into the function code before requesting the missing history. First of all, we
should make sure that the symbol name and period value are correct:
if(symbol==NULL || symbol=="") symbol=Symbol();
if(period==PERIOD_CURRENT) period=Period();

Then let's make sure that the symbol is available in the MarketW atch window, i.e., the history for the
symbol will be available when sending a request to a trade server. If there is no such a symbol in
MarketW atch, add it using the S ymbolS elect() function.
if(!SymbolInfoInteger(symbol,SYMBOL_SELECT))
{f
if(GetLastError()==ERR_MARKET_UNKNOWN_SYMBOL) return(-1);
SymbolSelect(symbol,true);
}

Now we should receive the start date of the available history for the indicated symbol/period pair.
Perhaps, the value of the input parameter startdate, passed to CheckLoadHistory(), is within the
available history; then request to a trade server is not needed. In order to obtain the very first date
for the symbol-period as of the moment, the S eriesInfoInteger() function with the SERIES_FIRS TDATE
modifier is used.
SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date);
if(first_date>0 && first_date<=start_date) return(1);

The next important check is checking the type of the program, from which the function is called. Note
that it is not desirable to send a request to update the timeseries from indicator with the same
period. The undesirability of requesting data on the same symbol-period as that of the indicator is
conditioned by the fact that update of history data is performed in the same thread where the
indicator operates. S o the possibility of deadlock occurrence is high. To check this use the
MQL5InfoInteger() function with the MQL5_PROGRAM _TYPE modifier.
if(MQL5InfoInteger(MQL5_PROGRAM_TYPE)==PROGRAM_INDICATOR && Period()==period && Symbol()==symbol
return(-4);

If all the checks have been passed successfully, make the last attempt to do without referring to the
trade server. First let's find out the start date, for which minute data in HCC format are available.
R equest this value using the S eriesInfoInteger() function with the SER IES_T ER MINAL _FIRS T DAT E
modifier and again compare it to the value of the start_date parameter.

© 2000-2025, MetaQuotes Ltd.


1894 Timeseries and Indicators Access

if(SeriesInfoInteger(symbol,PERIOD_M1,SERIES_TERMINAL_FIRSTDATE,first_date))
{
//--- there is loaded data to build timeseries
if(first_date>0)
{
//--- force timeseries build
CopyTime(symbol,period,first_date+PeriodSeconds(period),1,times);
//--- check date
if(SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date))
if(first_date>0 && first_date<=start_date) return(2);
}
}

If after all the checks the execution thread is still in the body of the CheckLoadHistory() function, it
means there is a necessity to request the missing price data from a trade server. First, return the
value of " Max bars in chart" using the TerminalInfoInteger() function:
int max_bars=TerminalInfoInteger(TERMINAL_MAXBARS);

W e'llneed it to prevent requesting extra data. Then find the very first date in the symbol history on
the trade server (regardless of the period) using already known function S eriesInfoInteger() with the
SER IES_SERVER_FIRS T DAT E modifier.

datetime first_server_date=0;
while(!SeriesInfoInteger(symbol,PERIOD_M1,SERIES_SERVER_FIRSTDATE,first_server_date) && !IsStopp
Sleep(5);

S ince the request is an asynchronous operation, the function is called in the loop with a small delay of
5 milliseconds until the first_server_date variable receives a value, or the loop execution is
terminated by a user (Is S topped() will return true in this case). Let's indicate a correct value of the
start date, starting from which we request price data from a trade server.
if(first_server_date>start_date) start_date=first_server_date;
if(first_date>0 && first_date<first_server_date)
Print("Warning: first server date ",first_server_date," for ",
symbol," does not match to first series date ",first_date);

If the start date first_server_date of the server is lower than the start date first_date of the symbol in
H CC format, the corresponding entry will be output in the journal.

Now we are ready to make a request to a trade server as king for missing price data. Make the request
in the form of a loop and start filling out its body:
while(!IsStopped())
{
//1. wait for synchronization between the re-built timeseries and intermediate history as HHC
//2. receive the current number of bars in this timeseries
// if bars is larger than Max_bars_in_chart, we can exit, work is over
//3. obtain the start date first_date in the re-built timeseries and compare it to start_date
// if first_date is lower than start_date, we can exit, work is over
//4. request from a server a new part of history - 100 bars starting from last available bar
}

© 2000-2025, MetaQuotes Ltd.


1895 Timeseries and Indicators Access

The first three points are implemented by already known means.


while(!IsStopped())
{
//--- 1.wait till timeseries re-build process is over
while(!SeriesInfoInteger(symbol,period,SERIES_SYNCHRONIZED) && !IsStopped())
Sleep(5);
//--- 2.request how many bars we have
int bars=Bars(symbol,period);
if(bars>0)
{
//--- bars more than ones that can be drawn in the chart, exit
if(bars>=max_bars) return(-2);
//--- 3. return the current start date in the timeseries
if(SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date))
// start date was earlier than that requested, task completed
if(first_date>0 && first_date<=start_date) return(0);
}
//4. Request from a server a new part of history - 100 bars starting from last available bar
}

The last fourth point is left - requesting history. W e can't refer to a server directly, but any Copy-
function automatically initiates request sending to a server, if the history in HCC format is not
enough. S ince the time of the very first start date in the first_date variable is the simple and natural
criterion to evaluate the request execution degree, then the easiest way is to use the CopyTime()
function.
W hen calling functions that copy any data from timeseries, it should be noted that the start parameter
(number of the bar, starting from which price data should be copied) must always be within the
available terminal history. If you have only 100 bars, it meaningless to try copying 300 bars starting
from the bar with the index 500. S uch a request will be understood as an erroneous and won't be
handled, i.e. no additional history will be loaded from a trade server.
That's why we'll copy bars in groups of 100 starting from the bar with the bars index. This will provide
the smooth loading of missing history from a trade server. Actually a little more than the requested
100 bars will be loaded, while server sends oversized history.

int copied=CopyTime(symbol,period,bars,100,times);

After the copying operation, we should analyze the number of copied elements. If the attempt fails,
then value of the copied will be equal to null and the value of the fail_cnt counter will be increased by
1. After 100 failing attempts, the operation of the function will be stopped.

int fail_cnt=0;
...
int copied=CopyTime(symbol,period,bars,100,times);
if(copied>0)
{
//--- check data
if(times[0]<=start_date) return(0); // the copied value is smaller, ready
if(bars+copied>=max_bars) return(-2); // bars are more than can be drawn in the chart, ready

© 2000-2025, MetaQuotes Ltd.


1896 Timeseries and Indicators Access

fail_cnt=0;
}
else
{
//--- no more than 100 failing attempts in succession
fail_cnt++;
if(fail_cnt>=100) return(-5);
Sleep(10);
}

S o,
not only correct handling of the current situation at each moment of execution is implemented in
the function, but also the termination code is returned, that can be handled after calling the
CheckLoadHistory() function for getting additional information. For example, this way:
int res=CheckLoadHistory(InpLoadedSymbol,InpLoadedPeriod,InpStartDate);
switch(res)
{
case -1 : Print("Unknown symbol ",InpLoadedSymbol); break;
case -2 : Print("More requested bars than can be drawn in the chart"); break;
case -3 : Print("Execution stopped by user"); break;
case -4 : Print("Indicator mustn't load its own data"); break;
case -5 : Print("Loading failed"); break;
case 0 : Print("All data loaded"); break;
case 1 : Print("Already available data in timeseries are enough"); break;
case 2 : Print("Timeseries is built from available terminal data"); break;
default : Print("Execution result undefined");
}

The full code of the function can be found in the example of a script that shows the correct
organization of access to any data with the handling of request's results.
Code:

//+------------------------------------------------------------------+
//| TestLoadHistory.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.02"
#property script_show_inputs
//--- input parameters
input string InpLoadedSymbol="NZDUSD"; // Symbol to be load
input ENUM_TIMEFRAMES InpLoadedPeriod=PERIOD_H1; // Period to be loaded
input datetime InpStartDate=D'2006.01.01'; // Start date
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()

© 2000-2025, MetaQuotes Ltd.


1897 Timeseries and Indicators Access

{
Print("Start load",InpLoadedSymbol+","+GetPeriodName(InpLoadedPeriod),"from",InpStartDate);
//---
int res=CheckLoadHistory(InpLoadedSymbol,InpLoadedPeriod,InpStartDate);
switch(res)
{
case -1 : Print("Unknown symbol ",InpLoadedSymbol); break;
case -2 : Print("Requested bars more than max bars in chart"); break;
case -3 : Print("Program was stopped"); break;
case -4 : Print("Indicator shouldn't load its own data"); break;
case -5 : Print("Load failed"); break;
case 0 : Print("Loaded OK"); break;
case 1 : Print("Loaded previously"); break;
case 2 : Print("Loaded previously and built"); break;
default : Print("Unknown result");
}
//---
datetime first_date;
SeriesInfoInteger(InpLoadedSymbol,InpLoadedPeriod,SERIES_FIRSTDATE,first_date);
int bars=Bars(InpLoadedSymbol,InpLoadedPeriod);
Print("First date ",first_date," - ",bars," bars");
//---
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int CheckLoadHistory(string symbol,ENUM_TIMEFRAMES period,datetime start_date)
{
datetime first_date=0;
datetime times[100];
//--- check symbol & period
if(symbol==NULL || symbol=="") symbol=Symbol();
if(period==PERIOD_CURRENT) period=Period();
//--- check if symbol is selected in the Market Watch
if(!SymbolInfoInteger(symbol,SYMBOL_SELECT))
{
if(GetLastError()==ERR_MARKET_UNKNOWN_SYMBOL) return(-1);
SymbolSelect(symbol,true);
}
//--- check if data is present
SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date);
if(first_date>0 && first_date<=start_date) return(1);
//--- don't ask for load of its own data if it is an indicator
if(MQL5InfoInteger(MQL5_PROGRAM_TYPE)==PROGRAM_INDICATOR && Period()==period && Symbol()==symbol
return(-4);
//--- second attempt
if(SeriesInfoInteger(symbol,PERIOD_M1,SERIES_TERMINAL_FIRSTDATE,first_date))
{
//--- there is loaded data to build timeseries

© 2000-2025, MetaQuotes Ltd.


1898 Timeseries and Indicators Access

if(first_date>0)
{
//--- force timeseries build
CopyTime(symbol,period,first_date+PeriodSeconds(period),1,times);
//--- check date
if(SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date))
if(first_date>0 && first_date<=start_date) return(2);
}
}
//--- max bars in chart from terminal options
int max_bars=TerminalInfoInteger(TERMINAL_MAXBARS);
//--- load symbol history info
datetime first_server_date=0;
while(!SeriesInfoInteger(symbol,PERIOD_M1,SERIES_SERVER_FIRSTDATE,first_server_date) && !IsStopp
Sleep(5);
//--- fix start date for loading
if(first_server_date>start_date) start_date=first_server_date;
if(first_date>0 && first_date<first_server_date)
Print("Warning: first server date ",first_server_date," for ",symbol,
" does not match to first series date ",first_date);
//--- load data step by step
int fail_cnt=0;
while(!IsStopped())
{
//--- wait for timeseries build
while(!SeriesInfoInteger(symbol,period,SERIES_SYNCHRONIZED) && !IsStopped())
Sleep(5);
//--- ask for built bars
int bars=Bars(symbol,period);
if(bars>0)
{
if(bars>=max_bars) return(-2);
//--- ask for first date
if(SeriesInfoInteger(symbol,period,SERIES_FIRSTDATE,first_date))
if(first_date>0 && first_date<=start_date) return(0);
}
//--- copying of next part forces data loading
int copied=CopyTime(symbol,period,bars,100,times);
if(copied>0)
{
//--- check for data
if(times[0]<=start_date) return(0);
if(bars+copied>=max_bars) return(-2);
fail_cnt=0;
}
else
{
//--- no more than 100 failed attempts
fail_cnt++;

© 2000-2025, MetaQuotes Ltd.


1899 Timeseries and Indicators Access

if(fail_cnt>=100) return(-5);
Sleep(10);
}
}
//--- stopped
return(-3);
}
//+------------------------------------------------------------------+
//| Returns string value of the period |
//+------------------------------------------------------------------+
string GetPeriodName(ENUM_TIMEFRAMES period)
{
if(period==PERIOD_CURRENT) period=Period();
//---
switch(period)
{
case PERIOD_M1: return("M1");
case PERIOD_M2: return("M2");
case PERIOD_M3: return("M3");
case PERIOD_M4: return("M4");
case PERIOD_M5: return("M5");
case PERIOD_M6: return("M6");
case PERIOD_M10: return("M10");
case PERIOD_M12: return("M12");
case PERIOD_M15: return("M15");
case PERIOD_M20: return("M20");
case PERIOD_M30: return("M30");
case PERIOD_H1: return("H1");
case PERIOD_H2: return("H2");
case PERIOD_H3: return("H3");
case PERIOD_H4: return("H4");
case PERIOD_H6: return("H6");
case PERIOD_H8: return("H8");
case PERIOD_H12: return("H12");
case PERIOD_D1: return("Daily");
case PERIOD_W1: return("Weekly");
case PERIOD_MN1: return("Monthly");
}
//---
return("unknown period");
}

© 2000-2025, MetaQuotes Ltd.


1900 Timeseries and Indicators Access

SeriesInfoInteger
R eturns information about the state of historical data. There are 2 variants of function calls.
Directly returns the property value.

long SeriesInfoInteger(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
ENUM_SERIES_INFO_INTEGER prop_id, // property identifier
);

Returns true or false depending on the success of the function run.

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] S ymbol 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.

Return 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 its 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(),Period(),SERIES_BARS_COUNT));

Print("The first date for the symbol-period at this moment = ",


(datetime)SeriesInfoInteger(Symbol(),Period(),SERIES_FIRSTDATE));

© 2000-2025, MetaQuotes Ltd.


1901 Timeseries and Indicators Access

Print("The first date in the history for the symbol-period on the server = ",
(datetime)SeriesInfoInteger(Symbol(),Period(),SERIES_SERVER_FIRSTDATE));

Print("Symbol data are synchronized = ",


(bool)SeriesInfoInteger(Symbol(),Period(),SERIES_SYNCHRONIZED));
}

© 2000-2025, MetaQuotes Ltd.


1902 Timeseries and Indicators Access

Bars
R eturns 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] S ymbol name.

timeframe
[in] Period.
start_time
[in] Bar time corresponding to the first element.
stop_time
[in] Bar time corresponding to the last element.

Return 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.
Note

If data for the timeseries with specified parameters are not formed in the terminal by the time of
the Bars() function call, or data of the timeseries are not synchronized with a trade server by the
moment of the function call, the function returns a zero value.
W hen requesting the number of bars in a specified time interval, only bars with an open time falling
within the interval are considered. For example, if the current day of the week is S aturday and the
request is made for the number of W1 bars with start_time=last_tuesday and stop_time=last_friday,
the function will return 0 since the open time of a W1 timeframe is always S unday and not a single
W1 bar falls within the specified interval.

Sample request for the number of all history bars:

© 2000-2025, MetaQuotes Ltd.


1903 Timeseries and Indicators Access

int bars=Bars(_Symbol,_Period);
if(bars>0)
{
Print("Number of bars in the terminal history for the symbol-period at the moment = ",bars);
}
else //no available bars
{
//--- data on the symbol might be not synchronized with data on the server
bool synchronized=false;
//--- loop counter
int attempts=0;
// make 5 attempts to wait for synchronization
while(attempts<5)
{
if(SeriesInfoInteger(Symbol(),0,SERIES_SYNCHRONIZED))
{
//--- synchronization done, exit
synchronized=true;
break;
}
//--- increase the counter
attempts++;
//--- wait 10 milliseconds till the next iteration
Sleep(10);
}
//--- exit the loop after synchronization
if(synchronized)
{
Print("Number of bars in the terminal history for the symbol-period at the moment = ",bars
Print("The first date in the terminal history for the symbol-period at the moment = ",
(datetime)SeriesInfoInteger(Symbol(),0,SERIES_FIRSTDATE));
Print("The first date in the history for the symbol on the server = ",
(datetime)SeriesInfoInteger(Symbol(),0,SERIES_SERVER_FIRSTDATE));
}
//--- synchronization of data didn't happen
else
{
Print("Failed to get number of bars for ",_Symbol);
}
}

Sample request for the number of bars in the specified interval:


int n;
datetime date1 = D'2016.09.02 23:55'; // Friday
datetime date2 = D'2016.09.05 00:00'; // Monday
datetime date3 = D'2016.09.08 00:00'; // Thursday
//---
n=Bars(_Symbol,PERIOD_H1,D'2016.09.02 02:05',D'2016.09.02 10:55');

© 2000-2025, MetaQuotes Ltd.


1904 Timeseries and Indicators Access

Print("Number of bars: ",n); // Output: "Number of bars: 8", H2 bar is considered in the calcula
n=Bars(_Symbol,PERIOD_D1,date1,date2);
Print("Number of bars: ",n); // Output: "Number of bars: 1", since an open time of a single D1 (
n=Bars(_Symbol,PERIOD_W1,date2,date3);
Print("Number of bars: ",n); // Output: "Number of bars: 0", since not a single W1 bar open time

See also
Event H andling Functions

© 2000-2025, MetaQuotes Ltd.


1905 Timeseries and Indicators Access

BarsCalculated
R eturns 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.

Return Value

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

© 2000-2025, MetaQuotes Ltd.


1906 Timeseries and Indicators Access

else
Print("Upper fractals copied",
"i = ",i," copied = ",copied);
}
else Print("Upper fractals copied. ArraySize = ",ArraySize(Ups));
}

© 2000-2025, MetaQuotes Ltd.


1907 Timeseries and Indicators Access

IndicatorCreate
The function returns the handle of a specified technical indicator created based on the array of
parameters of M qlParam type.
int IndicatorCreate(
string symbol, // symbol name
ENUM_TIMEFRAMES period, // timeframe
ENUM_INDICATOR indicator_type, // indicator type from the enumeration ENUM_
int parameters_cnt=0, // number of parameters
const MqlParam& parameters_array[]=NULL, // array of parameters
);

Parameters
symbol
[in] Name of a symbol, on data of which the indicator is calculated. NULL means the current
symbol.
period
[in]The value of the timeframe can be one of values of the ENUM _TIM EFRAM ES enumeration, 0
means the current timeframe.
indicator_type
[in] Indicator type, can be one of values of the ENUM _INDICATOR enumeration.
parameters_cnt
[in]The number of parameters passed in the parameters _array[] array. The array elements have a
special structure type M qlParam. By default, zero - parameters are not passed. If you specify a
non-zero number of parameters, the parameter parameters_array is obligatory. You can pass no
more than 64 parameters.
parameters_array[]=NULL
[in] An array of M qlParam type, whose elements contain the type and value of each input
parameter of a technical indicator.

Return Value

R eturns the handle of a specified technical indicator, in case of failure returns INVALID_HANDLE.
Note

If the indicator handle of IND_CUS TOM type is created, the type field of the first element of the
array of input parameters parameters_array must have the TYPE_S TRING value of the
ENUM _DAT AT YPE enumeration, and the string_value field of the first element must contain the
name of the custom indicator. The custom indicator must be compiled (file with EX5 extension) and
located in the directory MQL5/Indicators of the client terminal or in a subdirectory.
Indicators that require testing are defined automatically from the call of the iCustom() function, if
the corresponding parameter is set through a constant string. For all other cases (use of the
IndicatorCreate() function or use of a non-constant string in the parameter that sets the indicator
name) the property #property tester_indicator is required:
#property tester_indicator "indicator_name.ex5"

© 2000-2025, MetaQuotes Ltd.


1908 Timeseries and Indicators Access

If the first form of the call is used in a custom indicator, you can additionally indicate as the last
parameter on what data it will be calculated when passing input parameters. If the "Apply to"
parameter is not specified explicitly, the default calculation is based on the PRICE_CLOSE values.
Example:

void OnStart()
{
MqlParam params[];
int h_MA,h_MACD;
//--- create iMA("EURUSD",PERIOD_M15,8,0,MODE_EMA,PRICE_CLOSE);
ArrayResize(params,4);
//--- set ma_period
params[0].type =TYPE_INT;
params[0].integer_value=8;
//--- set ma_shift
params[1].type =TYPE_INT;
params[1].integer_value=0;
//--- set ma_method
params[2].type =TYPE_INT;
params[2].integer_value=MODE_EMA;
//--- set applied_price
params[3].type =TYPE_INT;
params[3].integer_value=PRICE_CLOSE;
//--- create MA
h_MA=IndicatorCreate("EURUSD",PERIOD_M15,IND_MA,4,params);
//--- create iMACD("EURUSD",PERIOD_M15,12,26,9,h_MA);
ArrayResize(params,4);
//--- set fast ma_period
params[0].type =TYPE_INT;
params[0].integer_value=12;
//--- set slow ma_period
params[1].type =TYPE_INT;
params[1].integer_value=26;
//--- set smooth period for difference
params[2].type =TYPE_INT;
params[2].integer_value=9;
//--- set indicator handle as applied_price
params[3].type =TYPE_INT;
params[3].integer_value=h_MA;
//--- create MACD based on moving average
h_MACD=IndicatorCreate("EURUSD",PERIOD_M15,IND_MACD,4,params);
//--- use indicators
//--- . . .
//--- release indicators (first h_MACD)
IndicatorRelease(h_MACD);
IndicatorRelease(h_MA);
}

© 2000-2025, MetaQuotes Ltd.


1909 Timeseries and Indicators Access

IndicatorParameters
Based on the specified handle,returns the number of input parameters of the indicator, as well as the
values and types of the parameters.
int IndicatorParameters(
int indicator_handle, // indicator handle
ENUM_INDICATOR& indicator_type, // a variable for receiving the indicator type
MqlParam& parameters[] // an array for receiving parameters
);

Parameters
indicator_handle
[in] The handle of the indicator, for which you need to know the number of parameters its is
calculated on.
indicator_type
[out] A variable if the ENUM _INDICATOR type, into which the indicator type will be written.
parameters[]
[out] Adynamic array for receiving values of the M qlParam type, into which the list of indicator
parameters will be written. The array size is returned by the IndicatorParameters() function.

Return Value

The number of input parameters of the indicator with the specified handle. In case of an error
returns -1. For more details about the error call the GetLastError() function.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{

//--- The number of windows on the chart (at least one main window is always present)
int windows=(int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);
//--- Go through the chart windows
for(int w=0;w<windows;w++)
{
//--- The number of indicators in this window/subwindow
int total=ChartIndicatorsTotal(0,w);
//--- Take all indicators in the window
for(int i=0;i<total;i++)
{
//--- Get the short name of the indicator
string name=ChartIndicatorName(0,w,i);
//--- Get the indicator handle
int handle=ChartIndicatorGet(0,w,name);
//--- Add to log

© 2000-2025, MetaQuotes Ltd.


1910 Timeseries and Indicators Access

PrintFormat("Window=%d, indicator #%d, handle=%d",w,i,handle);


//---
MqlParam parameters[];
ENUM_INDICATOR indicator_type;
int params=IndicatorParameters(handle,indicator_type,parameters);
//--- The header of the message
string par_info="Short name "+name+", type "
+EnumToString(ENUM_INDICATOR(indicator_type))+"\r\n";
//---
for(int p=0;p<params;p++)
{
par_info+=StringFormat("parameter %d: type=%s, long_value=%d, double_value=%G,string_va
p,
EnumToString((ENUM_DATATYPE)parameters[p].type),
parameters[p].integer_value,
parameters[p].double_value,
parameters[p].string_value
);
}
Print(par_info);
}
//--- Done for all indicators in the window
}
//---
}

See also
ChartIndicatorGet()

© 2000-2025, MetaQuotes Ltd.


1911 Timeseries and Indicators Access

IndicatorRelease
The function removes an indicator handle and releases the calculation block of the indicator, if it's not
used by anyone else.
bool IndicatorRelease(
int indicator_handle // indicator handle
);

Return Value

R eturns true in case of success, otherwise returns false.


Note

The function allows removing an indicator handle, if it's no longer needed, thus saving memory. The
handle is removed immediately, the calculation block is deleted in some time (if it's not called
anymore).
W hen work ing in the strategy tester, the IndicatorRelease() function is not executed.
Example:

//+------------------------------------------------------------------+
//| Test_IndicatorRelease.mq5 |
//| Copyright 2010, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2010, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- input parameters
input int MA_Period=15;
input int MA_shift=0;
input ENUM_MA_METHOD MA_smooth=MODE_SMA;
input ENUM_APPLIED_PRICE price=PRICE_CLOSE;
//--- will store indicator handle
int MA_handle=INVALID_HANDLE;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create indicator handle
MA_handle=iMA(Symbol(),0,MA_Period,MA_shift,MA_smooth,PRICE_CLOSE);
//--- delete global variable
if(GlobalVariableCheck("MA_value"))
GlobalVariableDel("MA_value");
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1912 Timeseries and Indicators Access

//| Expert tick function |


//+------------------------------------------------------------------+
void OnTick()
{
//--- if the global variable value does not exist
if(!GlobalVariableCheck("MA_value"))
{
//--- obtain the indicator value in the last two bars
if(MA_handle!=INVALID_HANDLE)
{
//--- dynamic array for the indicator values
double values[];
if(CopyBuffer(MA_handle,0,0,2,values)==2 && values[0]!=EMPTY_VALUE)
{
//--- remember in the global variable value on the last but one bar
if(GlobalVariableSet("MA_value",values[0]))
{
//--- free the handle of the indicator
if(!IndicatorRelease(MA_handle))
Print("IndicatorRelease() failed. Error ",GetLastError());
else MA_handle=INVALID_HANDLE;
}
else
Print("GlobalVariableSet failed. Error ",GetLastError());
}
}
}
//---
}

© 2000-2025, MetaQuotes Ltd.


1913 Timeseries and Indicators Access

CopyBuffer
Gets data of a specified buffer of a certain indicator in the necessary quantity.

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).
W hen copying the yet unknown amount of data, it is recommended to use a dynamic array as a
buffer[] recipient buffer, because the CopyBuffer() function tries to allocate the size of the receiving
array to the size of the copied data. If an indicator buffer (array that is pre-allocated for storing
indicator values by the S etIndexBufer() function) is used as the buffer[] recipient array, partial copying
is allowed. An example can be found in the Awesome_Oscillator.mql5 custom indicator in the standard
terminal package.
If you need to make a partial copy of the indicator values into another array (non-indicator buffer),
you should use an intermediate array, to which the desired number is copied. After that conduct the
element-wise copying of the required number of values into the required places of a receiving array
from this intermediate one.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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 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

© 2000-2025, MetaQuotes Ltd.


1914 Timeseries and Indicators Access

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.

Return Value

R eturns the copied data count or -1 in case of an error.


Note

W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration.

© 2000-2025, MetaQuotes Ltd.


1915 Timeseries and Indicators Access

Example:

//+------------------------------------------------------------------+
//| TestCopyBuffer3.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://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 clrRed
#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("Parameter AsSeries = ",AsSeries);
Print("Indicator buffer after SetIndexBuffer() is a timeseries = ",
ArrayGetAsSeries(MABuffer));
//--- set short indicator name
IndicatorSetString(INDICATOR_SHORTNAME,"MA("+period+")"+AsSeries);
//--- set AsSeries (depends on input parameter)
ArraySetAsSeries(MABuffer,AsSeries);
Print("Indicator buffer after ArraySetAsSeries(MABuffer,true); is a timeseries = ",
ArrayGetAsSeries(MABuffer));
//---
ma_handle=iMA(Symbol(),0,period,shift,smootMode,price);
return(INIT_SUCCEEDED);
}

© 2000-2025, MetaQuotes Ltd.


1916 Timeseries and Indicators Access

//+------------------------------------------------------------------+
//| 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[])
{
//--- check if all data calculated
if(BarsCalculated(ma_handle)<rates_total) return(0);
//--- we can copy not all data
int to_copy;
if(prev_calculated>rates_total || prev_calculated<=0) to_copy=rates_total;
else
{
to_copy=rates_total-prev_calculated;
//--- last value is always copied
to_copy++;
}
//--- try to copy
if(CopyBuffer(ma_handle,0,0,to_copy,MABuffer)<=0) return(0);
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+

The above example illustrates how an indicator buffer is filled out with the values of another indicator
buffer from the indicator on the same symbol/period.
S ee a detailed example of history requesting data in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

See also

© 2000-2025, MetaQuotes Ltd.


1917 Timeseries and Indicators Access

Properties of Custom Indicators, S etIndexBuffer

© 2000-2025, MetaQuotes Ltd.


1918 Timeseries and Indicators Access

CopyRates
Gets history data of M qlRates structure of a specified symbol-period in specified quantity into the
rates _array array. The elements ordering of the copied data is from present to the past, i.e., starting
position of 0 means the current bar.

W hen copying the yet unknown amount of data, it is recommended to use dynamic 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.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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 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(

© 2000-2025, MetaQuotes Ltd.


1919 Timeseries and Indicators Access

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] S ymbol 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 M qlRates type.

Return Value

R eturns the number of copied elements or -1 in case of an error.


Note

If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_M AXBARS (maximal number of bars on the chart) is requested,
the function will also return -1.
W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
W hen requesting data by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.

© 2000-2025, MetaQuotes Ltd.


1920 Timeseries and Indicators Access

W hen requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time
Time) is always within the requested interval.
Thus, if the current day is S aturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open

time on a week timeframe is always S unday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos =0 and count=1.
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());
}

S ee a detailed example of requesting history data in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

© 2000-2025, MetaQuotes Ltd.


1921 Timeseries and Indicators Access

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

See also
S tructures and Classes, TimeToS tring, S tringFormat

© 2000-2025, MetaQuotes Ltd.


1922 Timeseries and Indicators Access

CopySeries
Gets the synchronized timeseries from the M qlRates structure for the specified symbol-period and the
specified amount. The data is received into the specified set of arrays. Elements are counted down
from the present to the past, which means that the starting position equal to 0 means the current bar.

If the data amount to be copied is unknown, it is recommended to use the dynamic array for the
receiving arrays, since if the data amount exceeds what an array can contain, this can cause the
attempt to redistribute the array to fit all of the requested data.
If you need to copy a predetermined amount of data, it is recommended to use a statistically allocated
buffer to avoid unnecessary memory reallocation.
The property of the receiving array — as _series =true or as _series =false — will be ignored: during
copying, the oldest timeseries element will be copied to the beginning of the physical memory
allocated for the array.
int CopySeries(
string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // amount to copy
ulong rates_mask, // combination of flags to specify the requested series
void& array1[], // array to receive the data of the first copies timeseries
void& array2[] // array to receive the data of the second copied timeseries
...
);

© 2000-2025, MetaQuotes Ltd.


1923 Timeseries and Indicators Access

Parameters
symbol_name
[in] S ymbol.

timeframe
[in] Period.
start_pos
[in] First copied element index.

count
[in] Number of copied elements.
rates_mask
[in] A combination of flags from the ENUM _COPY_RATES enumeration.
array1, array2,...
[out] Array of the appropriate type to receive the timeseries from the M qlRates structure. The
order of the arrays passed to the function must match the order of the fields in the M qlRates
structure.

Return Value

The number of copied elements or -1 if error occurs.


Note

If the entire interval of the requested data is beyond the data available on the server, the function
returns -1. If the requested data is beyond TERMINAL_M AXBARS (the maximum number of bars on
the chart), the function also returns -1.
W hen requesting data from an indicator, the function immediately returns -1 if requested
timeseries are not constructed yet or they should be downloaded from the server. However, this will
initiate data download/constructing itself.
W hen requesting data from an Expert Advisor or a script, download from the server is initiated if
the terminal does not have the appropriate data locally, or construction of the necessary timeseries
starts if the data can be constructed from the local history but they are not ready yet. The function
returns the amount of data that is ready by the time the timeout expires, however the history
download continues, and the function returns more data during the next similar request.

Difference between CopySeries and CopyRates

The CopyS eries function allows obtaining only the necessary timeseries into different specified arrays
during one call, while all of timeseries data will be synchronized. This means that all values in the
resulting arrays at a certain index N will belong to the same bar on the specified S ymbol/Timeframe
pair. Therefore, there is no need for the programmer to ensure the synchronization of all received
timeseries by the bar opening time.
Unlik eCopyRates, which returns the full set of timeseries as an M qlRates array, the CopyS eries
function allows the programmer to get only the required timeseries as separate arrays. This can be

© 2000-2025, MetaQuotes Ltd.


1924 Timeseries and Indicators Access

done by specifying a combination of flags to select the type of timeseries. The order of the arrays
passed to the function must match the order of the fields in the M qlRates structure:
struct MqlRates
{
datetime time; // period start time
double open; // open price
double high; // high price for the period
double low; // low price for the period
double close; // close price
long tick_volume; // tick volume
int spread; // spread
long real_volume; // exchange volume
}

Thus, if you need to get the values of the time, close and real_volume timeseries for the last 100 bars
of the current S ymbol/Timeframe, you should use the following call:
datetime time[];
double close[];
long volume[];
CopySeries(NULL,0,0,100,COPY_RATES_TIME|COPY_RATES_CLOSE|COPY_RATES_VOLUME_REAL,time,close,volume);

Mind the order of the arrays " time, close, volume" — it must match the order of the fields in the
M qlRates structure. The order of values in the rates_mask does not matter. The mas k could be as
follows :
COPY_RATES_VOLUME_REAL|COPY_RATES_TIME|COPY_RATES_CLOSE

Example:

//--- input parameters


input datetime InpDateFrom=D'2022.01.01 00:00:00';
input datetime InpDateTo =D'2023.01.01 00:00:00';
input uint InpCount =20;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart(void)
{
//--- arrays to get timeseries from the MqlRates price structure
double open[];
double close[];
float closef[];
datetime time1[], time2[];
//--- request close prices to a double array
ResetLastError();
int res1=CopySeries(NULL, PERIOD_CURRENT, 0, InpCount,
COPY_RATES_TIME|COPY_RATES_CLOSE, time1, close);
PrintFormat("1. CopySeries returns %d values. Error code=%d", res1, GetLastError());

© 2000-2025, MetaQuotes Ltd.


1925 Timeseries and Indicators Access

ArrayPrint(close);

//--- now also request open prices; use float array for close prices
ResetLastError();
int res2=CopySeries(NULL, PERIOD_CURRENT, 0, InpCount,
COPY_RATES_TIME|COPY_RATES_CLOSE|COPY_RATES_OPEN, time2, open, closef);
PrintFormat("2. CopySeries returns %d values. Error code=%d", res2, GetLastError());
ArrayPrint(closef);
//--- Compare the received data
if((res1==res2) && (time1[0]==time2[0]))
{
Print(" | Time | Open | Close double | Close float |");
for(int i=0; i<10; i++)
{
PrintFormat("%d | %s | %.5f | %.5f | %.5f |",
i, TimeToString(time1[i]), open[i], close[i], closef[i]);
}
}
//--- Result
1. CopySeries returns 20 values. Error code=0
[ 0] 1.06722 1.06733 1.06653 1.06520 1.06573 1.06649 1.06694 1.06675 1.06684 1.06604
[10] 1.06514 1.06557 1.06456 1.06481 1.06414 1.06394 1.06364 1.06386 1.06239 1.06247
2. CopySeries returns 20 values. Error code=0
[ 0] 1.06722 1.06733 1.06653 1.06520 1.06573 1.06649 1.06694 1.06675 1.06684 1.06604
[10] 1.06514 1.06557 1.06456 1.06481 1.06414 1.06394 1.06364 1.06386 1.06239 1.06247
| Time | Open | Close double | Close float |
0 | 2023.03.01 17:00 | 1.06660 | 1.06722 | 1.06722 |
1 | 2023.03.01 18:00 | 1.06722 | 1.06733 | 1.06733 |
2 | 2023.03.01 19:00 | 1.06734 | 1.06653 | 1.06653 |
3 | 2023.03.01 20:00 | 1.06654 | 1.06520 | 1.06520 |
4 | 2023.03.01 21:00 | 1.06520 | 1.06573 | 1.06573 |
5 | 2023.03.01 22:00 | 1.06572 | 1.06649 | 1.06649 |
6 | 2023.03.01 23:00 | 1.06649 | 1.06694 | 1.06694 |
7 | 2023.03.02 00:00 | 1.06683 | 1.06675 | 1.06675 |
8 | 2023.03.02 01:00 | 1.06675 | 1.06684 | 1.06684 |
9 | 2023.03.02 02:00 | 1.06687 | 1.06604 | 1.06604 |
//---
}

See also
S tructures and classes, CopyRates

© 2000-2025, MetaQuotes Ltd.


1926 Timeseries and Indicators Access

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.

W hen copying the yet unknown amount of data, it is recommended to use dynamic 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.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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(

© 2000-2025, MetaQuotes Ltd.


1927 Timeseries and Indicators Access

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] S ymbol 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.

Return Value

R eturns the copied data count or -1 in case of an error.


Note

If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_M AXBARS (maximal number of bars on the chart) is requested,
the function will also return -1.
W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
W hen requesting data by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.

© 2000-2025, MetaQuotes Ltd.


1928 Timeseries and Indicators Access

W hen requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time
Time) is always within the requested interval.
Thus, if the current day is S aturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open

time on a week timeframe is always S unday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos =0 and count=1.
S ee a detailed example of requesting history data in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

© 2000-2025, MetaQuotes Ltd.


1929 Timeseries and Indicators Access

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.

W hen copying the yet unknown amount of data, it is recommended to use dynamic 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.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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(

© 2000-2025, MetaQuotes Ltd.


1930 Timeseries and Indicators Access

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] S ymbol 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.

Return Value

R eturns the number of element in the array or -1 in case of an error.


Note

If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_M AXBARS (maximal number of bars on the chart) is requested,
the function will also return -1.
W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
W hen requesting data by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.

© 2000-2025, MetaQuotes Ltd.


1931 Timeseries and Indicators Access

W hen requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time
Time) is always within the requested interval.
Thus, if the current day is S aturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open

time on a week timeframe is always S unday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos =0 and count=1.
S ee a detailed example of requesting history data in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

© 2000-2025, MetaQuotes Ltd.


1932 Timeseries and Indicators Access

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.

W hen copying the yet unknown amount of data, it is recommended to use dynamic 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.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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(

© 2000-2025, MetaQuotes Ltd.


1933 Timeseries and Indicators Access

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] S ymbol 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.

Return Value

R eturns the copied data count or -1 in case of an error.


Note

If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_M AXBARS (maximal number of bars on the chart) is requested,
the function will also return -1.
W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
W hen requesting data by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.

© 2000-2025, MetaQuotes Ltd.


1934 Timeseries and Indicators Access

W hen requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time
Time) is always within the requested interval.
Thus, if the current day is S aturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open

time on a week timeframe is always S unday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos =0 and count=1.
Example:

#property copyright "2009, MetaQuotes Software Corp."


#property link "https://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()
{

© 2000-2025, MetaQuotes Ltd.


1935 Timeseries and Indicators Access

//--- on every tick we output the High and Low values for the bar with index,
//--- that is equal to the second, on which tick arrived
datetime t=TimeCurrent();
int sec=t%60;
printf("High[%d] = %G Low[%d] = %G",
sec,iHigh(Symbol(),0,sec),
sec,iLow(Symbol(),0,sec));
}

S ee adetailed example of requesting history data in the Methods of Object Binding section. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

© 2000-2025, MetaQuotes Ltd.


1936 Timeseries and Indicators Access

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.

W hen copying the yet unknown amount of data, it is recommended to use dynamic 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.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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(

© 2000-2025, MetaQuotes Ltd.


1937 Timeseries and Indicators Access

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] S ymbol.

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.

Return Value

R eturns the copied data count or -1 in case of an error.


Note

If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_M AXBARS (maximal number of bars on the chart) is requested,
the function will also return -1.
W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
W hen requesting data by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.

© 2000-2025, MetaQuotes Ltd.


1938 Timeseries and Indicators Access

W hen requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time
Time) is always within the requested interval.
Thus, if the current day is S aturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open

time on a week timeframe is always S unday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos =0 and count=1.
S ee a detailed example of requesting history data in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

See also
CopyHigh

© 2000-2025, MetaQuotes Ltd.


1939 Timeseries and Indicators Access

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.

W hen copying the yet unknown amount of data, it is recommended to use dynamic 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.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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(

© 2000-2025, MetaQuotes Ltd.


1940 Timeseries and Indicators Access

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] S ymbol 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.

Return Value

R eturns the copied data count or -1 in case of an error.


Note

If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_M AXBARS (maximal number of bars on the chart) is requested,
the function will also return -1.
W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
W hen requesting data by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.

© 2000-2025, MetaQuotes Ltd.


1941 Timeseries and Indicators Access

W hen requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time
Time) is always within the requested interval.
Thus, if the current day is S aturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open

time on a week timeframe is always S unday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos =0 and count=1.
S ee a detailed example of history data requesting in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

© 2000-2025, MetaQuotes Ltd.


1942 Timeseries and Indicators Access

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.

W hen copying the yet unknown amount of data, it is recommended to use dynamic 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.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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(

© 2000-2025, MetaQuotes Ltd.


1943 Timeseries and Indicators Access

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] S ymbol 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.

Return Value

R eturns the copied data count or -1 in case of an error.


Note

If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_M AXBARS (maximal number of bars on the chart) is requested,
the function will also return -1.
W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
W hen requesting data by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.

© 2000-2025, MetaQuotes Ltd.


1944 Timeseries and Indicators Access

W hen requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time
Time) is always within the requested interval.
Thus, if the current day is S aturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open

time on a week timeframe is always S unday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos =0 and count=1.
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[],

© 2000-2025, MetaQuotes Ltd.


1945 Timeseries and Indicators Access

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

S ee a detailed example of history data requesting in section Methods of Object Binding. The script
available in that section shows how to get the values of indicator iFractals on the last 1000 bars and
how to display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

© 2000-2025, MetaQuotes Ltd.


1946 Timeseries and Indicators Access

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.

W hen copying the yet unknown amount of data, it is recommended to use dynamic 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.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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(

© 2000-2025, MetaQuotes Ltd.


1947 Timeseries and Indicators Access

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] S ymbol 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.

Return Value

R eturns the copied data count or -1 in the case of error.


Note

If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_M AXBARS (maximal number of bars on the chart) is requested,
the function will also return -1.
W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
W hen requesting data by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.

© 2000-2025, MetaQuotes Ltd.


1948 Timeseries and Indicators Access

W hen requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time
Time) is always within the requested interval.
Thus, if the current day is S aturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open

time on a week timeframe is always S unday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos =0 and count=1.
S ee an example of history data requesting in section Methods of Object Binding. The script available
in that section shows how to get the values of indicator iFractals on the last 1000 bars and how to
display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

© 2000-2025, MetaQuotes Ltd.


1949 Timeseries and Indicators Access

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.

W hen copying the yet unknown amount of data, it is recommended to use dynamic 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.
If you know the amount of data you need to copy, it should better be done to a statically allocated
buffer, in order to prevent the allocation of excessive memory.
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(

© 2000-2025, MetaQuotes Ltd.


1950 Timeseries and Indicators Access

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] S ymbol 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.

Return Value

R eturns the copied data count or -1 in case of an error.


Note

If the whole interval of requested data is out of the available data on the server, the function
returns -1. If data outside TERMINAL_M AXBARS (maximal number of bars on the chart) is requested,
the function will also return -1.
W hen requesting data from the indicator, if requested timeseries are not yet built or they need to
be downloaded from the server, the function will immediately return -1, but the process of
downloading/building will be initiated.
W hen requesting data from an Expert Advisor or script, downloading from the server will be
initiated, if the terminal does not have these data locally, or building of a required timeseries will
start, if data can be built from the local history but they are not ready yet. The function will return
the amount of data that will be ready by the moment of timeout expiration, but history downloading
will continue, and at the next similar request the function will return more data.
W hen requesting data by the start date and the number of required elements, only data whose date
is less than (earlier) or equal to the date specified will be returned. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices Open, High,
Low, Close or open time Time) is always less or equal to the specified one.

© 2000-2025, MetaQuotes Ltd.


1951 Timeseries and Indicators Access

W hen requesting data in a specified range of dates, only data from this interval will be returned.
The interval is set and counted up to seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices Open, High, Low, Close or open time
Time) is always within the requested interval.
Thus, if the current day is S aturday, at the attempt to copy data on a week timeframe specifying
start_time=Last_Tuesday and stop_time=Last_Friday the function will return 0, because the open

time on a week timeframe is always S unday, but one week bar does not fall into the specified
interval.
If you need to return value corresponding to the current uncompleted bar, you can use the first form
of call specifying start_pos =0 and count=1.
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 clrRed
#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[],

© 2000-2025, MetaQuotes Ltd.


1952 Timeseries and Indicators Access

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

S ee an example of history data requesting in section Methods of Object Binding. The script available
in that section shows how to get the values of indicator iFractals on the last 1000 bars and how to
display the last 10 up and 10 down fractals on the chart. A similar technique can be used for all
indicators that have missing data and that are usually drawn using the following styles :
· DRAW_SECTION,

· DRAW_ARR OW ,

· DRAW_ZI GZAG,

· DRAW_COLOR_SECTION,

· DRAW_COLOR_ARR OW ,

· DRAW_COLOR_ZI GZAG.

© 2000-2025, MetaQuotes Ltd.


1953 Timeseries and Indicators Access

CopyTicks
The function receives ticks in the M qlTick format into ticks _array. In this case, ticks are indexed from
the past to the present, i.e. the 0 indexed tick is the oldest one in the array. For tick analysis, check
the flags field, which shows what exactly has changed in the tick.
int CopyTicks(
string symbol_name, // Symbol name
MqlTick& ticks_array[], // Tick receiving array
uint flags=COPY_TICKS_ALL, // The flag that determines the type of received ticks
ulong from=0, // The date from which you want to request ticks
uint count=0 // The number of ticks that you want to receive
);

Parameters
symbol_name
[in] S ymbol.

ticks_array
[out] An array of the M qlTick type for receiving ticks.
flags
[in] A flag to define the type of the requested ticks. COPY_TICKS_INFO – ticks with Bid and/or As k
changes, COPY_TICKS_TRADE – ticks with changes in Last and Volume, COPY_TICKS_ALL – all ticks.
For any type of request, the values of the previous tick are added to the remaining fields of the
M qlTick structure.
from
[in] The date from which you want to request ticks. In milliseconds since 1970.01.01. If from=0,
the last count ticks will be returned.
count
[in] The number of requested ticks. If the 'from' and 'count' parameters are not specified, all
available recent ticks (but not more than 2000) will be written to ticks _array[].

Returned value

The number of copied tick or -1 in case of an error.


Note

The CopyTicks() function allows requesting and analyzing all received ticks. The first call of
CopyTicks() initiates synchronization of the symbol's tick database stored on the hard dis k. If the
local database does not provide all the requested ticks, then missing ticks will be automatically
downloaded from the trade server. Ticks beginning with the from date specified in CopyTicks() till
the current moment will be synchronized. After that, all ticks arriving for this symbol will be added
to the tick database thus keeping it in the synchronized state.
If the from and count parameters are not specified, all available recent ticks (but not more than
2000) will be written to ticks_array[]. The flags parameter allows specifying the type of required
ticks.

© 2000-2025, MetaQuotes Ltd.


1954 Timeseries and Indicators Access

COPY_TICKS_INFO – ticks with Bid and/or As k price changes are returned. Data of other fields will
also be added. For example, if only the Bid has changed, the ask and volume fields will be filled with
last known values. To find out exactly what has changed, analyze the flags field, which will have the
value of TICK_FLAG_BID and/or TICK_FLAG_ASK. If a tick has zero values of the Bid and As k prices,
and the flags show that these data have changed (flags =TICK_FLAG_BID|TICK_FLAG_ASK), this
means that the order book (Market Depth) is empty. In other words, there are no buy and sell
orders.
COPY_TICKS_TRADE – ticks with the Last price and volume changes are returned. Data of other
fields will also be added, i.e. last known values of Bid and As k will be specified in the appropriate
fields. To find out exactly what has changed, analyze the flags field, which will have the
TICK_FLAG_LAS T and TICK_FLAG_VOLUM E value.
COPY_TICKS_ALL – all ticks with any change are returned. Unchanged fields will be filled with last
k nown values.

Call of CopyTicks() with the COPY_TICKS_ALL flag immediately returns all ticks from the request
interval, while calls in other modes require some time to process and select ticks, therefore they do
not provide significant speed advantage.
W hen requesting ticks (either COPY_TICKS_INFO or COPY_TICKS_TRADE), every tick contains full
price information as of the time of the tick (bid, ask, last and volume). This feature is provided for
an easier analysis of the trade state at the time of each tick, so there is no need to request a deep
tick history and search for the values of other fields.
In indicators, the CopyTicks() function returns the result: when called from an indicator,
CopyTick() immediately returns all available ticks of a symbol, and will launch synchronization of the
tick database, if available data is not enough. All indicators in one symbol operate in one common
thread, so the indicator cannot wait for the completion of synchronization. After synchronization,
CopyTicks() will return all requested ticks during the next call. In indicators, the OnCalculate()
function is called after the arrival of each tick.
CopyTicks() can wait for the result for 45 seconds in Expert Advisors and scripts: as distinct
from indicators, every Expert Advisor and script operate in a separate thread, and therefore can
wait 45 seconds till the completion of synchronization. If the required amount of ticks fails to be
synchronized during this time, CopyTicks() will return available ticks by timeout and will continue
synchronization. OnTick() in Expert Advisor is not a handler of every tick, it only notifies an Expert
Advisor about changes in the mark et. It can be a batch of changes : the terminal can simultaneously
make a few ticks, but OnTick() will be called only once to notify the EA of the latest market state.
The rate of data return: the terminal stores in the fast access cache 4,096 last tick s for each
instrument (65,536 ticks for symbols with a running Market Depth). If requested ticks for the
current trading session are beyond the cache, CopyTicks() calls the ticks stored in the terminal
memory. These requests require more time for execution. The slowest requests are those
requesting ticks for other days, since the data is read from the dis k in this case.
Example:

#property copyright "Copyright 2000-2024, MetaQuotes Ltd."


#property link "https://www.mql5.com"
#property version "1.00"
#property script_show_inputs
//--- Requesting 100 million ticks to be sure we receive the entire tick history
input int getticks=100000000; // The number of required ticks

© 2000-2025, MetaQuotes Ltd.


1955 Timeseries and Indicators Access

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int attempts=0; // Count of attempts
bool success=false; // The flag of a successful copying of ticks
MqlTick tick_array[]; // Tick receiving array
MqlTick lasttick; // To receive last tick data
SymbolInfoTick(_Symbol,lasttick);
//--- Make 3 attempts to receive ticks
while(attempts<3)
{
//--- Measuring start time before receiving the ticks
uint start=GetTickCount();
//--- Requesting the tick history since 1970.01.01 00:00.001 (parameter from=1 ms)
int received=CopyTicks(_Symbol,tick_array,COPY_TICKS_ALL,1,getticks);
if(received!=-1)
{
//--- Showing information about the number of ticks and spent time
PrintFormat("%s: received %d ticks in %d ms",_Symbol,received,GetTickCount()-start);
//--- If the tick history is synchronized, the error code is equal to zero
if(GetLastError()==0)
{
success=true;
break;
}
else
PrintFormat("%s: Ticks are not synchronized yet, %d ticks received for %d ms. Error=%d"
_Symbol,received,GetTickCount()-start,_LastError);
}
//--- Counting attempts
attempts++;
//--- A one-second pause to wait for the end of synchronization of the tick database
Sleep(1000);
}
//--- Receiving the requested ticks from the beginning of the tick history failed in three attempts
if(!success)
{
PrintFormat("Error! Failed to receive %d ticks of %s in three attempts",getticks,_Symbol);
return;
}
int ticks=ArraySize(tick_array);
//--- Showing the time of the first tick in the array
datetime firstticktime=tick_array[ticks-1].time;
PrintFormat("Last tick time = %s.%03I64u",
TimeToString(firstticktime,TIME_DATE|TIME_MINUTES|TIME_SECONDS),tick_array[ticks-1].
//--- Show the time of the last tick in the array

© 2000-2025, MetaQuotes Ltd.


1956 Timeseries and Indicators Access

datetime lastticktime=tick_array[0].time;
PrintFormat("First tick time = %s.%03I64u",
TimeToString(lastticktime,TIME_DATE|TIME_MINUTES|TIME_SECONDS),tick_array[0].time_ms

//---
MqlDateTime today;
datetime current_time=TimeCurrent();
TimeToStruct(current_time,today);
PrintFormat("current_time=%s",TimeToString(current_time));
today.hour=0;
today.min=0;
today.sec=0;
datetime startday=StructToTime(today);
datetime endday=startday+24*60*60;
if((ticks=CopyTicksRange(_Symbol,tick_array,COPY_TICKS_ALL,startday*1000,endday*1000))==-1)
{
PrintFormat("CopyTicksRange(%s,tick_array,COPY_TICKS_ALL,%s,%s) failed, error %d",
_Symbol,TimeToString(startday),TimeToString(endday),GetLastError());
return;
}
ticks=MathMax(100,ticks);
//--- Showing the first 100 ticks of the last day
int counter=0;
for(int i=0;i<ticks;i++)
{
datetime time=tick_array[i].time;
if((time>=startday) && (time<endday) && counter<100)
{
counter++;
PrintFormat("%d. %s",counter,GetTickDescription(tick_array[i]));
}
}
//--- Showing the first 100 deals of the last day
counter=0;
for(int i=0;i<ticks;i++)
{
datetime time=tick_array[i].time;
if((time>=startday) && (time<endday) && counter<100)
{
if(((tick_array[i].flags&TICK_FLAG_BUY)==TICK_FLAG_BUY) || ((tick_array[i].flags&TICK_FLAG
{
counter++;
PrintFormat("%d. %s",counter,GetTickDescription(tick_array[i]));
}
}
}
}
//+------------------------------------------------------------------+
//| Returns the string description of a tick |

© 2000-2025, MetaQuotes Ltd.


1957 Timeseries and Indicators Access

//+------------------------------------------------------------------+
string GetTickDescription(MqlTick &tick)
{
string desc=StringFormat("%s.%03d ",
TimeToString(tick.time),tick.time_msc%1000);
//--- Checking flags
bool buy_tick=((tick.flags&TICK_FLAG_BUY)==TICK_FLAG_BUY);
bool sell_tick=((tick.flags&TICK_FLAG_SELL)==TICK_FLAG_SELL);
bool ask_tick=((tick.flags&TICK_FLAG_ASK)==TICK_FLAG_ASK);
bool bid_tick=((tick.flags&TICK_FLAG_BID)==TICK_FLAG_BID);
bool last_tick=((tick.flags&TICK_FLAG_LAST)==TICK_FLAG_LAST);
bool volume_tick=((tick.flags&TICK_FLAG_VOLUME)==TICK_FLAG_VOLUME);
//--- Checking trading flags in a tick first
if(buy_tick || sell_tick)
{
//--- Forming an output for the trading tick
desc=desc+(buy_tick?StringFormat("Buy Tick: Last=%G Volume=%d ",tick.last,tick.volume):"");
desc=desc+(sell_tick?StringFormat("Sell Tick: Last=%G Volume=%d ",tick.last,tick.volume):"");
desc=desc+(ask_tick?StringFormat("Ask=%G ",tick.ask):"");
desc=desc+(bid_tick?StringFormat("Bid=%G ",tick.ask):"");
desc=desc+"(Trade tick)";
}
else
{
//--- Form a different output for an info tick
desc=desc+(ask_tick?StringFormat("Ask=%G ",tick.ask):"");
desc=desc+(bid_tick?StringFormat("Bid=%G ",tick.ask):"");
desc=desc+(last_tick?StringFormat("Last=%G ",tick.last):"");
desc=desc+(volume_tick?StringFormat("Volume=%d ",tick.volume):"");
desc=desc+"(Info tick)";
}
//--- Returning tick description
return desc;
}
//+------------------------------------------------------------------+
/* Example of the output
Si-12.16: received 11048387 ticks in 4937 ms
Last tick time = 2016.09.26 18:32:59.775
First tick time = 2015.06.18 09:45:01.000
1. 2016.09.26 09:45.249 Ask=65370 Bid=65370 (Info tick)
2. 2016.09.26 09:47.420 Ask=65370 Bid=65370 (Info tick)
3. 2016.09.26 09:50.893 Ask=65370 Bid=65370 (Info tick)
4. 2016.09.26 09:51.827 Ask=65370 Bid=65370 (Info tick)
5. 2016.09.26 09:53.810 Ask=65370 Bid=65370 (Info tick)
6. 2016.09.26 09:54.491 Ask=65370 Bid=65370 (Info tick)
7. 2016.09.26 09:55.913 Ask=65370 Bid=65370 (Info tick)
8. 2016.09.26 09:59.350 Ask=65370 Bid=65370 (Info tick)
9. 2016.09.26 09:59.678 Bid=65370 (Info tick)
10. 2016.09.26 10:00.000 Sell Tick: Last=65367 Volume=3 (Trade tick)

© 2000-2025, MetaQuotes Ltd.


1958 Timeseries and Indicators Access

11. 2016.09.26 10:00.000 Sell Tick: Last=65335 Volume=45 (Trade tick)


12. 2016.09.26 10:00.000 Sell Tick: Last=65334 Volume=95 (Trade tick)
13. 2016.09.26 10:00.191 Sell Tick: Last=65319 Volume=1 (Trade tick)
14. 2016.09.26 10:00.191 Sell Tick: Last=65317 Volume=1 (Trade tick)
15. 2016.09.26 10:00.191 Sell Tick: Last=65316 Volume=1 (Trade tick)
16. 2016.09.26 10:00.191 Sell Tick: Last=65316 Volume=10 (Trade tick)
17. 2016.09.26 10:00.191 Sell Tick: Last=65315 Volume=5 (Trade tick)
18. 2016.09.26 10:00.191 Sell Tick: Last=65313 Volume=3 (Trade tick)
19. 2016.09.26 10:00.191 Sell Tick: Last=65307 Volume=25 (Trade tick)
20. 2016.09.26 10:00.191 Sell Tick: Last=65304 Volume=1 (Trade tick)
21. 2016.09.26 10:00.191 Sell Tick: Last=65301 Volume=1 (Trade tick)
22. 2016.09.26 10:00.191 Sell Tick: Last=65301 Volume=10 (Trade tick)
23. 2016.09.26 10:00.191 Sell Tick: Last=65300 Volume=5 (Trade tick)
24. 2016.09.26 10:00.191 Sell Tick: Last=65300 Volume=1 (Trade tick)
25. 2016.09.26 10:00.191 Sell Tick: Last=65300 Volume=6 (Trade tick)
26. 2016.09.26 10:00.191 Sell Tick: Last=65299 Volume=1 (Trade tick)
27. 2016.09.26 10:00.191 Bid=65370 (Info tick)
28. 2016.09.26 10:00.232 Ask=65297 (Info tick)
29. 2016.09.26 10:00.276 Sell Tick: Last=65291 Volume=31 (Trade tick)
30. 2016.09.26 10:00.276 Sell Tick: Last=65290 Volume=1 (Trade tick)
*/

See also
S ymbolInfoTick , S tructure for Current Prices, OnTick()

© 2000-2025, MetaQuotes Ltd.


1959 Timeseries and Indicators Access

CopyTicksRange
The function receives ticks in the M qlTick format within the specified date range to ticks _array.
Indexing goes from the past to the present meaning that a tick with the index 0 is the oldest one in
the array. For tick analysis, check the flags field, which shows what exactly has changed.
int CopyTicksRange(
const string symbol_name, // symbol name
MqlTick& ticks_array[], // tick receiving array
uint flags=COPY_TICKS_ALL, // flag that defines the type of the ticks that are rece
ulong from_msc=0, // date, starting from which ticks are requested
ulong to_msc=0 // date, up to which ticks are requested
);

Parameters
symbol_name
[in] S ymbol.

ticks_array
[out] M qlTick static or dynamic array for receiving tick s. If the static array cannot hold all the
ticks from the requested time interval, the maximum possible amount of ticks is received. In this
case, the function generates the error ERR_HIS TORY_S M ALL_BUFFER (4407) .
flags
[in] A flag to define the type of the requested ticks. COPY_TICKS_INFO – ticks with Bid and/or As k
changes, COPY_TICKS_TRADE – ticks with changes in Last and Volume, COPY_TICKS_ALL – all ticks.
For any type of request, the values of the previous tick are added to the remaining fields of the
M qlTick structure.
from_msc
[in] The date, from which you want to request ticks. In milliseconds since 1970.01.01. If the
from_msc parameter is not specified, ticks from the beginning of the history are sent. Ticks with
the time >= from_msc are sent.
to_msc
[in] The date, up to which you want to request ticks. In milliseconds since 01.01.1970. Ticks with
the time <= to_msc are sent. If the to_msc parameter is not specified, all ticks up to the end of
the history are sent.

Return Value

The number of copied tick or -1 in case of an error. GetLastError() is able to return the following
errors :
· ERR_H I S TORY_TIM EOUT – tick s synchronization waiting time is up, the function has sent all it
had.
· ERR_H I S TORY_S M ALL _BUFFER – static buffer is too small. Only the amount the array can store has
been sent.
· ERR_NOT _ENOUGH_M EMORY – insufficient memory for receiving a history from the specified
range to the dynamic tick array. Failed to allocate enough memory for the tick array.
Note

© 2000-2025, MetaQuotes Ltd.


1960 Timeseries and Indicators Access

The CopyTicks Range() function is used for requesting ticks strictly from a specified range, for
example, from a certain day in history. At the same time, CopyTicks() allows specifying only a start
date, for example – receive all ticks from the beginning of the month till the current moment.
See also
S ymbolInfoTick , S tructure for Current Prices, OnTick, CopyTicks

© 2000-2025, MetaQuotes Ltd.


1961 Timeseries and Indicators Access

iBars
R eturns the number of bars of a corresponding symbol and period, available in history.
int iBars(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe // Period
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.

Return Value

The number of bars of a corresponding symbol and period, available in history, but no more than
allowed by the " Max bars in chart" parameter in platform settings.
Example:

Print("Bar count on the 'EURUSD,H1' is ",iBars("EURUSD",PERIOD_H1));

See also
Bars

© 2000-2025, MetaQuotes Ltd.


1962 Timeseries and Indicators Access

iBarShift
S earch bar by time. The function returns the index of the bar corresponding to the specified time.
int iBarShift(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
datetime time, // Time
bool exact=false // Mode
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in]Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. PERIOD_CURRENT
means the current chart period.
time
[in] Time value to search for.
exact=false
[in] A return value, in case the bar with the specified time is not found. If exact=false, iBarShift
returns the index of the nearest bar, the Open time of which is less than the specified time
(time_open<time). If such a bar is not found (history before the specified time is not available),
then the function returns -1. If exact=true, iBarS hift does not search for a nearest bar but
immediately returns -1.

Return Value

The index of the bar corresponding to the specified time. If the bar corresponding to the specified
time is not found (there is a gap in the history), the function returns -1 or the index of the nearest
bar (depending on the 'exact' parameter).
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- The date is on Sunday
datetime time=D'2002.04.25 12:00';
string symbol="GBPUSD";
ENUM_TIMEFRAMES tf=PERIOD_H1;
bool exact=false;
//--- If there is no bar at the specified time, iBarShift will return the index of the nearest bar
int bar_index=iBarShift(symbol,tf,time,exact);
//--- Check the error code after the call of iBarShift()
int error=GetLastError();

© 2000-2025, MetaQuotes Ltd.


1963 Timeseries and Indicators Access

if(error!=0)
{
PrintFormat("iBarShift(): GetLastError=%d - The requested date %s "+
"for %s %s is not found in the available history",
error,TimeToString(time),symbol,EnumToString(tf));
return;
}
//--- The iBarShift() function was executed successfully, return a result for exact=false
PrintFormat("1. %s %s %s(%s): bar index is %d (exact=%s)",
symbol,EnumToString(tf),TimeToString(time),
DayOfWeek(time),bar_index,string(exact));
datetime bar_time=iTime(symbol,tf,bar_index);
PrintFormat("Time of bar #%d is %s (%s)",
bar_index,TimeToString(bar_time),DayOfWeek(bar_time));
//--- Request the index of the bar with the specified time; if there is no bar -1 will be returned
exact=true;
bar_index=iBarShift(symbol,tf,time,exact);
//--- The iBarShift() function was executed successfully, return a result for exact=true
PrintFormat("2. %s %s %s (%s):bar index is %d (exact=%s)",
symbol,EnumToString(tf),TimeToString(time)
,DayOfWeek(time),bar_index,string(exact));
}
//+------------------------------------------------------------------+
//| Returns the name of the day of the week |
//+------------------------------------------------------------------+
string DayOfWeek(const datetime time)
{
MqlDateTime dt;
string day="";
TimeToStruct(time,dt);
switch(dt.day_of_week)
{
case 0: day=EnumToString(SUNDAY);
break;
case 1: day=EnumToString(MONDAY);
break;
case 2: day=EnumToString(TUESDAY);
break;
case 3: day=EnumToString(WEDNESDAY);
break;
case 4: day=EnumToString(THURSDAY);
break;
case 5: day=EnumToString(FRIDAY);
break;
default:day=EnumToString(SATURDAY);
break;
}
//---
return day;

© 2000-2025, MetaQuotes Ltd.


1964 Timeseries and Indicators Access

}
//+------------------------------------------------------------------+
/* Execution result
1. GBPUSD PERIOD_H1 2018.06.10 12:00(SUNDAY): bar index is 64 (exact=false)
Time of bar #64 is 2018.06.08 23:00 (FRIDAY)
2. GBPUSD PERIOD_H1 2018.06.10 12:00 (SUNDAY):bar index is -1 (exact=true)
*/

© 2000-2025, MetaQuotes Ltd.


1965 Timeseries and Indicators Access

iClose
R eturns the Close price of the bar (indicated by the 'shift' parameter) on the corresponding chart.
double iClose(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
int shift // Shift
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
shift
[in] The index of the received value from the timeseries (backward shift by specified number of
bars relative to the current bar).

Return Value

The Close price of the bar (indicated by the 'shift' parameter) on the corresponding chart or 0 in case
of an error. For error details, call the GetLastError() function.
Note

The function always returns actual data. For this purpose it performs a request to the timeseries for
the specified symbol/period during each call. This means that if there is no ready data during the
first function call, some time may be taken to prepare the result.
The function does not store previous calls results, and there is no local cache for quick value return.
Example:

input int shift=0;


//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick()
{
datetime time = iTime(Symbol(),Period(),shift);
double open = iOpen(Symbol(),Period(),shift);
double high = iHigh(Symbol(),Period(),shift);
double low = iLow(Symbol(),Period(),shift);
double close = iClose(NULL,PERIOD_CURRENT,shift);
long volume= iVolume(Symbol(),0,shift);
int bars = iBars(NULL,0);

Comment(Symbol(),",",EnumToString(Period()),"\n",

© 2000-2025, MetaQuotes Ltd.


1966 Timeseries and Indicators Access

"Time: " ,TimeToString(time,TIME_DATE|TIME_SECONDS),"\n",


"Open: " ,DoubleToString(open,Digits()),"\n",
"High: " ,DoubleToString(high,Digits()),"\n",
"Low: " ,DoubleToString(low,Digits()),"\n",
"Close: " ,DoubleToString(close,Digits()),"\n",
"Volume: ",IntegerToString(volume),"\n",
"Bars: " ,IntegerToString(bars),"\n"
);
}

See also
CopyClose, CopyRates

© 2000-2025, MetaQuotes Ltd.


1967 Timeseries and Indicators Access

iHigh
R eturns the High price of the bar (indicated by the 'shift' parameter) on the corresponding chart.
double iHigh(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
int shift // Shift
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
shift
[in] The index of the received value from the timeseries (backward shift by specified number of
bars relative to the current bar).

Return Value

The High price of the bar (indicated by the 'shift' parameter) on the corresponding chart or 0 in case
of an error. For error details, call the GetLastError() function.
Note

The function always returns actual data. For this purpose it performs a request to the timeseries for
the specified symbol/period during each call. This means that if there is no ready data during the
first function call, some time may be taken to prepare the result.
The function does not store previous calls results, and there is no local cache for quick value return.
Example:

input int shift=0;


//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick()
{
datetime time = iTime(Symbol(),Period(),shift);
double open = iOpen(Symbol(),Period(),shift);
double high = iHigh(Symbol(),Period(),shift);
double low = iLow(Symbol(),Period(),shift);
double close = iClose(NULL,PERIOD_CURRENT,shift);
long volume= iVolume(Symbol(),0,shift);
int bars = iBars(NULL,0);

Comment(Symbol(),",",EnumToString(Period()),"\n",

© 2000-2025, MetaQuotes Ltd.


1968 Timeseries and Indicators Access

"Time: " ,TimeToString(time,TIME_DATE|TIME_SECONDS),"\n",


"Open: " ,DoubleToString(open,Digits()),"\n",
"High: " ,DoubleToString(high,Digits()),"\n",
"Low: " ,DoubleToString(low,Digits()),"\n",
"Close: " ,DoubleToString(close,Digits()),"\n",
"Volume: ",IntegerToString(volume),"\n",
"Bars: " ,IntegerToString(bars),"\n"
);
}

See also
CopyHigh, CopyRates

© 2000-2025, MetaQuotes Ltd.


1969 Timeseries and Indicators Access

iHighest
R eturns the index of the highest value found on the corresponding chart (shift relative to the current
bar).
int iHighest(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
ENUM_SERIESMODE type, // Timeseries identifier
int count=WHOLE_ARRAY, // Number of elements
int start=0 // Index
);

Parameters
symbol
[in] The symbol, on which the search will be performed. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
type
[in] The identifier of the timeseries, in which the search will be performed. Can be equal to any
value from ENUM _SERIES MODE.
count=WHOLE_ARRAY
[in] The number of elements in the timeseries (from the current bar towards index increasing
direction), among which the search should be performed.
start=0
[in] The index (shift relative to the current bar) of the initial bar, from which search for the
highest value begins. Negative values ​are ignored and replaced with a zero value.

Return Value

The index of the highest value found on the corresponding chart (shift relative to the current bar) or
-1 in case of an error. For error details, call the GetLastError() function.
Example:

double val;
//--- Calculation of the highest Close value among 20 consecutive bars
//--- From index 4 to index 23 inclusive, on the current timeframe
int val_index=iHighest(NULL,0,MODE_CLOSE,20,4);
if(val_index!=-1)
val=High[val_index];
else
PrintFormat("iHighest() call error. Error code=%d",GetLastError());

© 2000-2025, MetaQuotes Ltd.


1970 Timeseries and Indicators Access

iLow
R eturns the Low price of the bar (indicated by the 'shift' parameter) on the corresponding chart.
double iLow(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
int shift // Shift
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
shift
[in] The index of the received value from the timeseries (backward shift by specified number of
bars relative to the current bar).

Return Value

The Low price of the bar (indicated by the 'shift' parameter) on the corresponding chart or 0 in case
of an error. For error details, call the GetLastError() function.
Note

The function always returns actual data. For this purpose it performs a request to the timeseries for
the specified symbol/period during each call. This means that if there is no ready data during the
first function call, some time may be taken to prepare the result.
The function does not store previous calls results, and there is no local cache for quick value return.
Example:

input int shift=0;


//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick()
{
datetime time = iTime(Symbol(),Period(),shift);
double open = iOpen(Symbol(),Period(),shift);
double high = iHigh(Symbol(),Period(),shift);
double low = iLow(Symbol(),Period(),shift);
double close = iClose(NULL,PERIOD_CURRENT,shift);
long volume= iVolume(Symbol(),0,shift);
int bars = iBars(NULL,0);

Comment(Symbol(),",",EnumToString(Period()),"\n",

© 2000-2025, MetaQuotes Ltd.


1971 Timeseries and Indicators Access

"Time: " ,TimeToString(time,TIME_DATE|TIME_SECONDS),"\n",


"Open: " ,DoubleToString(open,Digits()),"\n",
"High: " ,DoubleToString(high,Digits()),"\n",
"Low: " ,DoubleToString(low,Digits()),"\n",
"Close: " ,DoubleToString(close,Digits()),"\n",
"Volume: ",IntegerToString(volume),"\n",
"Bars: " ,IntegerToString(bars),"\n"
);
}

See also
CopyLow, CopyRates

© 2000-2025, MetaQuotes Ltd.


1972 Timeseries and Indicators Access

iLowest
R eturns the index of the smallest value found on the corresponding chart (shift relative to the current
bar).
int iLowest(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
ENUM_SERIESMODE type, // Timeseries identifier
int count=WHOLE_ARRAY, // Number of elements
int start=0 // Index
);

Parameters
symbol
[in] The symbol, on which the search will be performed. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
type
[in] The identifier of the timeseries, in which the search will be performed. Can be equal to any
value from ENUM _SERIES MODE.
count=WHOLE_ARRAY
[in] The number of elements in the timeseries (from the current bar towards index increasing
direction), among which the search should be performed.
start=0
[in] The index (shift relative to the current bar) of the initial bar, from which search for the
lowest value begins. Negative values ​are ignored and replaced with a zero value.

Return Value

The index of the lowest value found on the corresponding chart (shift relative to the current bar) or
-1 in case of an error. For error details, call the GetLastError() function.
Example:

double val;
//--- Search for a bar with the lowest value of the real volume among 15 consecutive bars
//--- From index 10 to index 24 inclusive, on the current timeframe
int val_index=iLowest(NULL,0,MODE_REAL_VOLUME,15,10);
if(val_index!=-1)
val=Low[val_index];
else
PrintFormat("iLowest() call error. Error code=%d",GetLastError());

© 2000-2025, MetaQuotes Ltd.


1973 Timeseries and Indicators Access

iOpen
R eturns the Open price of the bar (indicated by the 'shift' parameter) on the corresponding chart.
double iOpen(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
int shift // Shift
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
shift
[in] The index of the received value from the timeseries (backward shift by specified number of
bars relative to the current bar).

Return Value

The Open price of the bar (indicated by the 'shift' parameter) on the corresponding chart or 0 in case
of an error. For error details, call the GetLastError() function.
Note

The function always returns actual data. For this purpose it performs a request to the timeseries for
the specified symbol/period during each call. This means that if there is no ready data during the
first function call, some time may be taken to prepare the result.
The function does not store previous calls results, and there is no local cache for quick value return.
Example:

input int shift=0;


//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick()
{
datetime time = iTime(Symbol(),Period(),shift);
double open = iOpen(Symbol(),Period(),shift);
double high = iHigh(Symbol(),Period(),shift);
double low = iLow(Symbol(),Period(),shift);
double close = iClose(NULL,PERIOD_CURRENT,shift);
long volume= iVolume(Symbol(),0,shift);
int bars = iBars(NULL,0);

Comment(Symbol(),",",EnumToString(Period()),"\n",

© 2000-2025, MetaQuotes Ltd.


1974 Timeseries and Indicators Access

"Time: " ,TimeToString(time,TIME_DATE|TIME_SECONDS),"\n",


"Open: " ,DoubleToString(open,Digits()),"\n",
"High: " ,DoubleToString(high,Digits()),"\n",
"Low: " ,DoubleToString(low,Digits()),"\n",
"Close: " ,DoubleToString(close,Digits()),"\n",
"Volume: ",IntegerToString(volume),"\n",
"Bars: " ,IntegerToString(bars),"\n"
);
}

See also
CopyOpen, CopyRates

© 2000-2025, MetaQuotes Ltd.


1975 Timeseries and Indicators Access

iTime
R eturns the opening time of the bar (indicated by the 'shift' parameter) on the corresponding chart.
datetime iTime(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
int shift // Shift
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
shift
[in] The index of the received value from the timeseries (backward shift by specified number of
bars relative to the current bar).

Return Value

The opening time of the bar (indicated by the 'shift' parameter) on the corresponding chart or 0 in
case of an error. For error details, call the GetLastError() function.
Note

The function always returns actual data. For this purpose it performs a request to the timeseries for
the specified symbol/period during each call. This means that if there is no ready data during the
first function call, some time may be taken to prepare the result.
The function does not store previous calls results, and there is no local cache for quick value return.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- The date is on Sunday
datetime time=D'2018.06.10 12:00';
string symbol="GBPUSD";
ENUM_TIMEFRAMES tf=PERIOD_H1;
bool exact=false;
//--- there is no bar at the specified time, iBarShift will return the index of the nearest bar
int bar_index=iBarShift(symbol,tf,time,exact);
PrintFormat("1. %s %s %s(%s): bar index is %d (exact=%s)",
symbol,EnumToString(tf),TimeToString(time),DayOfWeek(time),bar_index,string(exact));
datetime bar_time=iTime(symbol,tf,bar_index);

© 2000-2025, MetaQuotes Ltd.


1976 Timeseries and Indicators Access

PrintFormat("Time of bar #%d is %s (%s)",


bar_index,TimeToString(bar_time),DayOfWeek(bar_time));
//PrintFormat(iTime(symbol,tf,bar_index));
//--- Request the index of the bar with the specified time; but there is no bar, return -1
exact=true;
bar_index=iBarShift(symbol,tf,time,exact);
PrintFormat("2. %s %s %s (%s):bar index is %d (exact=%s)",
symbol,EnumToString(tf),TimeToString(time),DayOfWeek(time),bar_index,string(exact));
}
//+------------------------------------------------------------------+
//| Returns the name of the day of the week |
//+------------------------------------------------------------------+
string DayOfWeek(const datetime time)
{
MqlDateTime dt;
string day="";
TimeToStruct(time,dt);
switch(dt.day_of_week)
{
case 0: day=EnumToString(SUNDAY);
break;
case 1: day=EnumToString(MONDAY);
break;
case 2: day=EnumToString(TUESDAY);
break;
case 3: day=EnumToString(WEDNESDAY);
break;
case 4: day=EnumToString(THURSDAY);
break;
case 5: day=EnumToString(FRIDAY);
break;
default:day=EnumToString(SATURDAY);
break;
}
//---
return day;
}
/* The result:
1. GBPUSD PERIOD_H1 2018.06.10 12:00(SUNDAY): bar index is 64 (exact=false)
Time of bar #64 is 2018.06.08 23:00 (FRIDAY)
2. GBPUSD PERIOD_H1 2018.06.10 12:00 (SUNDAY):bar index is -1 (exact=true)
*/

See also
CopyTime, CopyRates

© 2000-2025, MetaQuotes Ltd.


1977 Timeseries and Indicators Access

iTickVolume
R eturns the tick volume of the bar (indicated by the 'shift' parameter) on the corresponding chart.
long iTickVolume(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
int shift // Shift
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
shift
[in] The index of the received value from the timeseries (backward shift by specified number of
bars relative to the current bar).

Return Value

The tick volume of the bar (indicated by the 'shift' parameter) on the corresponding chart or 0 in
case of an error. For error details, call the GetLastError() function.
Note

The function always returns actual data. For this purpose it performs a request to the timeseries for
the specified symbol/period during each call. This means that if there is no ready data during the
first function call, some time may be taken to prepare the result.
The function does not store previous calls results, and there is no local cache for quick value return.
Example:

input int shift=0;


//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick()
{
datetime time = iTime(Symbol(),Period(),shift);
double open = iOpen(Symbol(),Period(),shift);
double high = iHigh(Symbol(),Period(),shift);
double low = iLow(Symbol(),Period(),shift);
double close = iClose(NULL,PERIOD_CURRENT,shift);
long volume= iVolume(Symbol(),0,shift);
int bars = iBars(NULL,0);

Comment(Symbol(),",",EnumToString(Period()),"\n",

© 2000-2025, MetaQuotes Ltd.


1978 Timeseries and Indicators Access

"Time: " ,TimeToString(time,TIME_DATE|TIME_SECONDS),"\n",


"Open: " ,DoubleToString(open,Digits()),"\n",
"High: " ,DoubleToString(high,Digits()),"\n",
"Low: " ,DoubleToString(low,Digits()),"\n",
"Close: " ,DoubleToString(close,Digits()),"\n",
"Volume: ",IntegerToString(volume),"\n",
"Bars: " ,IntegerToString(bars),"\n"
);
}

See also
CopyTickVolume, CopyRates

© 2000-2025, MetaQuotes Ltd.


1979 Timeseries and Indicators Access

iRealVolume
R eturns the real volume of the bar (indicated by the 'shift' parameter) on the corresponding chart.
long iRealVolume(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
int shift // Shift
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
shift
[in] The index of the received value from the timeseries (backward shift by specified number of
bars relative to the current bar).

Return Value

The real volume of the bar (indicated by the 'shift' parameter) on the corresponding chart or 0 in
case of an error. For error details, call the GetLastError() function.
Note

The function always returns actual data. For this purpose it performs a request to the timeseries for
the specified symbol/period during each call. This means that if there is no ready data during the
first function call, some time may be taken to prepare the result.
The function does not store previous calls results, and there is no local cache for quick value return.
Example:

input int shift=0;


//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick()
{
datetime time = iTime(Symbol(),Period(),shift);
double open = iOpen(Symbol(),Period(),shift);
double high = iHigh(Symbol(),Period(),shift);
double low = iLow(Symbol(),Period(),shift);
double close = iClose(NULL,PERIOD_CURRENT,shift);
long volume= iVolume(Symbol(),0,shift);
int bars = iBars(NULL,0);

Comment(Symbol(),",",EnumToString(Period()),"\n",

© 2000-2025, MetaQuotes Ltd.


1980 Timeseries and Indicators Access

"Time: " ,TimeToString(time,TIME_DATE|TIME_SECONDS),"\n",


"Open: " ,DoubleToString(open,Digits()),"\n",
"High: " ,DoubleToString(high,Digits()),"\n",
"Low: " ,DoubleToString(low,Digits()),"\n",
"Close: " ,DoubleToString(close,Digits()),"\n",
"Volume: ",IntegerToString(volume),"\n",
"Bars: " ,IntegerToString(bars),"\n"
);
}

See also
CopyRealVolume, CopyRates

© 2000-2025, MetaQuotes Ltd.


1981 Timeseries and Indicators Access

iVolume
R eturns the tick volume of the bar (indicated by the 'shift' parameter) on the corresponding chart.
long iVolume(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
int shift // Shift
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
shift
[in] The index of the received value from the timeseries (backward shift by specified number of
bars relative to the current bar).

Return Value

The tick volume of the bar (indicated by the 'shift' parameter) on the corresponding chart or 0 in
case of an error. For error details, call the GetLastError() function.
Note

The function always returns actual data. For this purpose it performs a request to the timeseries for
the specified symbol/period during each call. This means that if there is no ready data during the
first function call, some time may be taken to prepare the result.
The function does not store previous calls results, and there is no local cache for quick value return.
Example:

input int shift=0;


//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick()
{
datetime time = iTime(Symbol(),Period(),shift);
double open = iOpen(Symbol(),Period(),shift);
double high = iHigh(Symbol(),Period(),shift);
double low = iLow(Symbol(),Period(),shift);
double close = iClose(NULL,PERIOD_CURRENT,shift);
long volume= iVolume(Symbol(),0,shift);
int bars = iBars(NULL,0);

Comment(Symbol(),",",EnumToString(Period()),"\n",

© 2000-2025, MetaQuotes Ltd.


1982 Timeseries and Indicators Access

"Time: " ,TimeToString(time,TIME_DATE|TIME_SECONDS),"\n",


"Open: " ,DoubleToString(open,Digits()),"\n",
"High: " ,DoubleToString(high,Digits()),"\n",
"Low: " ,DoubleToString(low,Digits()),"\n",
"Close: " ,DoubleToString(close,Digits()),"\n",
"Volume: ",IntegerToString(volume),"\n",
"Bars: " ,IntegerToString(bars),"\n"
);
}

See also
CopyTickVolume, CopyRates

© 2000-2025, MetaQuotes Ltd.


1983 Timeseries and Indicators Access

iSpread
R eturns the spread value of the bar (indicated by the 'shift' parameter) on the corresponding chart.
long iSpread(
const string symbol, // Symbol
ENUM_TIMEFRAMES timeframe, // Period
int shift // Shift
);

Parameters
symbol
[in] The symbol name of the financial instrument. NULL means the current symbol.
timeframe
[in] Period. It can be one of the values of the ENUM _TIM EFRAM ES enumeration. 0 means the
current chart period.
shift
[in] The index of the received value from the timeseries (backward shift by specified number of
bars relative to the current bar).

Return Value

The S pread value of the bar (indicated by the 'shift' parameter) on the corresponding chart or 0 in
case of an error. For error details, call the GetLastError() function.
Note

The function always returns actual data. For this purpose it performs a request to the timeseries for
the specified symbol/period during each call. This means that if there is no ready data during the
first function call, some time may be taken to prepare the result.
The function does not store previous calls results, and there is no local cache for quick value return.
Example:

input int shift=0;


//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick()
{
datetime time = iTime(Symbol(),Period(),shift);
double open = iOpen(Symbol(),Period(),shift);
double high = iHigh(Symbol(),Period(),shift);
double low = iLow(Symbol(),Period(),shift);
double close = iClose(NULL,PERIOD_CURRENT,shift);
long volume= iVolume(Symbol(),0,shift);
int bars = iBars(NULL,0);

Comment(Symbol(),",",EnumToString(Period()),"\n",

© 2000-2025, MetaQuotes Ltd.


1984 Timeseries and Indicators Access

"Time: " ,TimeToString(time,TIME_DATE|TIME_SECONDS),"\n",


"Open: " ,DoubleToString(open,Digits()),"\n",
"High: " ,DoubleToString(high,Digits()),"\n",
"Low: " ,DoubleToString(low,Digits()),"\n",
"Close: " ,DoubleToString(close,Digits()),"\n",
"Volume: ",IntegerToString(volume),"\n",
"Bars: " ,IntegerToString(bars),"\n"
);
}

See also
CopyS pread, CopyRates

© 2000-2025, MetaQuotes Ltd.


1985 Custom Symbols

Custom symbols
Functions for creating and editing the custom symbol properties.
W hen connecting the terminal to a certain trade server, a user is able to work with time series of the
financial symbols provided by a broker. Available financial symbols are displayed as a list in the Market
W atch window. A separate group of functions allows receiving data on the symbol properties, trading
sessions and market depth updates.
The group of functions described in this section allows creating custom symbols. To do this, users are
able to apply the trade server's existing symbols, text files or external data sources.

Function Action

CustomS ymbolCreate Create a custom symbol with the specified name in the
specified group
CustomS ymbolDelete Delete a custom symbol with the specified name
CustomS ymbolS etInteger S et the integer type property value for a custom symbol
CustomS ymbolS etDouble S et the real type property value for a custom symbol
CustomS ymbolS etS tring S et the string type property value for a custom symbol
CustomS ymbolS etMarginRate S et the margin rates depending on the order type and direction
for a custom symbol
CustomS ymbolS etS essionQuote S et the start and end time of the specified quotation session
for the specified symbol and week day
CustomS ymbolS etS essionTrade S et the start and
end time of the specified trading session for
the specified symbol and week day
CustomRates Delete Delete all bars from the price history of the custom symbol in
the specified time interval
CustomRates Replace Fully replacethe price history of the custom symbol within the
specified time interval with the data from the M qlRates type
array
CustomRates Update Add missing bars to the custom symbol history and replace
existing data with the ones from the M qlRates type array
CustomTicks Add Adds data from an array of the M qlTick type to the price
history of a custom symbol. The custom symbol must be
selected in the Market W atch window
CustomTicks Delete Delete all ticks from the price history of the custom symbol in
the specified time interval
CustomTicks Replace Fully replacethe price history of the custom symbol within the
specified time interval with the data from the M qlTick type
array
CustomBookAdd Passes the status of the Depth of Market for a custom symbol

© 2000-2025, MetaQuotes Ltd.


1986 Custom Symbols

CustomSymbolCreate
Creates a custom symbol with the specified name in the specified group.
bool CustomSymbolCreate(
const string symbol_name, // custom symbol name
const string symbol_path="", // name of a group a symbol is to be created in
const string symbol_origin=NULL // name of a symbol used as a basis to create a custom sym
);

Parameters
symbol_name
[in] Custom symbol name. It should not contain groups or subgroups the symbol is located in.
symbol_path=""
[in] The group name a symbol is located in.
symbol_origin=NULL
[in] Name of a symbol the properties of a created custom symbol are to be copied from. After
creating a custom symbol, any property value can be changed to a necessary one using the
appropriate functions.

Return Value

true – success, otherwise – false. To get information about the error, call the GetLastError()
function.
Note

All customsymbols are created in the special Custom section. If a group name is not specified (the
symbol_path parameter in the CustomS ymbolCreate function contains an empty string or NULL), a

custom symbol is generated in the Custom section root. Here we can draw an analogy with the file
system, where groups and subgroups can be viewed as folders and subfolders
The symbol and group names may only contain Latin letters without punctuation, spaces or special
characters (may only contain " ." , "_" , "&" and "#" ). It is not recommended to use characters <, >, :,
" , /, |, ?, *.

The custom symbol name should be unique regardless of a group name it is created in. If a symbol
with the same name already exists, the CustomS ymbolCreate() function returns 'false', while the
subsequent GetLastError() call returns the error 5300 (ERR_NOT_CUS TOM _SYM BOL) or 5304
(ERR_CUS TOM _SYM BOL_EXIS T).
The length of the symbol name should not exceed 31 characters. Otherwise, CustomS ymbolCreate()
returns 'false' and the error 5302 – ERR_CUS TOM _SYM BOL_NAM E_LONG is activated.
The symbol_path parameter can be set in two ways :
· only a group name without a name of the custom symbol, for example – " CFD\\ Metals " . It is best
to use this option to avoid errors.
· or <group> name + groups separator "\\" +<custom symbol name>, for example – " CFD\\ Metals \
\Platinum" . In this case, the group name should end with the exact name of the custom symbol. In
case of a mismatch, the custom symbol is still created, but not in the intended group. For
example, if symbol_path=" CFD\\Metals \\Platinum" and symbol_name=" platinum" (register error),

© 2000-2025, MetaQuotes Ltd.


1987 Custom Symbols

then a custom symbol named " platinum" is created in the " Custom\CFD\Metals \Platinum" group.
The S ymbolInfoGetS tring(" platinum" ,SYM BOL _PAT H ) function returns the
" Custom\CFD\Metals \Platinum\platinum" value.

Note that the SYM BOL _PAT H property returns the path with the symbol name at the end. Therefore,
it cannot be copied without changes if you want to create a custom symbol in the exact same group.
In this case, it is necessary to cut the symbol name in order not to get the result described above.
If a non-existent symbol is set as the symbol_origin parameter, then the custom symbol is created
empty as if the symbol_origin parameter is not set. The error 4301 –
ERR_M ARKET _UNKNOWN_SYM BOL is activated in that case.

The symbol_path parameter length should not exceed 127 characters considering " Custom\\" , "\\"
groups separators and the symbol name if it is specified at the end.

Example:

//+------------------------------------------------------------------+
//| CustomSymbolCreate.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be cr
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based on

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- if failed to create a custom symbol, inform of that in the journal
if(!CustomSymbolCreate(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN))
{
Print("CustomSymbolCreate() failed. Error ", GetLastError());
return;
}

//--- check the existence of the created symbol and get the group it was created in
bool custom= false;
bool exist = SymbolExist(CUSTOM_SYMBOL_NAME, custom);
string path = SymbolInfoString(CUSTOM_SYMBOL_NAME, SYMBOL_PATH);

//--- print the result of creating the symbol and the name of the group (specified and obtained fro
PrintFormat("Custom symbol '%s' created\n"+

© 2000-2025, MetaQuotes Ltd.


1988 Custom Symbols

"Symbol '%s' is exist: %s\n"+


"Symbol '%s' is custom: %s\n"+
"Path specified in the settings: '%s'\n"+
"Path returned from the 'SYMBOL_PATH' property: '%s'",
CUSTOM_SYMBOL_NAME,
CUSTOM_SYMBOL_NAME, (string)exist,
CUSTOM_SYMBOL_NAME, (string)custom,
CUSTOM_SYMBOL_PATH,
path);

//--- wait two seconds and delete the created symbol with the resulting message in the journal
Sleep(2000);
ResetLastError();
bool deleted = CustomSymbolDelete(CUSTOM_SYMBOL_NAME);
Print(deleted ? StringFormat("Custom symbol '%s' removed", CUSTOM_SYMBOL_NAME) : StringFormat("C
/*
result:
Custom symbol 'EURUSD.C' created
Symbol 'EURUSD.C' is exist: true
Symbol 'EURUSD.C' is custom: true
Path specified in the settings: 'Forex'
Path returned from the 'SYMBOL_PATH' property: 'Custom\Forex\EURUSD.C'
Custom symbol 'EURUSD.C' removed
*/
}

See also
S ymbolName, S ymbolS elect, CustomS ymbolDelete

© 2000-2025, MetaQuotes Ltd.


1989 Custom Symbols

CustomSymbolDelete
Deletes a custom symbol with the specified name.
bool CustomSymbolDelete(
const string symbol_name // custom symbol name
);

Parameters
symbol
[in] Custom symbol name. It should not match the name of an already existing symbol.

Return Value

true – success, otherwise – false. To get information about the error, call the GetLastError()
function.
Note

The custom symbol displayed in the Market W atch or the one a chart is opened for cannot be
deleted.

Example:

//+------------------------------------------------------------------+
//| CustomSymbolDelete.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be cr
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based on

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- if failed to create a custom symbol, inform of that in the journal
if(!CustomSymbolCreate(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN))
{
Print("CustomSymbolCreate() failed. Error ", GetLastError());
return;
}

© 2000-2025, MetaQuotes Ltd.


1990 Custom Symbols

//--- check the existence of the created symbol and print the result in the journal
bool custom= false;
bool exist = SymbolExist(CUSTOM_SYMBOL_NAME, custom);
PrintFormat("Custom symbol '%s' exists: %s", CUSTOM_SYMBOL_NAME, (string)exist);

//--- wait two seconds and delete the created symbol with the resulting message in the journal
Sleep(2000);
ResetLastError();
bool deleted = CustomSymbolDelete(CUSTOM_SYMBOL_NAME);
Print(deleted ? StringFormat("Custom symbol '%s' removed", CUSTOM_SYMBOL_NAME) : StringFormat("C

//--- check the existence of the created symbol and print the result in the journal
exist = SymbolExist(CUSTOM_SYMBOL_NAME, custom);
PrintFormat("Custom symbol '%s' exists: %s", CUSTOM_SYMBOL_NAME, (string)exist);
/*
result:
Custom symbol 'EURUSD.C' exists: true
Custom symbol 'EURUSD.C' removed
Custom symbol 'EURUSD.C' exists: false
*/
}

See also
S ymbolName, S ymbolS elect, CustomS ymbolCreate

© 2000-2025, MetaQuotes Ltd.


1991 Custom Symbols

CustomSymbolSetInteger
S ets the integer type property value for a custom symbol.
bool CustomSymbolSetInteger(
const string symbol_name, // symbol name
ENUM_SYMBOL_INFO_INTEGER property_id, // property ID
long property_value // property value
);

Parameters
symbol_name
[in] Custom symbol name.
property_id
[in] S ymbol property ID. The value can be one of the values of the ENUM _SYM BOL_INFO_INTEGER
enumeration.
property_value
[in] A long type variable containing the property value.

Return Value

true – success, otherwise – false. To get information about the error, call the GetLastError()
function.
Note

The minute and tick history of the custom symbol is completely removed if any of these properties is
changed in the symbol specification:
· SYM BOL _CHAR T _MODE – price type for constructing bars (Bid or Last)
· SYM BOL _DI GIT S – number of digits after the decimal point to display the price

Afterdeleting the custom symbol history, the terminal attempts to create a new history using the
updated properties. The same happens when the custom symbol properties are changed manually.

Example:

//+------------------------------------------------------------------+
//| CustomSymbolSetInteger.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be cr
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based on

© 2000-2025, MetaQuotes Ltd.


1992 Custom Symbols

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get and print in the journal the properties of the symbol the custom one is based on
//--- (trading mode, Stop order installation level and trading operations freezing distance)
ENUM_SYMBOL_TRADE_EXECUTION origin_exe_mode = (ENUM_SYMBOL_TRADE_EXECUTION)SymbolInfoInteger(CUS
int origin_stops_level = (int)SymbolInfoInteger(CUSTOM_SYMBOL_ORIGIN, SYMBOL_TRADE_STOPS_LEVEL);
int origin_freeze_level= (int)SymbolInfoInteger(CUSTOM_SYMBOL_ORIGIN, SYMBOL_TRADE_FREEZE_LEVEL)

PrintFormat("The '%s' symbol from which the custom '%s' was created:\n"+
" Deal execution mode: %s\n Stops Level: %d\n Freeze Level: %d",
CUSTOM_SYMBOL_ORIGIN, CUSTOM_SYMBOL_NAME,
StringSubstr(EnumToString(origin_exe_mode), 23), origin_stops_level, origin_freeze_l

//--- set other values for the custom symbol properties


ResetLastError();
bool res=true;
res &=CustomSymbolSetInteger(CUSTOM_SYMBOL_NAME, SYMBOL_TRADE_EXEMODE, SYMBOL_TRADE_EXECUTION_MA
res &=CustomSymbolSetInteger(CUSTOM_SYMBOL_NAME, SYMBOL_TRADE_STOPS_LEVEL, 10);
res &=CustomSymbolSetInteger(CUSTOM_SYMBOL_NAME, SYMBOL_TRADE_FREEZE_LEVEL, 3);

//--- if there was an error when setting any of the properties, display an appropriate message in t
if(!res)
Print("CustomSymbolSetInteger() failed. Error ", GetLastError());

//--- get and print in the journal the modified custom symbol properties
//--- (trading mode, Stop order installation level and trading operations freezing distance)
ENUM_SYMBOL_TRADE_EXECUTION custom_exe_mode = (ENUM_SYMBOL_TRADE_EXECUTION)SymbolInfoInteger(CUS
int custom_stops_level = (int)SymbolInfoInteger(CUSTOM_SYMBOL_NAME, SYMBOL_TRADE_STOPS_LEVEL);
int custom_freeze_level= (int)SymbolInfoInteger(CUSTOM_SYMBOL_NAME, SYMBOL_TRADE_FREEZE_LEVEL);

PrintFormat("Custom symbol '%s' based on '%s':\n"+


" Deal execution mode: %s\n Stops Level: %d\n Freeze Level: %d",
CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_ORIGIN,
StringSubstr(EnumToString(custom_exe_mode), 23), custom_stops_level, custom_freeze_l

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S

© 2000-2025, MetaQuotes Ltd.


1993 Custom Symbols

//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{
Sleep(16);
//--- when pressing Del, delete the created custom symbol
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
The 'EURUSD' symbol from which the custom 'EURUSD.C' was created:
Deal execution mode: INSTANT
Stops Level: 0
Freeze Level: 0
Custom symbol 'EURUSD.C' based on 'EURUSD':
Deal execution mode: MARKET
Stops Level: 10
Freeze Level: 3
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


1994 Custom Symbols

bool DeleteCustomSymbol(const string symbol_name)


{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}

See also
S ymbolInfoInteger

© 2000-2025, MetaQuotes Ltd.


1995 Custom Symbols

CustomSymbolSetDouble
S ets the real type property value for a custom symbol.
bool CustomSymbolSetDouble(
const string symbol_name, // symbol name
ENUM_SYMBOL_INFO_DOUBLE property_id, // property ID
double property_value // property value
);

Parameters
symbol_name
[in] Custom symbol name.
property_id
[in] S ymbol
property ID. The value can be one of the values of the ENUM _SYM BOL_INFO_DOUBLE
enumeration.
property_value
[in] A double type variable containing the property value.

Return Value

true – success, otherwise – false. To get information about the error, call the GetLastError()
function.
Note

The minute and tick history of the custom symbol is completely removed if any of these properties is
changed in the symbol specification:
· SYM BOL _POI NT – one point value
· SYM BOL _T RADE_TICK_S I ZE – value of a tick that specifies the minimum allowable price change
· SYM BOL _T RADE_TICK_VAL UE – one-tick price change value for a profitable position

Afterdeleting the custom symbol history, the terminal attempts to create a new history using the
updated properties. The same happens when the custom symbol properties are changed manually.

Example:

//+------------------------------------------------------------------+
//| CustomSymbolSetDouble.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be cr

© 2000-2025, MetaQuotes Ltd.


1996 Custom Symbols

#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based on

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get and print in the journal the properties of the symbol the custom one is based on
//--- (minimum volume, maximum volume, minimum volume change step for deal execution)
double origin_vol_min = SymbolInfoDouble(CUSTOM_SYMBOL_ORIGIN, SYMBOL_VOLUME_MIN);
double origin_vol_max = SymbolInfoDouble(CUSTOM_SYMBOL_ORIGIN, SYMBOL_VOLUME_MAX);
double origin_vol_step= SymbolInfoDouble(CUSTOM_SYMBOL_ORIGIN, SYMBOL_VOLUME_STEP);

PrintFormat("The '%s' symbol from which the custom '%s' was created:\n"+
" Volume Min: %.2f\n Volume Max: %.2f\n Volume Step: %.2f",
CUSTOM_SYMBOL_ORIGIN, CUSTOM_SYMBOL_NAME,
origin_vol_min, origin_vol_max, origin_vol_step);

//--- set other values for the custom symbol properties


ResetLastError();
bool res=true;
res &=CustomSymbolSetDouble(CUSTOM_SYMBOL_NAME, SYMBOL_VOLUME_MIN, 0.1);
res &=CustomSymbolSetDouble(CUSTOM_SYMBOL_NAME, SYMBOL_VOLUME_MAX, 1000);
res &=CustomSymbolSetDouble(CUSTOM_SYMBOL_NAME, SYMBOL_VOLUME_STEP, 0.1);

//--- if there was an error when setting any of the properties, display an appropriate message in t
if(!res)
Print("CustomSymbolSetDouble() failed. Error ", GetLastError());

//--- get and print in the journal the modified custom symbol properties
//--- (minimum volume, maximum volume, minimum volume change step for deal execution)
double custom_vol_min = SymbolInfoDouble(CUSTOM_SYMBOL_NAME, SYMBOL_VOLUME_MIN);
double custom_vol_max = SymbolInfoDouble(CUSTOM_SYMBOL_NAME, SYMBOL_VOLUME_MAX);
double custom_vol_step= SymbolInfoDouble(CUSTOM_SYMBOL_NAME, SYMBOL_VOLUME_STEP);

PrintFormat("Custom symbol '%s' based on '%s':\n"+


" Volume Min: %.2f\n Volume Max: %.2f\n Volume Step: %.2f",
CUSTOM_SYMBOL_ORIGIN, CUSTOM_SYMBOL_NAME,
custom_vol_min, custom_vol_max, custom_vol_step);

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S

© 2000-2025, MetaQuotes Ltd.


1997 Custom Symbols

//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{
Sleep(16);
//--- when pressing Del, delete the created custom symbol
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
The 'EURUSD' symbol from which the custom 'EURUSD.C' was created:
Volume Min: 0.01
Volume Max: 500.00
Volume Step: 0.01
Custom symbol 'EURUSD' based on 'EURUSD.C':
Volume Min: 0.10
Volume Max: 1000.00
Volume Step: 0.10
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |

© 2000-2025, MetaQuotes Ltd.


1998 Custom Symbols

//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}

See also
S ymbolInfoDouble

© 2000-2025, MetaQuotes Ltd.


1999 Custom Symbols

CustomSymbolSetString
S ets the string type property value for a custom symbol.
bool CustomSymbolSetString(
const string symbol_name, // symbol name
ENUM_SYMBOL_INFO_STRING property_id, // property ID
string property_value // property value
);

Parameters
symbol_name
[in] Custom symbol name.
property_id
[in] S ymbolproperty ID. The value can be one of the values of the ENUM _SYM BOL_INFO_S TRING
enumeration.
property_value
[in] A string type variable containing the property value.

Return Value

true – success, otherwise – false. To get information about the error, call the GetLastError()
function.
Note

The minute and tick history of the custom symbol is completely removed if the SYM BOL_FORM ULA
property (setting the equation for the custom symbol price construction) is changed in the symbol
specification. After deleting the custom symbol history, the terminal attempts to create a new
history using the new equation. The same happens when the custom symbol equation is changed
manually.

Example:

//+------------------------------------------------------------------+
//| CustomSymbolSetString.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be cr
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based on

//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


2000 Custom Symbols

//| Script program start function |


//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get and print in the journal the properties of the symbol the custom one is based on
//--- (minimum volume, maximum volume, minimum volume change step for deal execution)
string origin_basis = SymbolInfoString(CUSTOM_SYMBOL_ORIGIN, SYMBOL_BASIS);
string origin_category = SymbolInfoString(CUSTOM_SYMBOL_ORIGIN, SYMBOL_CATEGORY);
string origin_formula = SymbolInfoString(CUSTOM_SYMBOL_ORIGIN, SYMBOL_FORMULA);

PrintFormat("The '%s' symbol from which the custom '%s' was created:\n"+
" Basis: %s\n Category: %s\n Formula: %s",
CUSTOM_SYMBOL_ORIGIN, CUSTOM_SYMBOL_NAME,
origin_basis, origin_category, origin_formula);

//--- set other values for the custom symbol properties


ResetLastError();
bool res=true;
res &=CustomSymbolSetString(CUSTOM_SYMBOL_NAME, SYMBOL_BASIS, CUSTOM_SYMBOL_ORIGIN);
res &=CustomSymbolSetString(CUSTOM_SYMBOL_NAME, SYMBOL_CATEGORY, "FX");
res &=CustomSymbolSetString(CUSTOM_SYMBOL_NAME, SYMBOL_FORMULA, ("1.0 / "+CUSTOM_SYMBOL_ORIGIN))

//--- if there was an error when setting any of the properties, display an appropriate message in t
if(!res)
Print("CustomSymbolSetString() failed. Error ", GetLastError());

//--- get and print in the journal the modified custom symbol properties
//--- (minimum volume, maximum volume, minimum volume change step for deal execution)
string custom_basis = SymbolInfoString(CUSTOM_SYMBOL_NAME, SYMBOL_BASIS);
string custom_category = SymbolInfoString(CUSTOM_SYMBOL_NAME, SYMBOL_CATEGORY);
string custom_formula = SymbolInfoString(CUSTOM_SYMBOL_NAME, SYMBOL_FORMULA);

PrintFormat("Custom symbol '%s' based on '%s':\n"+


" Basis: %s\n Category: %s\n Formula: %s",
CUSTOM_SYMBOL_ORIGIN, CUSTOM_SYMBOL_NAME,
custom_basis, custom_category, custom_formula);

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S

//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)

© 2000-2025, MetaQuotes Ltd.


2001 Custom Symbols

{
Sleep(16);
//--- when pressing Del, delete the created custom symbol
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
The 'EURUSD' symbol from which the custom 'EURUSD.C' was created:
Basis:
Category:
Formula:
Custom symbol 'EURUSD' based on 'EURUSD.C':
Basis: EURUSD
Category: FX
Formula: 1.0 / EURUSD
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{

© 2000-2025, MetaQuotes Ltd.


2002 Custom Symbols

//--- hide the symbol from the Market Watch window


ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}

See also
S ymbolInfoS tring

© 2000-2025, MetaQuotes Ltd.


2003 Custom Symbols

CustomSymbolSetMarginRate
S ets the margin rates depending on the order type and direction for a custom symbol.
bool CustomSymbolSetMarginRate(
const string symbol_name, // symbol name
ENUM_ORDER_TYPE order_type, // order type
double initial_margin_rate, // initial margin rate
double maintenance_margin_rate // maintenance margin rate
);

Parameters
symbol_name
[in] Custom symbol name.
order_type
[in] Order type.
initial_margin_rate
[in] A double type variable with an initial margin rate. Initial margin is a security deposit for 1 lot
deal in the appropriate direction. Multiplying the rate by the initial margin, we receive the amount
of funds to be reserved on the account when placing an order of the specified type.
maintenance_margin_rate
[in] A double type variable with a maintenance margin rate. Maintenance margin is a minimum
amount for maintaining an open position of 1 lot in the appropriate direction. Multiplying the rate
by the maintenance margin, we receive the amount of funds to be reserved on the account after
an order of the specified type is activated.

Return Value

true – success, otherwise – false. To get information about the error, call the GetLastError()
function.

Example:

//+------------------------------------------------------------------+
//| CustomSymbolSetMarginRate.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be cr
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based on

© 2000-2025, MetaQuotes Ltd.


2004 Custom Symbols

#define INITIAL_MARGIN_RATE 1.5 // initial margin rate


#define MAINTENANCE_MARGIN_RATE 1.5 // maintenance margin rate

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get and print in the journal the properties of the symbol the custom one is based on
//--- (initial and maintenance margin rates for Buy and Sell orders)
double initial_margin_rate_buy=0;
double maintenance_margin_rate_buy=0;
double initial_margin_rate_sell=0;
double maintenance_margin_rate_sell=0;

if(!GetSymbolMarginRate(CUSTOM_SYMBOL_ORIGIN, ORDER_TYPE_BUY, initial_margin_rate_buy, maintenan


return;
if(!GetSymbolMarginRate(CUSTOM_SYMBOL_ORIGIN, ORDER_TYPE_SELL,initial_margin_rate_sell,maintenan
return;

PrintFormat("The '%s' symbol from which the custom '%s' was created:\n"+
" Buy order initial margin rate: %f\n Buy order maintenance margin rate: %f\n"+
" Sell order initial margin rate: %f\n Sell order maintenance margin rate: %f",
CUSTOM_SYMBOL_ORIGIN, CUSTOM_SYMBOL_NAME,
initial_margin_rate_buy, maintenance_margin_rate_buy, initial_margin_rate_sell, main

//--- set other values for the custom symbol properties


ResetLastError();
bool res=true;
res &=CustomSymbolSetMarginRate(CUSTOM_SYMBOL_NAME, ORDER_TYPE_BUY, INITIAL_MARGIN_RATE, MAINTEN
res &=CustomSymbolSetMarginRate(CUSTOM_SYMBOL_NAME, ORDER_TYPE_SELL,INITIAL_MARGIN_RATE, MAINTEN

//--- if there was an error when setting any of the properties, display an appropriate message in t
if(!res)
Print("CustomSymbolSetMarginRate() failed. Error ", GetLastError());

//--- get and print in the journal the modified custom symbol properties
//--- (initial and maintenance margin rates for Buy and Sell orders)
if(!GetSymbolMarginRate(CUSTOM_SYMBOL_NAME, ORDER_TYPE_BUY, initial_margin_rate_buy, maintenance
return;
if(!GetSymbolMarginRate(CUSTOM_SYMBOL_NAME, ORDER_TYPE_SELL,initial_margin_rate_sell,maintenance
return;

© 2000-2025, MetaQuotes Ltd.


2005 Custom Symbols

PrintFormat("Custom symbol '%s' based on '%s':\n"+


" Buy order initial margin rate: %f\n Buy order maintenance margin rate: %f\n"+
" Sell order initial margin rate: %f\n Sell order maintenance margin rate: %f",
CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_ORIGIN,
initial_margin_rate_buy, maintenance_margin_rate_buy, initial_margin_rate_sell, main

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S

//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{
Sleep(16);
//--- when pressing Del, delete the created custom symbol
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
The 'EURUSD' symbol from which the custom 'EURUSD.C' was created:
Buy order initial margin rate: 1.000000
Buy order maintenance margin rate: 0.000000
Sell order initial margin rate: 1.000000
Sell order maintenance margin rate: 0.000000
Custom symbol 'EURUSD.C' based on 'EURUSD':
Buy order initial margin rate: 1.500000
Buy order maintenance margin rate: 1.500000
Sell order initial margin rate: 1.500000
Sell order maintenance margin rate: 1.500000
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;

© 2000-2025, MetaQuotes Ltd.


2006 Custom Symbols

if(!CustomSymbolCreate(symbol_name, symbol_path, origin))


{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}
//+------------------------------------------------------------------+
//| Return margin ratios |
//+------------------------------------------------------------------+
bool GetSymbolMarginRate(const string symbol, const ENUM_ORDER_TYPE order_type, double &initial_mar
{
ResetLastError();
if(!SymbolInfoMarginRate(symbol, order_type, initial_margin_rate, maintenance_margin_rate))
{
PrintFormat("%s: SymbolInfoMarginRate(%s, %s) failed. Error %d",__FUNCTION__, symbol, EnumToS
return false;
}
return true;
}

See also

© 2000-2025, MetaQuotes Ltd.


2007 Custom Symbols

S ymbolInfoMarginR ate

© 2000-2025, MetaQuotes Ltd.


2008 Custom Symbols

CustomSymbolSetSessionQuote
S ets the start and end time of the specified quotation session for the specified symbol and week day.
bool CustomSymbolSetSessionQuote(
const string symbol_name, // symbol name
ENUM_DAY_OF_WEEK day_of_week, // week day
uint session_index, // session index
datetime from, // session start time
datetime to // session end time
);

Parameters
symbol_name
[in] Custom symbol name.
ENUM_DAY_OF_WEEK
[in] W eek day, value from the ENUM _DAY_OF_WEEK enumeration.
uint
[in] Index of the session, for which start and end times are to be set. S ession indexing starts
from 0.
from
[in] S ession start time in seconds from 00:00, data value in the variable is ignored.
to
[in] S ession end time in seconds from 00:00, data value in the variable is ignored.

Return Value

true – success, otherwise – false. To get information about the error, call the GetLastError()
function.
Note

If the session with the specified session_index already exists, the function simply edits the
beginning and end of the session.
If zero start and end parameters have been passed for the session (from=0 and to=0), the
appropriate session with the session_index is deleted, while the session indexing is shifted
downwards.
S essions can be added only sequentially. In other words, you can add session_index=1 only if the
session with the index 0 already exists. If this rule is broken, a new session is not created, while the
function itself returns 'false'.

Example:

//+------------------------------------------------------------------+
//| CustomSymbolSetSessionQuote.mq5 |

© 2000-2025, MetaQuotes Ltd.


2009 Custom Symbols

//| Copyright 2024, MetaQuotes Ltd. |


//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be

#define SESSION_0_FROM D'1970.01.01 00:15:00' // session 0 start time


#define SESSION_0_TO D'1970.01.01 11:59:00' // session 0 end time
#define SESSION_1_FROM D'1970.01.01 12:15:00' // session 1 start time
#define SESSION_1_TO D'1970.01.01 23:59:00' // session 1 end time

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- print the header with the base symbol and session index and
//--- in a loop by day of the week from Mon to Fri, print the start and end times of each quote ses
for(int session=0; session<2; session++)
{
PrintFormat("Quote session %d of '%s' symbol from which the custom '%s' was created", session
for(int day_of_week=MONDAY; day_of_week<SATURDAY; day_of_week++)
SymbolInfoSessionQuotePrint(CUSTOM_SYMBOL_ORIGIN, (ENUM_DAY_OF_WEEK)day_of_week, session);
}

//--- in a loop by two sessions


bool res=true;
for(int session=0; session<2; session++)
{
datetime from = SESSION_0_FROM;
datetime to = SESSION_0_TO;
if(session>0)
{
from = SESSION_1_FROM;
to = SESSION_1_TO;
}
//--- set the quote sessions time for a custom symbol of each day of the week

© 2000-2025, MetaQuotes Ltd.


2010 Custom Symbols

ResetLastError();
for(int day_of_week=MONDAY; day_of_week<SATURDAY; day_of_week++)
res &=CustomSymbolSetSessionQuote(CUSTOM_SYMBOL_NAME, (ENUM_DAY_OF_WEEK)day_of_week, sessi
}

//--- if there was an error when setting any of the sessions, display an appropriate message in the
if(!res)
Print("CustomSymbolSetSessionQuote() failed. Error ", GetLastError());

//--- print the header with the custom symbol and session index and
//--- in a loop by day of the week from Mon to Fri, print the start and end times of each quote ses
for(int session=0; session<2; session++)
{
PrintFormat("Quote session %d of custom symbol '%s' based on '%s'", session, CUSTOM_SYMBOL_NA
for(int day_of_week=MONDAY; day_of_week<SATURDAY; day_of_week++)
SymbolInfoSessionQuotePrint(CUSTOM_SYMBOL_NAME, (ENUM_DAY_OF_WEEK)day_of_week, session);
}

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S
//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{
Sleep(16);
//--- when pressing Del, delete the created custom symbol
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
Quote session 0 of 'EURUSD' symbol from which the custom 'EURUSD.C' was created
- Monday 00:15 - 23:55
- Tuesday 00:15 - 23:55
- Wednesday 00:15 - 23:55
- Thursday 00:15 - 23:55
- Friday 00:15 - 23:55
Quote session 1 of 'EURUSD' symbol from which the custom 'EURUSD.C' was created
- Monday Session not set
- Tuesday Session not set
- Wednesday Session not set
- Thursday Session not set
- Friday Session not set
Quote session 0 of custom symbol 'EURUSD.C' based on 'EURUSD'

© 2000-2025, MetaQuotes Ltd.


2011 Custom Symbols

- Monday 00:15 - 11:59


- Tuesday 00:15 - 11:59
- Wednesday 00:15 - 11:59
- Thursday 00:15 - 11:59
- Friday 00:15 - 11:59
Quote session 1 of custom symbol 'EURUSD.C' based on 'EURUSD'
- Monday 12:15 - 23:59
- Tuesday 12:15 - 23:59
- Wednesday 12:15 - 23:59
- Thursday 12:15 - 23:59
- Friday 12:15 - 23:59
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))

© 2000-2025, MetaQuotes Ltd.


2012 Custom Symbols

{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}
//+------------------------------------------------------------------+
//| Send the start and end times of the specified quote session |
//| for the specified symbol and day of the week to the journal |
//+------------------------------------------------------------------+
void SymbolInfoSessionQuotePrint(const string symbol, const ENUM_DAY_OF_WEEK day_of_week, const uin
{
//--- declare variables to record the beginning and end of the quote session
datetime date_from; // session start time
datetime date_to; // session end time

//--- create the week day name from the enumeration constant
string week_day=EnumToString(day_of_week);
if(week_day.Lower())
week_day.SetChar(0, ushort(week_day.GetChar(0)-32));

//--- get data from the quotation session by symbol and day of the week
if(!SymbolInfoSessionQuote(symbol, day_of_week, session_index, date_from, date_to))
{
int err=GetLastError();
string message=(err==4307 ? StringFormat("- %-10s Session not set", week_day) :
StringFormat("SymbolInfoSessionQuote(%s, %s, session %d) failed. Error %d", s
Print(message);
return;
}

//--- send data for the specified quote session to the journal
PrintFormat("- %-10s %s - %s", week_day, TimeToString(date_from, TIME_MINUTES), TimeToString(dat
}

See also
S ymbolInfoS essionQuote, S ymbol info, TimeToS truct, Date structure

© 2000-2025, MetaQuotes Ltd.


2013 Custom Symbols

CustomSymbolSetSessionTrade
S ets the start and end time of the specified trading session for the specified symbol and week day.
bool CustomSymbolSetSessionTrade(
const string symbol_name, // symbol name
ENUM_DAY_OF_WEEK day_of_week, // week day
uint session_index, // session index
datetime from, // session start time
datetime to // session end time
);

Parameters
symbol_name
[in] Custom symbol name.
ENUM_DAY_OF_WEEK
[in] W eek day, value from the ENUM _DAY_OF_WEEK enumeration.
uint
[in] Index of the session, for which start and end times are to be set. S ession indexing starts
from 0.
from
[in] S ession start time in seconds from 00:00, data value in the variable is ignored.
to
[in] S ession end time in seconds from 00:00, data value in the variable is ignored.

Return Value

true – success, otherwise – false. To get information about the error, call the GetLastError()
function.
Note

If the session with the specified session_index already exists, the function simply edits the
beginning and end of the session.
If zero start and end parameters have been passed for the session (from=0 and to=0), the
appropriate session with the session_index is deleted, while the session indexing is shifted
downwards.
S essions can be added only sequentially. In other words, you can add session_index=1 only if the
session with the index 0 already exists. If this rule is broken, a new session is not created, while the
function itself returns 'false'.

Example:

//+------------------------------------------------------------------+
//| CustomSymbolSetSessionTrade.mq5 |

© 2000-2025, MetaQuotes Ltd.


2014 Custom Symbols

//| Copyright 2024, MetaQuotes Ltd. |


//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be

#define SESSION_0_FROM D'1970.01.01 00:15:00' // session 0 start time


#define SESSION_0_TO D'1970.01.01 11:59:00' // session 0 end time
#define SESSION_1_FROM D'1970.01.01 12:15:00' // session 1 start time
#define SESSION_1_TO D'1970.01.01 23:59:00' // session 1 end time

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- print the header with the base symbol and session index and
//--- in a loop by day of the week from Mon to Fri, print the start and end times of each trading s
for(int session=0; session<2; session++)
{
PrintFormat("Trade session %d of the '%s' symbol from which the custom '%s' was created", ses
for(int day_of_week=MONDAY; day_of_week<SATURDAY; day_of_week++)
SymbolInfoSessionQuotePrint(CUSTOM_SYMBOL_ORIGIN, (ENUM_DAY_OF_WEEK)day_of_week, session);
}

//--- in a loop by two sessions


bool res=true;
for(int session=0; session<2; session++)
{
datetime from = SESSION_0_FROM;
datetime to = SESSION_0_TO;
if(session>0)
{
from = SESSION_1_FROM;
to = SESSION_1_TO;
}
//--- set the quote sessions time for a custom symbol of each day of the week

© 2000-2025, MetaQuotes Ltd.


2015 Custom Symbols

ResetLastError();
for(int day_of_week=MONDAY; day_of_week<SATURDAY; day_of_week++)
res &=CustomSymbolSetSessionQuote(CUSTOM_SYMBOL_NAME, (ENUM_DAY_OF_WEEK)day_of_week, sessi
}

//--- if there was an error when setting any of the sessions, display an appropriate message in the
if(!res)
Print("CustomSymbolSetSessionTrade() failed. Error ", GetLastError());

//--- print the header with the custom symbol and session index and
//--- in a loop by day of the week from Mon to Fri, print the start and end times of each trading s
for(int session=0; session<2; session++)
{
PrintFormat("Trade session %d of a custom symbol '%s' based on '%s'", session, CUSTOM_SYMBOL_
for(int day_of_week=MONDAY; day_of_week<SATURDAY; day_of_week++)
SymbolInfoSessionQuotePrint(CUSTOM_SYMBOL_NAME, (ENUM_DAY_OF_WEEK)day_of_week, session);
}

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S
//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{
Sleep(16);
//--- when pressing Del, delete the created custom symbol
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
Trade session 0 of the 'EURUSD' symbol from which the custom 'EURUSD.C' was created
- Monday 00:15 - 23:55
- Tuesday 00:15 - 23:55
- Wednesday 00:15 - 23:55
- Thursday 00:15 - 23:55
- Friday 00:15 - 23:55
Trade session 1 of the 'EURUSD' symbol from which the custom 'EURUSD.C' was created
- Monday Session not set
- Tuesday Session not set
- Wednesday Session not set
- Thursday Session not set
- Friday Session not set
Trade session 0 of a custom symbol 'EURUSD.C' based on 'EURUSD'

© 2000-2025, MetaQuotes Ltd.


2016 Custom Symbols

- Monday 00:15 - 11:59


- Tuesday 00:15 - 11:59
- Wednesday 00:15 - 11:59
- Thursday 00:15 - 11:59
- Friday 00:15 - 11:59
Trade session 1 of a custom symbol 'EURUSD.C' based on 'EURUSD'
- Monday 12:15 - 23:59
- Tuesday 12:15 - 23:59
- Wednesday 12:15 - 23:59
- Thursday 12:15 - 23:59
- Friday 12:15 - 23:59
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))

© 2000-2025, MetaQuotes Ltd.


2017 Custom Symbols

{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}
//+------------------------------------------------------------------+
//| Send the start and end times of the specified quote session |
//| for the specified symbol and day of the week to the journal |
//+------------------------------------------------------------------+
void SymbolInfoSessionTradePrint(const string symbol, const ENUM_DAY_OF_WEEK day_of_week, const uin
{
//--- declare variables to record the beginning and end of the quote session
datetime date_from; // session start time
datetime date_to; // session end time

//--- create the week day name from the enumeration constant
string week_day=EnumToString(day_of_week);
if(week_day.Lower())
week_day.SetChar(0, ushort(week_day.GetChar(0)-32));

//--- get data from the quotation session by symbol and day of the week
if(!SymbolInfoSessionTrade(symbol, day_of_week, session_index, date_from, date_to))
{
int err=GetLastError();
string message=(err==4307 ? StringFormat("- %-10s Session not set", week_day) :
StringFormat("SymbolInfoSessionTrade(%s, %s, session %d) failed. Error %d", s
Print(message);
return;
}

//--- send data for the specified trading session to the journal
PrintFormat("- %-10s %s - %s", week_day, TimeToString(date_from, TIME_MINUTES), TimeToString(dat
}

See also
S ymbolInfoS essionTrade, S ymbol info, TimeToS truct, Date structure

© 2000-2025, MetaQuotes Ltd.


2018 Custom Symbols

CustomRatesDelete
Deletes all bars from the price history of the custom symbol in the specified time interval.
int CustomRatesDelete(
const string symbol, // symbol name
datetime from, // start date
datetime to // end date
);

Parameters
symbol
[in] Custom symbol name.
from
[in] Time of the first bar in the price history within the specified range to be removed.
to
[in] Time of the last bar in the price history within the specified range to be removed.

Return Value

Number of deleted bars or -1 in case of an error.

Example:

//+------------------------------------------------------------------+
//| CustomRatesDelete.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based

#define DATARATES_COUNT 4 // number of bars sent to the journal

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

© 2000-2025, MetaQuotes Ltd.


2019 Custom Symbols

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get the number of standard symbol bars


int bars=Bars(CUSTOM_SYMBOL_ORIGIN, PERIOD_M1);

//--- get the data of all bars of the standard symbol minute timeframe into the MqlRates array
MqlRates rates[]={};
ResetLastError();
if(CopyRates(CUSTOM_SYMBOL_ORIGIN, PERIOD_M1, 0, bars, rates)!=bars)
{
PrintFormat("CopyRates(%s, PERIOD_M1, 0, %d) failed. Error %d", CUSTOM_SYMBOL_ORIGIN, bars, G
return;
}

//--- set the copied data to the minute history of the custom symbol
ResetLastError();
if(CustomRatesUpdate(CUSTOM_SYMBOL_NAME, rates)<0)
{
PrintFormat("CustomRatesUpdate(%s) failed. Error %d", CUSTOM_SYMBOL_NAME, GetLastError());
return;
}

//--- after updating the historical data, get the number of custom symbol bars
bars=Bars(CUSTOM_SYMBOL_NAME, PERIOD_M1);

//--- get the data of all bars of the custom symbol minute timeframe into the MqlRates array
ResetLastError();
if(CopyRates(CUSTOM_SYMBOL_NAME, PERIOD_M1, 0, bars, rates)!=bars)
{
PrintFormat("CopyRates(%s, PERIOD_M1, 0, %d) failed. Error %d", CUSTOM_SYMBOL_NAME, bars, Get
return;
}

//--- print the last DATARATES_COUNT bars of the custom symbol minute history in the journal
int digits=(int)SymbolInfoInteger(CUSTOM_SYMBOL_NAME, SYMBOL_DIGITS);
PrintFormat("Last %d bars of the custom symbol's minute history:", DATARATES_COUNT);
ArrayPrint(rates, digits, NULL, bars-DATARATES_COUNT, DATARATES_COUNT);

//--- delete the two penultimate data bars in the custom symbol minute history
datetime time_from= rates[bars-3].time;
datetime time_to = rates[bars-2].time;
ResetLastError();
int deleted=CustomRatesDelete(CUSTOM_SYMBOL_NAME, time_from, time_to);
if(deleted<0)
{
PrintFormat("CustomRatesDelete(%s) failed. Error %d", CUSTOM_SYMBOL_NAME, GetLastError());
return;

© 2000-2025, MetaQuotes Ltd.


2020 Custom Symbols

//--- after deleting two bars of historical data, get the number of custom symbol bars again
bars=Bars(CUSTOM_SYMBOL_NAME, PERIOD_M1);

//--- get the data of all remaining bars of the custom symbol minute timeframe again
ResetLastError();
if(CopyRates(CUSTOM_SYMBOL_NAME, PERIOD_M1, 0, bars, rates)!=bars)
{
PrintFormat("CopyRates(%s, PERIOD_M1, 0, %d) failed. Error %d", CUSTOM_SYMBOL_NAME, bars, Get
return;
}

//--- print the last DATARATES_COUNT bars of the updated custom symbol minute history in the journa
PrintFormat("\nLast %d bars after applying CustomRatesDelete() with %d deleted bars:", DATARATES
ArrayPrint(rates, digits, NULL, bars-DATARATES_COUNT, DATARATES_COUNT);

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S
//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{
Sleep(16);
//--- when pressing Del, delete the created custom symbol and its data
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
//--- delete bar data
int deleted=CustomRatesDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history bars of the custom symbol '%s' were successfully deleted", dele

//--- delete tick data


deleted=CustomTicksDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history ticks of the custom symbol '%s' were successfully deleted", del

//--- delete symbol


if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
Last 4 bars of the custom symbol's minute history:
[time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume]
[0] 2024.06.18 20:53:00 1.07341 1.07347 1.07336 1.07343 38 0 0

© 2000-2025, MetaQuotes Ltd.


2021 Custom Symbols

[1] 2024.06.18 20:54:00 1.07344 1.07354 1.07344 1.07353 21 0 0


[2] 2024.06.18 20:55:00 1.07353 1.07362 1.07351 1.07356 32 0 0
[3] 2024.06.18 20:56:00 1.07356 1.07358 1.07352 1.07354 24 0 0

Last 4 bars after applying CustomRatesDelete() with 2 deleted bars:


[time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume]
[0] 2024.06.18 20:51:00 1.07357 1.07358 1.07347 1.07349 25 0 0
[1] 2024.06.18 20:52:00 1.07349 1.07350 1.07336 1.07341 31 0 0
[2] 2024.06.18 20:53:00 1.07341 1.07347 1.07336 1.07343 38 0 0
[3] 2024.06.18 20:56:00 1.07356 1.07358 1.07352 1.07354 24 0 0
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{

© 2000-2025, MetaQuotes Ltd.


2022 Custom Symbols

PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());


return(false);
}
//--- successful
return(true);
}

See also
CustomRates Replace, CustomRates Update, CopyRates

© 2000-2025, MetaQuotes Ltd.


2023 Custom Symbols

CustomRatesReplace
Fullyreplaces the price history of the custom symbol within the specified time interval with the data
from the M qlRates type array.
int CustomRatesReplace(
const string symbol, // symbol name
datetime from, // start date
datetime to, // end date
const MqlRates& rates[], // array for the data to be applied to a custom symbol
uint count=WHOLE_ARRAY // number of the rates[] array elements to be used
);

Parameters
symbol
[in] Custom symbol name.
from
[in] Time of the first bar in the price history within the specified range to be updated.
to
[in] Time of the last bar in the price history within the specified range to be updated.
rates[]
[in] Array of the M qlRates type history data for M 1.
count=WHOLE_ARRAY
[in] Number of the rates[] array elements to be used for replacement. WHOLE_ARRAY means that
all rates[] array elements should be used for replacement.

Return Value

Number of updated bars or -1 in case of an error.


Note

If the bar from the rates[] array goes beyond the specified range, it is ignored. If such a bar is
already present in the price history and enters the given range, it is replaced. All other bars in the
current price history outside the specified range remain unchanged. The rates[] array data should be
correct regarding OHLC prices, while the bars opening time should correspond to the M 1 timeframe.

Example:

//+------------------------------------------------------------------+
//| CustomRatesReplace.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"

© 2000-2025, MetaQuotes Ltd.


2024 Custom Symbols

#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based

#define DATARATES_COUNT 4 // number of bars sent to the journal

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get the number of standard symbol bars


int bars=Bars(CUSTOM_SYMBOL_ORIGIN, PERIOD_M1);

//--- get the data of all bars of the standard symbol minute timeframe into the MqlRates array
MqlRates rates[]={};
ResetLastError();
if(CopyRates(CUSTOM_SYMBOL_ORIGIN, PERIOD_M1, 0, bars, rates)!=bars)
{
PrintFormat("CopyRates(%s, PERIOD_M1, 0, %d) failed. Error %d", CUSTOM_SYMBOL_ORIGIN, bars, G
return;
}

//--- set the copied data to the minute history of the custom symbol
ResetLastError();
if(CustomRatesUpdate(CUSTOM_SYMBOL_NAME, rates)<0)
{
PrintFormat("CustomRatesUpdate(%s) failed. Error %d", CUSTOM_SYMBOL_NAME, GetLastError());
return;
}

//--- after updating the historical data, get the number of custom symbol bars
bars=Bars(CUSTOM_SYMBOL_NAME, PERIOD_M1);

//--- get the data of all bars of the custom symbol minute timeframe into the MqlRates array
ResetLastError();
if(CopyRates(CUSTOM_SYMBOL_NAME, PERIOD_M1, 0, bars, rates)!=bars)
{
PrintFormat("CopyRates(%s, PERIOD_M1, 0, %d) failed. Error %d", CUSTOM_SYMBOL_NAME, bars, Get
return;

© 2000-2025, MetaQuotes Ltd.


2025 Custom Symbols

//--- print the last DATARATES_COUNT bars of the custom symbol minute history in the journal
int digits=(int)SymbolInfoInteger(CUSTOM_SYMBOL_NAME, SYMBOL_DIGITS);
PrintFormat("Last %d bars of the custom symbol's minute history:", DATARATES_COUNT);
ArrayPrint(rates, digits, NULL, bars-DATARATES_COUNT, DATARATES_COUNT);

//--- change the two penultimate data bars in the custom symbol minute history
datetime time_from= rates[bars-3].time;
datetime time_to = rates[bars-2].time;

//--- make all prices of the two penultimate bars equal to the open prices of these bars in the 'ra
rates[bars-3].high=rates[bars-3].open;
rates[bars-3].low=rates[bars-3].open;
rates[bars-3].close=rates[bars-3].open;

rates[bars-2].high=rates[bars-2].open;
rates[bars-2].low=rates[bars-2].open;
rates[bars-2].close=rates[bars-2].open;

//--- replace existing bars with data from the modified 'rates' array
ResetLastError();
int replaced=CustomRatesUpdate(CUSTOM_SYMBOL_NAME, rates);
if(replaced<0)
{
PrintFormat("CustomRatesUpdate(%s) failed. Error %d", CUSTOM_SYMBOL_NAME, GetLastError());
return;
}

//--- after changing two bars of historical data, get the number of custom symbol bars again
bars=Bars(CUSTOM_SYMBOL_NAME, PERIOD_M1);

//--- get the data of all bars of the custom symbol minute timeframe again
ResetLastError();
if(CopyRates(CUSTOM_SYMBOL_NAME, PERIOD_M1, 0, bars, rates)!=bars)
{
PrintFormat("CopyRates(%s, PERIOD_M1, 0, %d) failed. Error %d", CUSTOM_SYMBOL_NAME, bars, Get
return;
}

//--- print the last DATARATES_COUNT bars of the updated custom symbol minute history in the journa
PrintFormat("\nLast %d bars after applying CustomRatesUpdate() with %d replaced bars:", DATARATE
ArrayPrint(rates, digits, NULL, bars-DATARATES_COUNT, DATARATES_COUNT);

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S
//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{

© 2000-2025, MetaQuotes Ltd.


2026 Custom Symbols

Sleep(16);
//--- when pressing Del, delete the created custom symbol and its data
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
//--- delete bar data
int deleted=CustomRatesDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history bars of the custom symbol '%s' were successfully deleted", dele

//--- delete tick data


deleted=CustomTicksDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history ticks of the custom symbol '%s' were successfully deleted", del

//--- delete symbol


if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
Last 4 bars of the custom symbol's minute history:
[time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume]
[0] 2024.07.29 13:37:00 1.08394 1.08396 1.08388 1.08390 16 1 0
[1] 2024.07.29 13:38:00 1.08389 1.08400 1.08389 1.08398 35 1 0
[2] 2024.07.29 13:39:00 1.08398 1.08410 1.08394 1.08410 29 1 0
[3] 2024.07.29 13:40:00 1.08409 1.08414 1.08408 1.08414 14 1 0

Last 4 bars after applying CustomRatesUpdate() with 250820 replaced bars:


[time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume]
[0] 2024.07.29 13:37:00 1.08394 1.08396 1.08388 1.08390 16 1 0
[1] 2024.07.29 13:38:00 1.08389 1.08389 1.08389 1.08389 35 1 0
[2] 2024.07.29 13:39:00 1.08398 1.08398 1.08398 1.08398 29 1 0
[3] 2024.07.29 13:40:00 1.08409 1.08414 1.08408 1.08414 14 1 0
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


2027 Custom Symbols

int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}

See also
CustomRates Delete, CustomRates Update, CopyRates

© 2000-2025, MetaQuotes Ltd.


2028 Custom Symbols

CustomRatesUpdate
Adds missing bars to the custom symbol history and replaces existing data with the ones from the
M qlRates type array.
int CustomRatesUpdate(
const string symbol, // custom symbol name
const MqlRates& rates[], // array for the data to be applied to a custom symbol
uint count=WHOLE_ARRAY // number of the rates[] array elements to be used
);

Parameters
symbol
[in] Custom symbol name.
rates[]
[in] Array of the M qlRates type history data for M 1.
count=WHOLE_ARRAY
[in] Number of the rates[] array elements to be used for update. WH OL E_ARRAY means that all
rates[] array elements should be used.

Return Value

Number of updated bars or -1 in case of an error.


Note

If there is no bar from the rates[] array in the current custom symbol history, it is added. If such a
bar already exists, it is replaced. All other bars in the current price history remain unchanged. The
rates[] array data should be correct regarding O H LC prices, while the bars opening time should

correspond to the M 1 timeframe.

Example:

//+------------------------------------------------------------------+
//| CustomRatesUpdate.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based

#define DATARATES_COUNT 4 // number of bars sent to the journal

© 2000-2025, MetaQuotes Ltd.


2029 Custom Symbols

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get and print in the journal the number of standard symbol bars
int bars_origin=Bars(CUSTOM_SYMBOL_ORIGIN, PERIOD_M1);
PrintFormat("The symbol '%s' from which the custom '%s' was created has %d bars of minute histor

//--- get and print in the journal the number of custom symbol bars
int bars_custom=Bars(CUSTOM_SYMBOL_NAME, PERIOD_M1);
PrintFormat("Custom symbol '%s' created from symbol '%s' has %d bars of minute history", CUSTOM_

//--- get the data of all bars of the standard symbol minute timeframe into the MqlRates array
MqlRates rates[]={};
ResetLastError();
if(CopyRates(CUSTOM_SYMBOL_ORIGIN, PERIOD_M1, 0, bars_origin, rates)!=bars_origin)
{
PrintFormat("CopyRates(%s, PERIOD_M1, 0, %d) failed. Error %d", CUSTOM_SYMBOL_ORIGIN, bars_or
return;
}

//--- set the copied data to the minute history of the custom symbol
ResetLastError();
int updated=CustomRatesUpdate(CUSTOM_SYMBOL_NAME, rates);
if(updated<0)
{
PrintFormat("CustomRatesUpdate(%s) failed. Error %d", CUSTOM_SYMBOL_NAME, GetLastError());
return;
}

//--- get and print in the journal the number of custom symbol bars after adding history
bars_custom=Bars(CUSTOM_SYMBOL_NAME, PERIOD_M1);
PrintFormat("\nAfter CustomRatesUpdate(), the custom symbol '%s' has %d bars of minute history",

//--- get the data of all bars of the custom symbol minute timeframe into the MqlRates array
ResetLastError();
if(CopyRates(CUSTOM_SYMBOL_NAME, PERIOD_M1, 0, bars_custom, rates)!=bars_custom)
{
PrintFormat("CopyRates(%s, PERIOD_M1, 0, %d) failed. Error %d", CUSTOM_SYMBOL_NAME, bars_cust
return;
}

© 2000-2025, MetaQuotes Ltd.


2030 Custom Symbols

//--- print the last four bars of the custom symbol minute history in the journal
int digits=(int)SymbolInfoInteger(CUSTOM_SYMBOL_NAME, SYMBOL_DIGITS);
PrintFormat("Last %d bars of the custom symbol's minute history:", DATARATES_COUNT);
ArrayPrint(rates, digits, NULL, bars_custom-DATARATES_COUNT, DATARATES_COUNT);

//--- replace the data in the MqlRates array with the one calculated using the equation 1.0 / Symbo
for(int i=0; i<bars_custom; i++)
{
rates[i].open =(rates[i].open !=0 ? 1.0 / rates[i].open : rates[i].open);
rates[i].high =(rates[i].high !=0 ? 1.0 / rates[i].high : rates[i].high);
rates[i].low =(rates[i].low !=0 ? 1.0 / rates[i].low : rates[i].low);
rates[i].close =(rates[i].close!=0 ? 1.0 / rates[i].close : rates[i].close);
}

//--- set the modified data to the minute history of the custom symbol
ResetLastError();
updated=CustomRatesUpdate(CUSTOM_SYMBOL_NAME, rates);
if(updated<0)
{
PrintFormat("CustomRatesUpdate(%s) failed. Error %d", CUSTOM_SYMBOL_NAME, GetLastError());
return;
}

//--- get the data of all bars of the custom symbol minute timeframe into the MqlRates array again
ResetLastError();
if(CopyRates(CUSTOM_SYMBOL_NAME, PERIOD_M1, 0, bars_custom, rates)!=bars_custom)
{
PrintFormat("CopyRates(%s, PERIOD_M1, 0, %d) failed. Error %d", CUSTOM_SYMBOL_NAME, bars_cust
return;
}

//--- print the last four bars of the updated custom symbol minute history in the journal
Print("\nLast %d bars after changing the custom symbol calculation formula:", DATARATES_COUNT);
ArrayPrint(rates, digits, NULL, bars_custom-DATARATES_COUNT, DATARATES_COUNT);

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S
//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{
Sleep(16);
//--- when pressing Del, delete the created custom symbol and its data
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
//--- delete bar data
int deleted=CustomRatesDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history bars of the custom symbol '%s' were successfully deleted", dele

© 2000-2025, MetaQuotes Ltd.


2031 Custom Symbols

//--- delete tick data


deleted=CustomTicksDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history ticks of the custom symbol '%s' were successfully deleted", del

//--- delete symbol


if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
The symbol 'EURUSD' from which the custom 'EURUSD.C' was created has 250488 bars of minute histo
Custom symbol 'EURUSD.C' created from symbol 'EURUSD' has 0 bars of minute history

After CustomRatesUpdate(), the custom symbol 'EURUSD.C' has 250488 bars of minute history
Last 4 bars of the custom symbol's minute history:
[time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume]
[0] 2024.06.18 11:14:00 1.07235 1.07239 1.07232 1.07239 24 0 0
[1] 2024.06.18 11:15:00 1.07238 1.07239 1.07232 1.07235 44 0 0
[2] 2024.06.18 11:16:00 1.07234 1.07238 1.07227 1.07234 37 0 0
[3] 2024.06.18 11:17:00 1.07234 1.07234 1.07217 1.07225 41 0 0

Last 4 bars after changing the custom symbol calculation formula:


[time] [open] [high] [low] [close] [tick_volume] [spread] [real_volume]
[0] 2024.06.18 11:14:00 0.93253 0.93250 0.93256 0.93250 24 0 0
[1] 2024.06.18 11:15:00 0.93251 0.93250 0.93256 0.93253 44 0 0
[2] 2024.06.18 11:16:00 0.93254 0.93251 0.93260 0.93254 37 0 0
[3] 2024.06.18 11:17:00 0.93254 0.93254 0.93269 0.93262 41 0 0
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();

© 2000-2025, MetaQuotes Ltd.


2032 Custom Symbols

if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}

See also
CustomRates Replace, CustomRates Delete, CopyRates

© 2000-2025, MetaQuotes Ltd.


2033 Custom Symbols

CustomTicksAdd
Adds data from an array of the M qlTick type to the price history of a custom symbol. The custom
symbol must be selected in the Market W atch window.
int CustomTicksAdd(
const string symbol, // Symbol name
const MqlTick& ticks[], // The array with tick data that should be applied to the c
uint count=WHOLE_ARRAY // number of the ticks[] array elements to be used
);

Parameters
symbol
[in] The name of the custom symbol.
ticks[]
[in] An array of tick data of the M qlTick type arranged in order of time from earlier data to more
recent ones, i.e. ticks [k].time_msc <= ticks [n].time_msc, if k<n.
count=WHOLE_ARRAY
[in] Number of the ticks[] array elements to be used for adding. WH OL E_ARRAY means that all
ticks[] array elements should be used.

Return Value

The number of added ticks or -1 in case of an error.


Further Note

The CustomTicks Add function only works for custom symbols opened in the Market W atch window. If
the symbol is not selected in Market W atch, then you should add ticks using CustomTicks Replace.
The CustomTicks Add function allows transmitting ticks as if they are delivered from the broker's
server. Data are sent to the Market W atch window instead of being written directly to the tick
database. The terminal then saves ticks from the Market W atch to a database. If the amount of
data transmitted during one function call is large, the behavior of the function changes in order to
reduce resource usage. If more than 256 ticks are passed, data is divided into two parts. The first,
i.e. the larger part is written directly to the tick database (as it is done in CustomTicks Replace).
The second part containing 128 ticks is passed to the Market W atch window, from which the
terminal saves the ticks to a database.
The M qlTick structure has two fields with the time value: time (the tick time in seconds) and
time_msc (the tick time in milliseconds), which are counted from January 1, 1970. These fields in
the added ticks are processed in the following order:
1. If ticks [k].time_msc!=0, we use it to fill the ticks [k].time field, i.e.
ticks [k].time=ticks [k].time_msc/1000 (integer division) is set for the tick
2. If tick s [k].time_msc==0 and tick s [k].time!=0, time in milliseconds is obtained by multiplying by
1000, i.e. tick s [k].time_msc=tick s [k].time*1000
3. If tick s [k].time_msc==0 and tick s [k].time==0, the current trade server time up to a millisecond
as of the moment of CustomTicks Add call is written to these fields.

© 2000-2025, MetaQuotes Ltd.


2034 Custom Symbols

If the value of ticks [k].bid, ticks [k].as k, ticks [k].last or ticks [k].volume is greater than zero, a
combination of appropriate flags is written to the ticks [k].flags field:
· TICK_FL AG_BI D – the tick has changed the bid price
· TICK_FL AG_ASK – the tick has changed the as k price
· TICK_FL AG_L AS T – the tick has changed the last deal price
· TICK_FL AG_VOL UM E – the tick has changed the volume
If the value of a field is less than or equal to zero, the corresponding flag is not written to the
ticks [k].flags field.

Flags TICK_FLAG_BUY and TICK_FLAG_SELL are not added to the history of a custom symbol.

Example:

//+------------------------------------------------------------------+
//| CustomTicksAdd.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based

#define DATATICKS_TO_COPY UINT_MAX // number of ticks copied


#define DATATICKS_TO_PRINT 20 // number of ticks sent to the journal

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get the standard symbol tick data to the MqlTick array
MqlTick array[]={};
if(!GetTicksToArray(CUSTOM_SYMBOL_ORIGIN, DATATICKS_TO_COPY, array))
return;

//--- print the time of the first and last received ticks of the standard symbol

© 2000-2025, MetaQuotes Ltd.


2035 Custom Symbols

int total=(int)array.Size();
PrintFormat("First tick time: %s.%03u, Last tick time: %s.%03u",
TimeToString(array[0].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[0].time_msc%
TimeToString(array[total-1].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[total-

//--- print DATATICKS_TO_PRINT last ticks of the standard symbol in the journal
PrintFormat("\nThe last %d ticks for the standard symbol '%s':", DATATICKS_TO_PRINT, CUSTOM_SYMB
for(int i=total-DATATICKS_TO_PRINT; i<total; i++)
{
if(i<0)
continue;
PrintFormat(" %dth Tick: %s", i, GetTickDescription(array[i]));
}

//--- add a custom symbol to the MarketWatch window


ResetLastError();
if(!SymbolSelect(CUSTOM_SYMBOL_NAME, true))
{
Print("SymbolSelect() failed. Error ", GetLastError());
return;
}

//--- add the tick array data to the custom symbol price history
Print("...");
uint start=GetTickCount();
PrintFormat("Start of adding %u ticks to the history of the custom symbol '%s'", array.Size(), C
int added=CustomTicksAdd(CUSTOM_SYMBOL_NAME, array);
PrintFormat("Added %u ticks to the history of the custom symbol '%s' in %u ms", added, CUSTOM_SY

//--- get the custom symbol tick data to the MqlTick array
Print("...");
if(!GetTicksToArray(CUSTOM_SYMBOL_NAME, array.Size(), array))
return;

//--- print the time of the first and last received ticks of the custom symbol
total=(int)array.Size();
PrintFormat("First tick time: %s.%03u, Last tick time: %s.%03u",
TimeToString(array[0].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[0].time_msc%
TimeToString(array[total-1].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[total-

//--- print DATATICKS_TO_PRINT last ticks of the custom symbol in the journal
PrintFormat("\nThe last %d ticks for the custom symbol '%s':", DATATICKS_TO_PRINT, CUSTOM_SYMBOL
for(int i=total-DATATICKS_TO_PRINT; i<total; i++)
{
if(i<0)
continue;
PrintFormat(" %dth Tick: %s", i, GetTickDescription(array[i]));
}

© 2000-2025, MetaQuotes Ltd.


2036 Custom Symbols

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S
//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{
Sleep(16);
//--- when pressing Del, delete the created custom symbol and its data
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
//--- delete bar data
int deleted=CustomRatesDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history bars of the custom symbol '%s' were successfully deleted", dele

//--- delete tick data


deleted=CustomTicksDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history ticks of the custom symbol '%s' were successfully deleted", del

//--- delete symbol


if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
Requested 4294967295 ticks to download tick history for the symbol 'EURUSD'
The tick history for the 'EURUSD' symbol is received in the amount of 351183943 ticks in 56454 m
First tick time: 2011.12.19 00:00:08.000, Last tick time: 2024.06.20 21:18:12.010

The last 20 ticks for the standard symbol 'EURUSD':


351183923th Tick: 2024.06.20 21:17:46.380 Bid=1.07124 (Info tick)
351183924th Tick: 2024.06.20 21:17:47.779 Ask=1.07125 Bid=1.07125 (Info tick)
351183925th Tick: 2024.06.20 21:17:48.584 Ask=1.07124 Bid=1.07124 (Info tick)
351183926th Tick: 2024.06.20 21:17:49.481 Ask=1.07125 (Info tick)
351183927th Tick: 2024.06.20 21:17:49.985 Ask=1.07122 Bid=1.07122 (Info tick)
351183928th Tick: 2024.06.20 21:17:50.482 Ask=1.07124 Bid=1.07124 (Info tick)
351183929th Tick: 2024.06.20 21:17:51.584 Ask=1.07123 Bid=1.07123 (Info tick)
351183930th Tick: 2024.06.20 21:17:52.786 Ask=1.07124 Bid=1.07124 (Info tick)
351183931th Tick: 2024.06.20 21:17:53.487 Ask=1.07125 Bid=1.07125 (Info tick)
351183932th Tick: 2024.06.20 21:17:53.989 Ask=1.07126 Bid=1.07126 (Info tick)
351183933th Tick: 2024.06.20 21:17:55.789 Ask=1.07125 Bid=1.07125 (Info tick)
351183934th Tick: 2024.06.20 21:17:58.495 Ask=1.07126 Bid=1.07126 (Info tick)
351183935th Tick: 2024.06.20 21:18:00.102 Bid=1.07126 (Info tick)
351183936th Tick: 2024.06.20 21:18:00.698 Ask=1.07129 Bid=1.07129 (Info tick)
351183937th Tick: 2024.06.20 21:18:03.699 Bid=1.07129 (Info tick)

© 2000-2025, MetaQuotes Ltd.


2037 Custom Symbols

351183938th Tick: 2024.06.20 21:18:04.699 Ask=1.07128 Bid=1.07128 (Info tick)


351183939th Tick: 2024.06.20 21:18:05.901 Ask=1.07129 Bid=1.07129 (Info tick)
351183940th Tick: 2024.06.20 21:18:07.606 Ask=1.07128 Bid=1.07128 (Info tick)
351183941th Tick: 2024.06.20 21:18:11.512 Ask=1.07127 Bid=1.07127 (Info tick)
351183942th Tick: 2024.06.20 21:18:12.010 Ask=1.07126 Bid=1.07126 (Info tick)
...
Start of adding 351183943 ticks to the history of the custom symbol 'EURUSD.C'
Added 351183943 ticks to the history of the custom symbol 'EURUSD.C' in 269890 ms
...
Requested 351183943 ticks to download tick history for the symbol 'EURUSD.C'
The tick history for the 'EURUSD.C' symbol is received in the amount of 351183943 ticks in 11640
First tick time: 2011.12.19 00:00:08.000, Last tick time: 2024.06.20 21:18:12.010

The last 20 ticks for the custom symbol 'EURUSD.C':


351183923th Tick: 2024.06.20 21:17:46.380 Ask=1.07124 Bid=1.07124 (Info tick)
351183924th Tick: 2024.06.20 21:17:47.779 Ask=1.07125 Bid=1.07125 (Info tick)
351183925th Tick: 2024.06.20 21:17:48.584 Ask=1.07124 Bid=1.07124 (Info tick)
351183926th Tick: 2024.06.20 21:17:49.481 Ask=1.07125 Bid=1.07125 (Info tick)
351183927th Tick: 2024.06.20 21:17:49.985 Ask=1.07122 Bid=1.07122 (Info tick)
351183928th Tick: 2024.06.20 21:17:50.482 Ask=1.07124 Bid=1.07124 (Info tick)
351183929th Tick: 2024.06.20 21:17:51.584 Ask=1.07123 Bid=1.07123 (Info tick)
351183930th Tick: 2024.06.20 21:17:52.786 Ask=1.07124 Bid=1.07124 (Info tick)
351183931th Tick: 2024.06.20 21:17:53.487 Ask=1.07125 Bid=1.07125 (Info tick)
351183932th Tick: 2024.06.20 21:17:53.989 Ask=1.07126 Bid=1.07126 (Info tick)
351183933th Tick: 2024.06.20 21:17:55.789 Ask=1.07125 Bid=1.07125 (Info tick)
351183934th Tick: 2024.06.20 21:17:58.495 Ask=1.07126 Bid=1.07126 (Info tick)
351183935th Tick: 2024.06.20 21:18:00.102 Ask=1.07126 Bid=1.07126 (Info tick)
351183936th Tick: 2024.06.20 21:18:00.698 Ask=1.07129 Bid=1.07129 (Info tick)
351183937th Tick: 2024.06.20 21:18:03.699 Ask=1.07129 Bid=1.07129 (Info tick)
351183938th Tick: 2024.06.20 21:18:04.699 Ask=1.07128 Bid=1.07128 (Info tick)
351183939th Tick: 2024.06.20 21:18:05.901 Ask=1.07129 Bid=1.07129 (Info tick)
351183940th Tick: 2024.06.20 21:18:07.606 Ask=1.07128 Bid=1.07128 (Info tick)
351183941th Tick: 2024.06.20 21:18:11.512 Ask=1.07127 Bid=1.07127 (Info tick)
351183942th Tick: 2024.06.20 21:18:12.010 Ask=1.07126 Bid=1.07126 (Info tick)
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{

© 2000-2025, MetaQuotes Ltd.


2038 Custom Symbols

error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}
//+------------------------------------------------------------------+
//| Get the specified number of ticks in the array |
//+------------------------------------------------------------------+
bool GetTicksToArray(const string symbol, const uint count, MqlTick &array[])
{
//--- notify of the start of loading historical data
PrintFormat("Requested %u ticks to get tick history for the symbol '%s'", count, symbol);

//--- make 3 attempts to receive ticks


int attempts=0;
while(attempts<3)
{
//--- measure the start time before receiving the ticks
uint start=GetTickCount();

//--- request the tick history since 1970.01.01 00:00.001 (parameter from=1 ms)
int received=CopyTicks(symbol, array, COPY_TICKS_ALL, 1, count);
if(received!=-1)
{

© 2000-2025, MetaQuotes Ltd.


2039 Custom Symbols

//--- display information about the number of ticks and spent time
PrintFormat("The tick history for the '%s' symbol is received in the amount of %u ticks in

//--- if the tick history is synchronized, the error code is equal to zero - return 'true'
if(GetLastError()==0)
return(true);

PrintFormat("%s: Ticks are not synchronized yet, %d ticks received for %d ms. Error=%d",
symbol, received, GetTickCount()-start, GetLastError());
}
//--- count attempts
attempts++;
//--- a one-second pause to wait for the end of synchronization of the tick database
Sleep(1000);
}
//--- failed to copy ticks in 3 attempts
return(false);
}
//+------------------------------------------------------------------+
//| return the string description of a tick |
//+------------------------------------------------------------------+
string GetTickDescription(MqlTick &tick)
{
string desc=StringFormat("%s.%03u ", TimeToString(tick.time, TIME_DATE|TIME_MINUTES|TIME_SECONDS

//--- check tick flags


bool buy_tick = ((tick.flags &TICK_FLAG_BUY) == TICK_FLAG_BUY);
bool sell_tick = ((tick.flags &TICK_FLAG_SELL) == TICK_FLAG_SELL);
bool ask_tick = ((tick.flags &TICK_FLAG_ASK) == TICK_FLAG_ASK);
bool bid_tick = ((tick.flags &TICK_FLAG_BID) == TICK_FLAG_BID);
bool last_tick = ((tick.flags &TICK_FLAG_LAST) == TICK_FLAG_LAST);
bool volume_tick= ((tick.flags &TICK_FLAG_VOLUME)== TICK_FLAG_VOLUME);

//--- check the tick for trading flags first (there are none for CustomTicksAdd())
if(buy_tick || sell_tick)
{
//--- form an output for a trading tick
desc += (buy_tick ? StringFormat("Buy Tick: Last=%G Volume=%d ", tick.last, tick.volume) : "
desc += (sell_tick? StringFormat("Sell Tick: Last=%G Volume=%d ",tick.last, tick.volume) : ""
desc += (ask_tick ? StringFormat("Ask=%G ", tick.ask) : "");
desc += (bid_tick ? StringFormat("Bid=%G ", tick.ask) : "");
desc += "(Trade tick)";
}
else
{
//--- form an output for an info tick a bit differently
desc += (ask_tick ? StringFormat("Ask=%G ", tick.ask) : "");
desc += (bid_tick ? StringFormat("Bid=%G ", tick.ask) : "");
desc += (last_tick ? StringFormat("Last=%G ", tick.last) : "");

© 2000-2025, MetaQuotes Ltd.


2040 Custom Symbols

desc += (volume_tick? StringFormat("Volume=%d ",tick.volume): "");


desc += "(Info tick)";
}
//--- return tick description
return(desc);
}

See also
CustomRates Delete, CustomRates Update, CustomTicks Replace, CopyTicks, CopyTicks Range

© 2000-2025, MetaQuotes Ltd.


2041 Custom Symbols

CustomTicksDelete
Deletes all ticks from the price history of the custom symbol in the specified time interval.
int CustomTicksDelete(
const string symbol, // symbol name
long from_msc, // start date
long to_msc // end date
);

Parameters
symbol
[in] Custom symbol name.
from_msc
[in] Time of the first tick in the price history within the specified range to be removed. Time in
milliseconds since 01.01.1970.
to_msc
[in] Time of the last tick in the price history within the specified range to be removed. Time in
milliseconds since 01.01.1970.

Return Value

Number of deleted ticks or -1 in case of an error.

Example:

//+------------------------------------------------------------------+
//| CustomTicksDelete.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based

#define DATATICKS_TO_COPY UINT_MAX // number of ticks copied


#define DATATICKS_TO_DELETE 10 // number of deleted ticks
#define DATATICKS_TO_PRINT 20 // number of ticks sent to the journal

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()

© 2000-2025, MetaQuotes Ltd.


2042 Custom Symbols

{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get the standard symbol tick data to the MqlTick array
MqlTick array[]={};
if(!GetTicksToArray(CUSTOM_SYMBOL_ORIGIN, DATATICKS_TO_COPY, array))
return;

//--- print the time of the first and last received ticks of the standard symbol
int total=(int)array.Size();
PrintFormat("First tick time: %s.%03u, Last tick time: %s.%03u",
TimeToString(array[0].time,TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[0].time_msc%1
TimeToString(array[total-1].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[total-

//--- print DATATICKS_TO_PRINT last ticks of the standard symbol in the journal
PrintFormat("\nThe last %d ticks for the standard symbol '%s':", DATATICKS_TO_PRINT, CUSTOM_SYMB
for(int i=total-DATATICKS_TO_PRINT; i<total; i++)
{
if(i<0)
continue;
PrintFormat(" %dth Tick: %s", i, GetTickDescription(array[i]));
}

//--- add a custom symbol to the MarketWatch window


ResetLastError();
if(!SymbolSelect(CUSTOM_SYMBOL_NAME, true))
{
Print("SymbolSelect() failed. Error ", GetLastError());
return;
}

//--- add the tick array data to the custom symbol price history
Print("...");
uint start=GetTickCount();
PrintFormat("Start of adding %u ticks to the history of the custom symbol '%s'", array.Size(), C
int added=CustomTicksAdd(CUSTOM_SYMBOL_NAME, array);
PrintFormat("Added %u ticks to the history of the custom symbol '%s' in %u ms", added, CUSTOM_SY

//--- get the newly added custom symbol tick data to the MqlTick array
Print("...");
if(!GetTicksToArray(CUSTOM_SYMBOL_NAME, array.Size(), array))
return;

//--- print the time of the first and last received ticks of the custom symbol

© 2000-2025, MetaQuotes Ltd.


2043 Custom Symbols

total=(int)array.Size();
PrintFormat("First tick time: %s.%03u, Last tick time: %s.%03u",
TimeToString(array[0].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[0].time_msc%
TimeToString(array[total-1].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[total-

//--- print DATATICKS_TO_PRINT last ticks of the custom symbol in the journal
PrintFormat("\nThe last %d ticks for the custom symbol '%s':", DATATICKS_TO_PRINT, CUSTOM_SYMBOL
for(int i=total-DATATICKS_TO_PRINT; i<total; i++)
{
if(i<0)
continue;
PrintFormat(" %dth Tick: %s", i, GetTickDescription(array[i]));
}

//--- get the tick time in milliseconds, from which we will delete the range of ticks, from history
long time_from=array[total-DATATICKS_TO_DELETE-1].time_msc;

//--- delete DATATICKS_TO_DELETE the range of the last ticks of the custom symbol in the array
Print("...");
start=GetTickCount();
PrintFormat("Start deleting %u ticks in the history of the custom symbol '%s'", DATATICKS_TO_DEL
int deleted=CustomTicksDelete(CUSTOM_SYMBOL_NAME, time_from, array[total-2].time_msc);
PrintFormat("Deleted %u ticks in the history of the custom symbol '%s' in %u ms", deleted, CUSTO

//--- get the newly modified custom symbol tick data to the MqlTick array
Print("...");
if(!GetTicksToArray(CUSTOM_SYMBOL_NAME, array.Size(), array))
return;

//--- print the time of the first and last ticks of a custom symbol with a removed tick range
total=(int)array.Size();
PrintFormat("Time of the first tick from the changed history: %s.%03u, Time of the last tick fro
TimeToString(array[0].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[0].time_msc%
TimeToString(array[total-1].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[total-

//--- print DATATICKS_TO_PRINT last ticks of the custom symbol in the journal
PrintFormat("\nThe last %d ticks of custom symbol '%s' with modified history:", DATATICKS_TO_PRI
for(int i=total-DATATICKS_TO_PRINT; i<total; i++)
{
if(i<0)
continue;
PrintFormat(" %dth Tick: %s", i, GetTickDescription(array[i]));
}

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S
//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{

© 2000-2025, MetaQuotes Ltd.


2044 Custom Symbols

Sleep(16);
//--- when pressing Del, delete the created custom symbol and its data
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
//--- delete bar data
int deleted=CustomRatesDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history bars of the custom symbol '%s' were successfully deleted", dele

//--- delete tick data


deleted=CustomTicksDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history ticks of the custom symbol '%s' were successfully deleted", del

//--- delete symbol


if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
Requested 4294967295 ticks to get tick history for the symbol 'EURUSD'
The tick history for the 'EURUSD' symbol is received in the amount of 351199027 ticks in 55875 m
First tick time: 2011.12.19 00:00:08.000, Last tick time: 2024.06.21 10:10:40.392

The last 20 ticks for the standard symbol 'EURUSD':


351199007th Tick: 2024.06.21 10:10:23.045 Bid=1.07032 (Info tick)
351199008th Tick: 2024.06.21 10:10:24.045 Ask=1.07031 Bid=1.07031 (Info tick)
351199009th Tick: 2024.06.21 10:10:24.545 Ask=1.07032 (Info tick)
351199010th Tick: 2024.06.21 10:10:25.146 Bid=1.07032 (Info tick)
351199011th Tick: 2024.06.21 10:10:25.649 Ask=1.07037 Bid=1.07037 (Info tick)
351199012th Tick: 2024.06.21 10:10:27.050 Ask=1.07036 Bid=1.07036 (Info tick)
351199013th Tick: 2024.06.21 10:10:28.153 Ask=1.07039 Bid=1.07039 (Info tick)
351199014th Tick: 2024.06.21 10:10:29.157 Ask=1.07037 Bid=1.07037 (Info tick)
351199015th Tick: 2024.06.21 10:10:29.658 Ask=1.07036 Bid=1.07036 (Info tick)
351199016th Tick: 2024.06.21 10:10:30.258 Bid=1.07036 (Info tick)
351199017th Tick: 2024.06.21 10:10:30.872 Ask=1.07035 Bid=1.07035 (Info tick)
351199018th Tick: 2024.06.21 10:10:31.358 Ask=1.07036 (Info tick)
351199019th Tick: 2024.06.21 10:10:31.859 Ask=1.07037 Bid=1.07037 (Info tick)
351199020th Tick: 2024.06.21 10:10:32.377 Ask=1.07039 Bid=1.07039 (Info tick)
351199021th Tick: 2024.06.21 10:10:32.962 Ask=1.0704 Bid=1.0704 (Info tick)
351199022th Tick: 2024.06.21 10:10:33.961 Ask=1.07039 Bid=1.07039 (Info tick)
351199023th Tick: 2024.06.21 10:10:34.667 Ask=1.0704 (Info tick)
351199024th Tick: 2024.06.21 10:10:35.170 Bid=1.0704 (Info tick)
351199025th Tick: 2024.06.21 10:10:38.266 Ask=1.07041 Bid=1.07041 (Info tick)
351199026th Tick: 2024.06.21 10:10:40.392 Ask=1.07042 Bid=1.07042 (Info tick)

© 2000-2025, MetaQuotes Ltd.


2045 Custom Symbols

...
Start of adding 351199027 ticks to the history of the custom symbol 'EURUSD.C'
Added 351199027 ticks to the history of the custom symbol 'EURUSD.C' in 261594 ms
...
Requested 351199027 ticks to get tick history for the symbol 'EURUSD.C'
The tick history for the 'EURUSD.C' symbol is received in the amount of 351199027 ticks in 13715
First tick time: 2011.12.19 00:00:08.000, Last tick time: 2024.06.21 10:10:40.392

The last 20 ticks for the custom symbol 'EURUSD.C':


351199007th Tick: 2024.06.21 10:10:23.045 Ask=1.07032 Bid=1.07032 (Info tick)
351199008th Tick: 2024.06.21 10:10:24.045 Ask=1.07031 Bid=1.07031 (Info tick)
351199009th Tick: 2024.06.21 10:10:24.545 Ask=1.07032 Bid=1.07032 (Info tick)
351199010th Tick: 2024.06.21 10:10:25.146 Ask=1.07032 Bid=1.07032 (Info tick)
351199011th Tick: 2024.06.21 10:10:25.649 Ask=1.07037 Bid=1.07037 (Info tick)
351199012th Tick: 2024.06.21 10:10:27.050 Ask=1.07036 Bid=1.07036 (Info tick)
351199013th Tick: 2024.06.21 10:10:28.153 Ask=1.07039 Bid=1.07039 (Info tick)
351199014th Tick: 2024.06.21 10:10:29.157 Ask=1.07037 Bid=1.07037 (Info tick)
351199015th Tick: 2024.06.21 10:10:29.658 Ask=1.07036 Bid=1.07036 (Info tick)
351199016th Tick: 2024.06.21 10:10:30.258 Ask=1.07036 Bid=1.07036 (Info tick)
351199017th Tick: 2024.06.21 10:10:30.872 Ask=1.07035 Bid=1.07035 (Info tick)
351199018th Tick: 2024.06.21 10:10:31.358 Ask=1.07036 Bid=1.07036 (Info tick)
351199019th Tick: 2024.06.21 10:10:31.859 Ask=1.07037 Bid=1.07037 (Info tick)
351199020th Tick: 2024.06.21 10:10:32.377 Ask=1.07039 Bid=1.07039 (Info tick)
351199021th Tick: 2024.06.21 10:10:32.962 Ask=1.0704 Bid=1.0704 (Info tick)
351199022th Tick: 2024.06.21 10:10:33.961 Ask=1.07039 Bid=1.07039 (Info tick)
351199023th Tick: 2024.06.21 10:10:34.667 Ask=1.0704 Bid=1.0704 (Info tick)
351199024th Tick: 2024.06.21 10:10:35.170 Ask=1.0704 Bid=1.0704 (Info tick)
351199025th Tick: 2024.06.21 10:10:38.266 Ask=1.07041 Bid=1.07041 (Info tick)
351199026th Tick: 2024.06.21 10:10:40.392 Ask=1.07042 Bid=1.07042 (Info tick)
...
Start deleting 10 ticks in the history of the custom symbol 'EURUSD.C'
Deleted 10 ticks in the history of the custom symbol 'EURUSD.C' in 188 ms
...
Requested 351199027 ticks to get tick history for the symbol 'EURUSD.C'
The tick history for the 'EURUSD.C' symbol is received in the amount of 351199017 ticks in 13831
Time of the first tick from the changed history: 2011.12.19 00:00:08.000, Time of the last tick

The last 20 ticks of custom symbol 'EURUSD.C' with modified history:


351198997th Tick: 2024.06.21 10:10:14.935 Ask=1.07036 Bid=1.07036 (Info tick)
351198998th Tick: 2024.06.21 10:10:15.533 Ask=1.07035 Bid=1.07035 (Info tick)
351198999th Tick: 2024.06.21 10:10:17.736 Ask=1.07036 Bid=1.07036 (Info tick)
351199000th Tick: 2024.06.21 10:10:18.540 Ask=1.07037 Bid=1.07037 (Info tick)
351199001th Tick: 2024.06.21 10:10:19.046 Ask=1.07038 Bid=1.07038 (Info tick)
351199002th Tick: 2024.06.21 10:10:19.542 Ask=1.07036 Bid=1.07036 (Info tick)
351199003th Tick: 2024.06.21 10:10:20.041 Ask=1.07035 Bid=1.07035 (Info tick)
351199004th Tick: 2024.06.21 10:10:21.041 Ask=1.07035 Bid=1.07035 (Info tick)
351199005th Tick: 2024.06.21 10:10:21.544 Ask=1.07032 Bid=1.07032 (Info tick)
351199006th Tick: 2024.06.21 10:10:22.344 Ask=1.07032 Bid=1.07032 (Info tick)
351199007th Tick: 2024.06.21 10:10:23.045 Ask=1.07032 Bid=1.07032 (Info tick)

© 2000-2025, MetaQuotes Ltd.


2046 Custom Symbols

351199008th Tick: 2024.06.21 10:10:24.045 Ask=1.07031 Bid=1.07031 (Info tick)


351199009th Tick: 2024.06.21 10:10:24.545 Ask=1.07032 Bid=1.07032 (Info tick)
351199010th Tick: 2024.06.21 10:10:25.146 Ask=1.07032 Bid=1.07032 (Info tick)
351199011th Tick: 2024.06.21 10:10:25.649 Ask=1.07037 Bid=1.07037 (Info tick)
351199012th Tick: 2024.06.21 10:10:27.050 Ask=1.07036 Bid=1.07036 (Info tick)
351199013th Tick: 2024.06.21 10:10:28.153 Ask=1.07039 Bid=1.07039 (Info tick)
351199014th Tick: 2024.06.21 10:10:29.157 Ask=1.07037 Bid=1.07037 (Info tick)
351199015th Tick: 2024.06.21 10:10:29.658 Ask=1.07036 Bid=1.07036 (Info tick)
351199016th Tick: 2024.06.21 10:10:40.392 Ask=1.07042 Bid=1.07042 (Info tick)
*/
}
//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());

© 2000-2025, MetaQuotes Ltd.


2047 Custom Symbols

return(false);
}
//--- successful
return(true);
}
//+------------------------------------------------------------------+
//| Get the specified number of ticks in the array |
//+------------------------------------------------------------------+
bool GetTicksToArray(const string symbol, const uint count, MqlTick &array[])
{
//--- notify of the start of loading historical data
PrintFormat("Requested %u ticks to get tick history for the symbol '%s'", count, symbol);

//--- make 3 attempts to receive ticks


int attempts=0;
while(attempts<3)
{
//--- measure the start time before receiving the ticks
uint start=GetTickCount();

//--- request the tick history since 1970.01.01 00:00.001 (parameter from=1 ms)
int received=CopyTicks(symbol, array, COPY_TICKS_ALL, 1, count);
if(received!=-1)
{
//--- display information about the number of ticks and spent time
PrintFormat("The tick history for the '%s' symbol is received in the amount of %u ticks in

//--- if the tick history is synchronized, the error code is equal to zero - return 'true'
if(GetLastError()==0)
return(true);

PrintFormat("%s: Ticks are not synchronized yet, %d ticks received for %d ms. Error=%d",
symbol, received, GetTickCount()-start, GetLastError());
}
//--- count attempts
attempts++;
//--- a one-second pause to wait for the end of synchronization of the tick database
Sleep(1000);
}
//--- failed to copy ticks in 3 attempts
return(false);
}
//+------------------------------------------------------------------+
//| return the string description of a tick |
//+------------------------------------------------------------------+
string GetTickDescription(MqlTick &tick)
{
string desc=StringFormat("%s.%03u ", TimeToString(tick.time, TIME_DATE|TIME_MINUTES|TIME_SECONDS

© 2000-2025, MetaQuotes Ltd.


2048 Custom Symbols

//--- check tick flags


bool buy_tick = ((tick.flags &TICK_FLAG_BUY) == TICK_FLAG_BUY);
bool sell_tick = ((tick.flags &TICK_FLAG_SELL) == TICK_FLAG_SELL);
bool ask_tick = ((tick.flags &TICK_FLAG_ASK) == TICK_FLAG_ASK);
bool bid_tick = ((tick.flags &TICK_FLAG_BID) == TICK_FLAG_BID);
bool last_tick = ((tick.flags &TICK_FLAG_LAST) == TICK_FLAG_LAST);
bool volume_tick= ((tick.flags &TICK_FLAG_VOLUME)== TICK_FLAG_VOLUME);

//--- check the tick for trading flags first (there are none for CustomTicksAdd())
if(buy_tick || sell_tick)
{
//--- form an output for a trading tick
desc += (buy_tick ? StringFormat("Buy Tick: Last=%G Volume=%d ", tick.last, tick.volume) : "
desc += (sell_tick? StringFormat("Sell Tick: Last=%G Volume=%d ",tick.last, tick.volume) : ""
desc += (ask_tick ? StringFormat("Ask=%G ", tick.ask) : "");
desc += (bid_tick ? StringFormat("Bid=%G ", tick.ask) : "");
desc += "(Trade tick)";
}
else
{
//--- form an output for an info tick a bit differently
desc += (ask_tick ? StringFormat("Ask=%G ", tick.ask) : "");
desc += (bid_tick ? StringFormat("Bid=%G ", tick.ask) : "");
desc += (last_tick ? StringFormat("Last=%G ", tick.last) : "");
desc += (volume_tick? StringFormat("Volume=%d ",tick.volume): "");
desc += "(Info tick)";
}
//--- return tick description
return(desc);
}

See also
CustomRates Delete, CustomRates Update, CustomTicks Replace, CopyTicks, CopyTicks Range

© 2000-2025, MetaQuotes Ltd.


2049 Custom Symbols

CustomTicksReplace
Fullyreplaces the price history of the custom symbol within the specified time interval with the data
from the M qlTick type array.
int CustomTicksReplace(
const string symbol, // symbol name
long from_msc, // start date
long to_msc, // end date
const MqlTick& ticks[], // array for the data to be applied to a custom symbol
uint count=WHOLE_ARRAY // number of the ticks[] array elements to be used
);

Parameters
symbol
[in] Custom symbol name.
from_msc
[in] Time of the first tick in the price history within the specified range to be removed. Time in
milliseconds since 01.01.1970.
to_msc
[in] Time of the last tick in the price history within the specified range to be removed. Time in
milliseconds since 01.01.1970.
ticks[]
[in] Array of the M qlTick type tick data ordered in time in ascending order.
count=WHOLE_ARRAY
[in] Number of the ticks[] array elements to be used for replacement in the specified time
interval. WHOLE_ARRAY means that all ticks[] array elements should be used.

Return Value

Number of updated ticks or -1 in case of an error.


Note

S inceseveral ticks may often have the same time up to a millisecond in a stream of quotes
(accurate tick time is stored in the time_msc field of the M qlTick structure), the
CustomTicks Replace function does not automatically sort out the ticks[] array elements by time.
Therefore, the array of ticks must be pre-arranged in time ascending order.
The ticks are replaced consecutively, day after day, until the time specified in to_msc or until an
error occurs. The first day from the specified range is processed followed by the next one, etc. As
soon as the mismatch between the tick time and the ascending (non-descending) order is detected,
the tick replacement stops on the current day. All ticks from the previous days are successfully
replaced, while the current day (at the moment of a wrong tick) and all the remaining days in the
specified interval remain unchanged.
If the ticks[] array contains no tick data for any day (generally, any time interval), a " hole"
corresponding to the missing data appears in the custom symbol history after the tick data from
ticks[] are applied. In other words, the call of CustomTicks Replace with missing ticks is

© 2000-2025, MetaQuotes Ltd.


2050 Custom Symbols

equivalent to deleting part of the tick history, as if CustomTicks Delete with the " hole" interval is
called.
If the tick database has no data for the specified time interval, CustomTicks Replace will add to the
database ticks form the ticks [] array.
The CustomTicks Replace function works directly with the tick database.

Example:

//+------------------------------------------------------------------+
//| CustomTicksReplace.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"

#define CUSTOM_SYMBOL_NAME Symbol()+".C" // custom symbol name


#define CUSTOM_SYMBOL_PATH "Forex" // name of the group, in which a symbol is to be
#define CUSTOM_SYMBOL_ORIGIN Symbol() // name of a symbol a custom one is to be based

#define DATATICKS_TO_COPY UINT_MAX // number of ticks copied


#define DATATICKS_TO_PRINT 20 // number of ticks sent to the journal

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the error code when creating a custom symbol
int create=CreateCustomSymbol(CUSTOM_SYMBOL_NAME, CUSTOM_SYMBOL_PATH, CUSTOM_SYMBOL_ORIGIN);

//--- if the error code is not 0 (successful symbol creation) and not 5304 (symbol has already been
if(create!=0 && create!=5304)
return;

//--- get the standard symbol tick data to the MqlTick array
MqlTick array[]={};
if(!GetTicksToArray(CUSTOM_SYMBOL_ORIGIN, DATATICKS_TO_COPY, array))
return;

//--- print the time of the first and last received ticks of the standard symbol
int total=(int)array.Size();
PrintFormat("First tick time: %s.%03u, Last tick time: %s.%03u",
TimeToString(array[0].time,TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[0].time_msc%1
TimeToString(array[total-1].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[total-

© 2000-2025, MetaQuotes Ltd.


2051 Custom Symbols

//--- print DATATICKS_TO_PRINT last ticks of the standard symbol in the journal
PrintFormat("\nThe last %d ticks for the standard symbol '%s':", DATATICKS_TO_PRINT, CUSTOM_SYMB
for(int i=total-DATATICKS_TO_PRINT; i<total; i++)
{
if(i<0)
continue;
PrintFormat(" %dth Tick: %s", i, GetTickDescription(array[i]));
}

//--- add a custom symbol to the MarketWatch window


ResetLastError();
if(!SymbolSelect(CUSTOM_SYMBOL_NAME, true))
{
Print("SymbolSelect() failed. Error ", GetLastError());
return;
}

//--- add the tick array data to the custom symbol price history
Print("...");
uint start=GetTickCount();
PrintFormat("Start of adding %u ticks to the history of the custom symbol '%s'", array.Size(), C
int added=CustomTicksAdd(CUSTOM_SYMBOL_NAME, array);
PrintFormat("Added %u ticks to the history of the custom symbol '%s' in %u ms", added, CUSTOM_SY

//--- get the newly added custom symbol tick data to the MqlTick array
Print("...");
if(!GetTicksToArray(CUSTOM_SYMBOL_NAME, array.Size(), array))
return;

//--- print the time of the first and last received ticks of the custom symbol
total=(int)array.Size();
PrintFormat("First tick time: %s.%03u, Last tick time: %s.%03u",
TimeToString(array[0].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[0].time_msc%
TimeToString(array[total-1].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[total-

//--- print DATATICKS_TO_PRINT last ticks of the custom symbol in the journal
PrintFormat("\nThe last %d ticks for the custom symbol '%s':", DATATICKS_TO_PRINT, CUSTOM_SYMBOL
for(int i=total-DATATICKS_TO_PRINT; i<total; i++)
{
if(i<0)
continue;
PrintFormat(" %dth Tick: %s", i, GetTickDescription(array[i]));
}

//--- now change Ask and Bid tick values in the array using the equation Ask(Symbol) = 1.0 / Ask(Sy
for(int i=0; i<total; i++)
{
array[i].ask = (array[i].ask !=0 ? 1.0 / array[i].ask : array[i].ask);

© 2000-2025, MetaQuotes Ltd.


2052 Custom Symbols

array[i].bid = (array[i].bid !=0 ? 1.0 / array[i].bid : array[i].bid);


}
Print("\nNow the ticks are changed");

//--- replace the tick history of the custom symbol with data from the modified array of ticks
Print("...");
start=GetTickCount();
PrintFormat("Start replacing %u changed ticks in the history of the custom symbol '%s'", array.S
int replaced=CustomTicksReplace(CUSTOM_SYMBOL_NAME, array[0].time_msc, array[total-1].time_msc,
PrintFormat("Replaced %u ticks in the history of the custom symbol '%s' in %u ms", replaced, CUS

//--- get the newly replaced custom symbol tick data to the MqlTick array
Print("...");
if(!GetTicksToArray(CUSTOM_SYMBOL_NAME, array.Size(), array))
return;

//--- print the time of the first and last received modified ticks of the custom symbol
total=(int)array.Size();
PrintFormat("First changed tick time: %s.%03u, Last changed tick time: %s.%03u",
TimeToString(array[0].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[0].time_msc%
TimeToString(array[total-1].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), array[total-

//--- print DATATICKS_TO_PRINT last modified ticks of the custom symbol in the journal
PrintFormat("\nThe last %d changed ticks for the custom symbol '%s':", DATATICKS_TO_PRINT, CUSTO
for(int i=total-DATATICKS_TO_PRINT; i<total; i++)
{
if(i<0)
continue;
PrintFormat(" %dth Changed tick: %s", i, GetTickDescription(array[i]));
}

//--- display a hint about the script termination keys on the chart comment
Comment(StringFormat("Press 'Esc' to exit or 'Del' to delete the '%s' symbol and exit", CUSTOM_S
//--- wait for pressing the Esc or Del keys to exit in an endless loop
while(!IsStopped() && TerminalInfoInteger(TERMINAL_KEYSTATE_ESCAPE)==0)
{
Sleep(16);
//--- when pressing Del, delete the created custom symbol and its data
if(TerminalInfoInteger(TERMINAL_KEYSTATE_DELETE)<0)
{
//--- delete bar data
int deleted=CustomRatesDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history bars of the custom symbol '%s' were successfully deleted", dele

//--- delete tick data


deleted=CustomTicksDelete(CUSTOM_SYMBOL_NAME, 0, LONG_MAX);
if(deleted>0)
PrintFormat("%d history ticks of the custom symbol '%s' were successfully deleted", del

© 2000-2025, MetaQuotes Ltd.


2053 Custom Symbols

//--- delete symbol


if(DeleteCustomSymbol(CUSTOM_SYMBOL_NAME))
PrintFormat("Custom symbol '%s' deleted successfully", CUSTOM_SYMBOL_NAME);
break;
}
}
//--- clear the chart before exiting
Comment("");
/*
result:
Requested 4294967295 ticks to get tick history for the symbol 'EURUSD'
The tick history for the 'EURUSD' symbol is received in the amount of 351195822 ticks in 55735 m
First tick time: 2011.12.19 00:00:08.000, Last tick time: 2024.06.21 08:39:03.113

The last 20 ticks for the standard symbol 'EURUSD':


351195802th Tick: 2024.06.21 08:38:10.076 Ask=1.07194 (Info tick)
351195803th Tick: 2024.06.21 08:38:13.162 Ask=1.07195 (Info tick)
351195804th Tick: 2024.06.21 08:38:13.872 Bid=1.07195 (Info tick)
351195805th Tick: 2024.06.21 08:38:14.866 Ask=1.07194 Bid=1.07194 (Info tick)
351195806th Tick: 2024.06.21 08:38:17.374 Bid=1.07194 (Info tick)
351195807th Tick: 2024.06.21 08:38:18.883 Bid=1.07194 (Info tick)
351195808th Tick: 2024.06.21 08:38:19.771 Bid=1.07194 (Info tick)
351195809th Tick: 2024.06.21 08:38:20.873 Ask=1.07195 Bid=1.07195 (Info tick)
351195810th Tick: 2024.06.21 08:38:22.278 Ask=1.07196 Bid=1.07196 (Info tick)
351195811th Tick: 2024.06.21 08:38:22.775 Bid=1.07196 (Info tick)
351195812th Tick: 2024.06.21 08:38:23.477 Bid=1.07196 (Info tick)
351195813th Tick: 2024.06.21 08:38:38.194 Ask=1.07197 (Info tick)
351195814th Tick: 2024.06.21 08:38:38.789 Ask=1.07196 (Info tick)
351195815th Tick: 2024.06.21 08:38:39.290 Ask=1.07197 (Info tick)
351195816th Tick: 2024.06.21 08:38:43.695 Ask=1.07196 (Info tick)
351195817th Tick: 2024.06.21 08:38:52.203 Ask=1.07195 Bid=1.07195 (Info tick)
351195818th Tick: 2024.06.21 08:38:55.105 Ask=1.07196 Bid=1.07196 (Info tick)
351195819th Tick: 2024.06.21 08:38:57.607 Ask=1.07195 Bid=1.07195 (Info tick)
351195820th Tick: 2024.06.21 08:39:00.512 Ask=1.07196 Bid=1.07196 (Info tick)
351195821th Tick: 2024.06.21 08:39:03.113 Ask=1.07195 Bid=1.07195 (Info tick)
...
Start of adding 351195822 ticks to the history of the custom symbol 'EURUSD.C'
Added 351195822 ticks to the history of the custom symbol 'EURUSD.C' in 349407 ms
...
Requested 351195822 ticks to get tick history for the symbol 'EURUSD.C'
The tick history for the 'EURUSD.C' symbol is received in the amount of 351195822 ticks in 19020
First tick time: 2011.12.19 00:00:08.000, Last tick time: 2024.06.21 08:39:03.113

The last 20 ticks for the custom symbol 'EURUSD.C':


351195802th Tick: 2024.06.21 08:38:10.076 Ask=1.07194 Bid=1.07194 (Info tick)
351195803th Tick: 2024.06.21 08:38:13.162 Ask=1.07195 Bid=1.07195 (Info tick)
351195804th Tick: 2024.06.21 08:38:13.872 Ask=1.07195 Bid=1.07195 (Info tick)
351195805th Tick: 2024.06.21 08:38:14.866 Ask=1.07194 Bid=1.07194 (Info tick)

© 2000-2025, MetaQuotes Ltd.


2054 Custom Symbols

351195806th Tick: 2024.06.21 08:38:17.374 Ask=1.07194 Bid=1.07194 (Info tick)


351195807th Tick: 2024.06.21 08:38:18.883 Ask=1.07194 Bid=1.07194 (Info tick)
351195808th Tick: 2024.06.21 08:38:19.771 Ask=1.07194 Bid=1.07194 (Info tick)
351195809th Tick: 2024.06.21 08:38:20.873 Ask=1.07195 Bid=1.07195 (Info tick)
351195810th Tick: 2024.06.21 08:38:22.278 Ask=1.07196 Bid=1.07196 (Info tick)
351195811th Tick: 2024.06.21 08:38:22.775 Ask=1.07196 Bid=1.07196 (Info tick)
351195812th Tick: 2024.06.21 08:38:23.477 Ask=1.07196 Bid=1.07196 (Info tick)
351195813th Tick: 2024.06.21 08:38:38.194 Ask=1.07197 Bid=1.07197 (Info tick)
351195814th Tick: 2024.06.21 08:38:38.789 Ask=1.07196 Bid=1.07196 (Info tick)
351195815th Tick: 2024.06.21 08:38:39.290 Ask=1.07197 Bid=1.07197 (Info tick)
351195816th Tick: 2024.06.21 08:38:43.695 Ask=1.07196 Bid=1.07196 (Info tick)
351195817th Tick: 2024.06.21 08:38:52.203 Ask=1.07195 Bid=1.07195 (Info tick)
351195818th Tick: 2024.06.21 08:38:55.105 Ask=1.07196 Bid=1.07196 (Info tick)
351195819th Tick: 2024.06.21 08:38:57.607 Ask=1.07195 Bid=1.07195 (Info tick)
351195820th Tick: 2024.06.21 08:39:00.512 Ask=1.07196 Bid=1.07196 (Info tick)
351195821th Tick: 2024.06.21 08:39:03.113 Ask=1.07195 Bid=1.07195 (Info tick)

Now the ticks are changed


...
Start replacing 351195822 changed ticks in the history of the custom symbol 'EURUSD.C'
Replaced 351195822 ticks in the history of the custom symbol 'EURUSD.C' in 452266 ms
...
Requested 351195822 ticks to get tick history for the symbol 'EURUSD.C'
The tick history for the 'EURUSD.C' symbol is received in the amount of 351195822 ticks in 19981
First changed tick time: 2011.12.19 00:00:08.000, Last changed tick time: 2024.06.21 08:39:03.11

The last 20 changed ticks for the custom symbol 'EURUSD.C':


351195802th Changed tick: 2024.06.21 08:38:10.076 Ask=0.93289 Bid=0.93289 (Info tick)
351195803th Changed tick: 2024.06.21 08:38:13.162 Ask=0.93288 Bid=0.93288 (Info tick)
351195804th Changed tick: 2024.06.21 08:38:13.872 Ask=0.93288 Bid=0.93288 (Info tick)
351195805th Changed tick: 2024.06.21 08:38:14.866 Ask=0.93289 Bid=0.93289 (Info tick)
351195806th Changed tick: 2024.06.21 08:38:17.374 Ask=0.93289 Bid=0.93289 (Info tick)
351195807th Changed tick: 2024.06.21 08:38:18.883 Ask=0.93289 Bid=0.93289 (Info tick)
351195808th Changed tick: 2024.06.21 08:38:19.771 Ask=0.93289 Bid=0.93289 (Info tick)
351195809th Changed tick: 2024.06.21 08:38:20.873 Ask=0.93288 Bid=0.93288 (Info tick)
351195810th Changed tick: 2024.06.21 08:38:22.278 Ask=0.93287 Bid=0.93287 (Info tick)
351195811th Changed tick: 2024.06.21 08:38:22.775 Ask=0.93287 Bid=0.93287 (Info tick)
351195812th Changed tick: 2024.06.21 08:38:23.477 Ask=0.93287 Bid=0.93287 (Info tick)
351195813th Changed tick: 2024.06.21 08:38:38.194 Ask=0.93286 Bid=0.93286 (Info tick)
351195814th Changed tick: 2024.06.21 08:38:38.789 Ask=0.93287 Bid=0.93287 (Info tick)
351195815th Changed tick: 2024.06.21 08:38:39.290 Ask=0.93286 Bid=0.93286 (Info tick)
351195816th Changed tick: 2024.06.21 08:38:43.695 Ask=0.93287 Bid=0.93287 (Info tick)
351195817th Changed tick: 2024.06.21 08:38:52.203 Ask=0.93288 Bid=0.93288 (Info tick)
351195818th Changed tick: 2024.06.21 08:38:55.105 Ask=0.93287 Bid=0.93287 (Info tick)
351195819th Changed tick: 2024.06.21 08:38:57.607 Ask=0.93288 Bid=0.93288 (Info tick)
351195820th Changed tick: 2024.06.21 08:39:00.512 Ask=0.93287 Bid=0.93287 (Info tick)
351195821th Changed tick: 2024.06.21 08:39:03.113 Ask=0.93288 Bid=0.93288 (Info tick)
*/
}

© 2000-2025, MetaQuotes Ltd.


2055 Custom Symbols

//+------------------------------------------------------------------+
//| Create a custom symbol, return an error code |
//+------------------------------------------------------------------+
int CreateCustomSymbol(const string symbol_name, const string symbol_path, const string symbol_orig
{
//--- define the name of a symbol a custom one is to be based on
string origin=(symbol_origin==NULL ? Symbol() : symbol_origin);

//--- if failed to create a custom symbol and this is not error 5304, report this in the journal
ResetLastError();
int error=0;
if(!CustomSymbolCreate(symbol_name, symbol_path, origin))
{
error=GetLastError();
if(error!=5304)
PrintFormat("CustomSymbolCreate(%s, %s, %s) failed. Error %d", symbol_name, symbol_path, o
}
//--- successful
return(error);
}
//+------------------------------------------------------------------+
//| Remove a custom symbol |
//+------------------------------------------------------------------+
bool DeleteCustomSymbol(const string symbol_name)
{
//--- hide the symbol from the Market Watch window
ResetLastError();
if(!SymbolSelect(symbol_name, false))
{
PrintFormat("SymbolSelect(%s, false) failed. Error %d", GetLastError());
return(false);
}

//--- if failed to delete a custom symbol, report this in the journal and return 'false'
ResetLastError();
if(!CustomSymbolDelete(symbol_name))
{
PrintFormat("CustomSymbolDelete(%s) failed. Error %d", symbol_name, GetLastError());
return(false);
}
//--- successful
return(true);
}
//+------------------------------------------------------------------+
//| Get the specified number of ticks in the array |
//+------------------------------------------------------------------+
bool GetTicksToArray(const string symbol, const uint count, MqlTick &array[])
{
//--- notify of the start of loading historical data

© 2000-2025, MetaQuotes Ltd.


2056 Custom Symbols

PrintFormat("Requested %u ticks to get tick history for the symbol '%s'", count, symbol);

//--- make 3 attempts to receive ticks


int attempts=0;
while(attempts<3)
{
//--- measure the start time before receiving the ticks
uint start=GetTickCount();

//--- request the tick history since 1970.01.01 00:00.001 (parameter from=1 ms)
int received=CopyTicks(symbol, array, COPY_TICKS_ALL, 1, count);
if(received!=-1)
{
//--- display information about the number of ticks and spent time
PrintFormat("The tick history for the '%s' symbol is received in the amount of %u ticks in

//--- if the tick history is synchronized, the error code is equal to zero - return 'true'
if(GetLastError()==0)
return(true);

PrintFormat("%s: Ticks are not synchronized yet, %d ticks received for %d ms. Error=%d",
symbol, received, GetTickCount()-start, GetLastError());
}
//--- count attempts
attempts++;
//--- a one-second pause to wait for the end of synchronization of the tick database
Sleep(1000);
}
//--- failed to copy ticks in 3 attempts
return(false);
}
//+------------------------------------------------------------------+
//| return the string description of a tick |
//+------------------------------------------------------------------+
string GetTickDescription(MqlTick &tick)
{
string desc=StringFormat("%s.%03u ", TimeToString(tick.time, TIME_DATE|TIME_MINUTES|TIME_SECONDS

//--- check tick flags


bool buy_tick = ((tick.flags &TICK_FLAG_BUY) == TICK_FLAG_BUY);
bool sell_tick = ((tick.flags &TICK_FLAG_SELL) == TICK_FLAG_SELL);
bool ask_tick = ((tick.flags &TICK_FLAG_ASK) == TICK_FLAG_ASK);
bool bid_tick = ((tick.flags &TICK_FLAG_BID) == TICK_FLAG_BID);
bool last_tick = ((tick.flags &TICK_FLAG_LAST) == TICK_FLAG_LAST);
bool volume_tick= ((tick.flags &TICK_FLAG_VOLUME)== TICK_FLAG_VOLUME);

//--- check the tick for trading flags first (there are none for CustomTicksAdd())
if(buy_tick || sell_tick)
{

© 2000-2025, MetaQuotes Ltd.


2057 Custom Symbols

//--- form an output for a trading tick


desc += (buy_tick ? StringFormat("Buy Tick: Last=%G Volume=%d ", tick.last, tick.volume) : "
desc += (sell_tick? StringFormat("Sell Tick: Last=%G Volume=%d ",tick.last, tick.volume) : ""
desc += (ask_tick ? StringFormat("Ask=%G ", tick.ask) : "");
desc += (bid_tick ? StringFormat("Bid=%G ", tick.ask) : "");
desc += "(Trade tick)";
}
else
{
//--- form an output for an info tick a bit differently
desc += (ask_tick ? StringFormat("Ask=%G ", tick.ask) : "");
desc += (bid_tick ? StringFormat("Bid=%G ", tick.ask) : "");
desc += (last_tick ? StringFormat("Last=%G ", tick.last) : "");
desc += (volume_tick? StringFormat("Volume=%d ",tick.volume): "");
desc += "(Info tick)";
}
//--- return tick description
return(desc);
}

See also
CustomRates Delete, CustomRates Update, CustomTicks Delete, CopyTicks, CopyTicks Range

© 2000-2025, MetaQuotes Ltd.


2058 Custom Symbols

CustomBookAdd
Passes the status of the Depth of Market for a custom symbol. The function allows broadcasting the
Depth of Mark et as if the prices arrive from a brok er's server.

bool CustomBookAdd(
const string symbol, // symbol name
const MqlBookInfo& books[] // array with descriptions of the Depth of Market element
uint count=WHOLE_ARRAY // number of elements to be used
);

Parameters
symbol
[in] Custom symbol name.
books[]
[in] The array of M qlBookInfo type data fully describing the Depth of Market status — all buy and
sell requests. The passed Depth of Market status completely replaces the previous one.
count=WHOLE_ARRAY
[in] The number of 'books ' array elements to be passed to the function. The entire array is used
by default.

Return Value

true – success, otherwise – false. To get information about the error, call the GetLastError()
function.
Note

The CustomBookAdd function works only for custom symbols the Depth of Market is opened for — via
the platform interface or the MarketBookAdd function.
W hen throwing the Depth of Market in, the symbol's Bid and As k prices are not updated. You should
control the change of the best prices and throw in the ticks using CustomTicks Add.
The function verifies the accuracy of transmitted data: the type, price and volume must be
indicated for each element. Furthermore, M qlBookInfo.volume and M qlBookInfo.volume_real must
not be zero or negative; if both volumes are negative, this will be considered an error. You can
specify any of the volumes or both of them: the one that is indicated or is positive will be used:
volume=-1 && volume_real=2 — volume_real=2 will be used,
a volume=3 && volume_real=0 — volume=3 will be used.

The M qlBookInfo.volume_real extended accuracy volume has a higher priority over the regular
M qlBookInfo.volume. If both values are specified for the Depth of Market element, the volume_real
one is used.
The order of the M qlBookInfo elements in the 'books ' array does not matter. W hen saving the data,
the terminal sorts them by price on its own.

© 2000-2025, MetaQuotes Ltd.


2059 Custom Symbols

W hen saving data, the "Book depth" (SYM BOL_TICKS_BOOKDEPTH) parameter of the recipient
custom symbol is checked. If the number of sell requests exceeds this value in the passed Depth of
Market, the excess levels are discarded. The same is true for buy requests.
S ample filling of the 'books ' array:

Depth of Market status Filling books[]

books[0].type=BOOK_TYPE_SELL;
books[0].price=1.14337;
books[0].volume=100;
books[1].type=BOOK_TYPE_SELL;
books[1].price=1.14330;
books[1].volume=50;
books[2].type=BOOK_TYPE_SELL;
books[2].price=1.14335;
books[2].volume=40;
books[3].type=BOOK_TYPE_SELL;
books[3].price=1.14333;
books[3].volume=10;
books[4].type=BOOK_TYPE_BUY;
books[4].price=1.14322;
books[4].volume=10;
books[5].type=BOOK_TYPE_BUY;
books[5].price=1.14320;
books[5].volume=90;
books[6].type=BOOK_TYPE_BUY;
books[6].price=1.14319;
books[6].volume=100;
books[7].type=BOOK_TYPE_BUY;
books[7].price=1.14318;
books[7].volume=10;

Example:

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- enable the Depth of Market for a symbol we are to retrieve data from
MarketBookAdd(Symbol());
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Tick function |
//+------------------------------------------------------------------+
void OnTick(void)
{
MqlTick ticks[];
ArrayResize(ticks,1);

© 2000-2025, MetaQuotes Ltd.


2060 Custom Symbols

//--- copy the current prices from the common symbol to the custom one
if(SymbolInfoTick(Symbol(),ticks[0]))
{
string symbol_name=Symbol()+".SYN";
CustomTicksAdd(symbol_name,ticks);
}
}
//+------------------------------------------------------------------+
//| Book function |
//+------------------------------------------------------------------+
void OnBookEvent(const string &book_symbol)
{
//--- copy the current Depth of Market status from the common symbol to the custom one
if(book_symbol==Symbol())
{
MqlBookInfo book_array[];
if(MarketBookGet(Symbol(),book_array))
{
string symbol_name=Symbol()+".SYN";
CustomBookAdd(symbol_name,book_array);
}
}
}
//+------------------------------------------------------------------+

See also
MarketBookAdd, CustomTicks Add, OnBookEvent

© 2000-2025, MetaQuotes Ltd.


2061 Chart Operations

Chart Operations
Functions for setting chart properties (ChartS etInteger, ChartS etDouble, ChartS etS tring) are
asynchronous and are used for sending update commands to a chart. If these functions are executed
successfully, the command is included in the common queue of the chart events. Chart property
changes are implemented along with handling of the events queue of this chart.
Thus, do not expect an immediate update of the chart after calling asynchronous functions. Use the
ChartRedraw() function to forcedly update the chart appearance and properties.

Function Action

ChartApplyTemplate Applies a specific template from a specified file to the chart


ChartS aveTemplate S aves current chart settings in a template with a specified name
ChartW indowFind R eturns the number of a subwindow where an indicator is drawn
ChartTimePriceToXY Converts the coordinates of a chart from the time/price
representation to the X and Y coordinates
ChartXYToTimePrice Converts the X and Y coordinates on a chart to the time and price
values
ChartOpen Opens a new chart with the specified symbol and period
ChartClose Closes the specified chart
ChartFirst R eturns the ID of the first chart of the client terminal
ChartNext R eturns the chart ID of the chart next to the specified one
ChartS ymbol R eturns the symbol name of the specified chart
ChartPeriod R eturns the period value of the specified chart
ChartRedraw Calls a forced redrawing of a specified chart
ChartS etDouble S etsthe double value for a corresponding property of the specified
chart
ChartS etInteger S etsthe integer value (datetime, int, color, bool or char) for a
corresponding property of the specified chart
ChartS etS tring S ets the string value for a corresponding property of the specified
chart
ChartGetDouble R eturns the double value property of the specified chart
ChartGetInteger R eturns the integer value property of the specified chart
ChartGetS tring R eturns 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 R eturns the ID of the current chart

© 2000-2025, MetaQuotes Ltd.


2062 Chart Operations

Function Action

ChartIndicatorAdd Adds an indicator with the specified handle into a specified chart
window
ChartIndicatorDelete R emoves an indicator with a specified name from the specified chart
window
ChartIndicatorGet R eturnsthe handle of the indicator with the specified short name in
the specified chart window
ChartIndicatorName R eturns the short name of the indicator by the number in the
indicators list on the specified chart window
ChartIndicatorsTotal R eturns the number of all indicators applied to the specified chart
window.
ChartW indowOnDropped R eturns the number (index) of the chart subwindow the Expert
Advisor or script has been dropped to

ChartPriceOnDropped R eturns the price coordinate of the chart point the Expert Advisor or
script has been dropped to
ChartTimeOnDropped R eturns the time coordinate of the chart point the Expert Advisor or
script has been dropped to
ChartXOnDropped R eturns the X coordinate of the chart point the Expert Advisor or
script has been dropped to
ChartYOnDropped R eturns the Y coordinate of the chart point the Expert Advisor or
script has been dropped to
ChartS etS ymbolPeriod Changes the symbol value and a period of the specified chart
ChartS creenS hot Provides a screenshot of the chart of its current state in a GIF, PNG
or BMP format depending on specified extension

© 2000-2025, MetaQuotes Ltd.


2063 Chart Operations

ChartApplyTemplate
Appliesa specific template from a specified file to the chart. The command is added to chart
messages queue and will be executed after processing of all previous commands.
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.

Return Value

R eturnstrue if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
Note

The Expert Advisor will be unloaded and will not be able to continue operating in case of successful
loading of a new template to the chart it is attached to.
W hen applying the template to the chart, trade permissions may be limited due to security reasons :
Live trading permission cannot be extended for the Expert Advisors launched by
applying the template using ChartApplyTemplate() function.

If the mql5-program calling ChartApplyTemplate() function has no permission to trade, the Expert
Advisor launched via the template will also not be able to trade regardless of the template settings.

If the mql5-program calling ChartApplyTemplate() function has permission to trade, while there is no
such permission in the template settings, the Expert Advisor launched via the template will not be
able to trade.

Using Templates
The resources of the MQL5 language allow setting multiple chart properties, including colors using the
ChartS etInteger() function:
· Chart background color;
· Color of the axes, scale and the OHLC line;
· Grid color;
· Color of volumes and position open levels ;
· Color of the up bar, shadow and edge of a bullish candlestick;
· Color of the down bar, shadow and edge of a bearish candlestick;
· Color of the chart line and Doji candlesticks ;

© 2000-2025, MetaQuotes Ltd.


2064 Chart Operations

· Color of the bullish candlestick body;


· Color of the bearish candlestick body;
· Color of the Bid price line;
· Color of the As k price line;
· Color of the line of the last deal price (Last);
· Color of the stop order levels (S top Loss and Take Profit).
Besides, there can be multiple graphical objects and indicators on a chart. You may set up a chart with
all the necessary indicators once and then save it as a template. S uch a template can be applied to any
chart.
The ChartApplyTemplate() function is intended for using a previously saved template, and it can be
used in any mql5 program. The path to the file that stores the template is passed as the second
parameter to ChartApplyTemplate(). The template file is searched according to the following rules :
· if the backslash "\" separator (written as "\\" ) is placed at the beginning of the path, the template
is searched for relative to the path _terminal_data_directory\MQL5,
· if there is no back slash, the template is searched for relative to the executable EX5 file, in which
ChartApplyTemplate() is called;
· if a template is not found in the first two variants, the search is performed in the folder
terminal_directory\Profiles \Templates \.
H ere terminal_directory is the folder from which the MetaTrader 5 Client Terminal is running, and
terminal_data_directory is the folder, in which editable files are stored, its location depends on the
operating system, user name and computer's security settings. Normally they are different folders, but
in some cases they may coincide.
The location of folders terminal_data_directory and terminal_directory can be obtained using the
TerminalInfoS tring() function.
//--- directory from which the terminal is started
string terminal_path=TerminalInfoString(TERMINAL_PATH);
Print("Terminal directory:",terminal_path);
//--- terminal data directory, in which the MQL5 folder with EAs and indicators is located
string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH);
Print("Terminal data directory:",terminal_data_path);

For example:
//--- search for a template in terminal_data_directory\MQL5\
ChartApplyTemplate(0,"\\first_template.tpl"))
//--- search for a template in directory_of_EX5_file\, then in folder terminal_data_directory\Profi
ChartApplyTemplate(0,"second_template.tpl"))
//--- search for a template in directory_of_EX5_file\My_templates\, then in folder terminal_directo
ChartApplyTemplate(0,"My_templates\\third_template.tpl"))
Templates are not resources, they cannot be included into an executable EX5 file.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


2065 Chart Operations

void OnStart()
{
//--- example of applying template, located in \MQL5\Files
if(FileIsExist("my_template.tpl"))
{
Print("The file my_template.tpl found in \Files'");
//--- apply template
if(ChartApplyTemplate(0,"\\Files\\my_template.tpl"))
{
Print("The template 'my_template.tpl' applied successfully");
//--- redraw chart
ChartRedraw();
}
else
Print("Failed to apply 'my_template.tpl', error code ",GetLastError());
}
else
{
Print("File 'my_template.tpl' not found in "
+TerminalInfoString(TERMINAL_PATH)+"\\MQL5\\Files");
}
}

See also
R esources

© 2000-2025, MetaQuotes Ltd.


2066 Chart Operations

ChartSaveTemplate
S aves current chart settings in a template with a specified name.
bool ChartSaveTemplate(
long chart_id, // Chart ID
const string filename // Filename to save the template
);

Parameters
chart_id
[in] Chart ID. 0 means the current chart.
filename
[in] The filename to save the template. The " .tpl" extension will be added to the filename
automatically; there is no need to specify it. The template is saved in
data_folder \Profiles \Templates \ and can be used for manual application in the terminal. If a
template with the same filename already exists, the contents of this file will be overwritten.

Return Value

If successful, the function returns true, otherwise it returns false. To get information about the
error, call the GetLastError() function.
Note

Using templates, you can save chart settings with all applied indicators and graphical objects, to
then apply it to another chart.
Example:

//+------------------------------------------------------------------+
//| Test_ChartSaveTemplate.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property script_show_inputs
//--- input parameters
input string symbol="GBPUSD"; // The symbol of a new chart
input ENUM_TIMEFRAMES period=PERIOD_H3; // The timeframe of a new chart
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- First attach indicators to the chart
int handle;
//--- Prepare the indicator for use

© 2000-2025, MetaQuotes Ltd.


2067 Chart Operations

if(!PrepareZigzag(NULL,0,handle)) return; // Failed, so exit


//--- Attach the indicator to the current chart, but in a separate window.
if(!ChartIndicatorAdd(0,1,handle))
{
PrintFormat("Failed to attach to chart %s/%s an indicator with the handle=%d. Error code %d",
_Symbol,
EnumToString(_Period),
handle,
GetLastError());
//--- Terminate the program operation
return;
}
//--- Refresh the chart to see the indicator
ChartRedraw();
//--- Find the last two last fractures of the zigzag
double two_values[];
datetime two_times[];
if(!GetLastTwoFractures(two_values,two_times,handle))
{
PrintFormat("Failed to find two last fractures in the Zigzag!");
//--- Terminate the program operation
return;
}
//--- Now attach a standard deviation channel
string channel="StdDeviation Channel";
if(!ObjectCreate(0,channel,OBJ_STDDEVCHANNEL,0,two_times[1],0))
{
PrintFormat("Failed to create object %s. Error code %d",
EnumToString(OBJ_STDDEVCHANNEL),GetLastError());
return;
}
else
{
//--- The channel has been created, define the second point
ObjectSetInteger(0,channel,OBJPROP_TIME,1,two_times[0]);
//--- Set a tooltip text for the channel
ObjectSetString(0,channel,OBJPROP_TOOLTIP,"Demo from MQL5 Help");
//--- Refresh the chart
ChartRedraw();
}
//--- Save the result in a template
ChartSaveTemplate(0,"StdDevChannelOnZigzag");
//--- Open a new chart and apply a saved template to it
long new_chart=ChartOpen(symbol,period);
//--- Enable tooltips for graphical objects
ChartSetInteger(new_chart,CHART_SHOW_OBJECT_DESCR,true);
if(new_chart!=0)
{
//--- Apply the saved template to a chart

© 2000-2025, MetaQuotes Ltd.


2068 Chart Operations

ChartApplyTemplate(new_chart,"StdDevChannelOnZigzag");
}
Sleep(10000);
}
//+------------------------------------------------------------------+
//| Creates a zigzag handle and ensures readiness of its data |
//+------------------------------------------------------------------+
bool PrepareZigzag(string sym,ENUM_TIMEFRAMES tf,int &h)
{
ResetLastError();
//--- The Zigzag indicator must be located in terminal_data_folder\MQL5\Examples
h=iCustom(sym,tf,"Examples\\Zigzag");
if(h==INVALID_HANDLE)
{
PrintFormat("%s: Failed to create the handle of the Zigzag indicator. Error code %d",
__FUNCTION__,GetLastError());
return false;
}
//--- When creating an indicator handle, it requires time to calculate values
int k=0; // The number of attempts to wait for the indicator calculation
//--- Wait for the calculation in a loop, pausing to 50 milliseconds if the calculation is not yet
while(BarsCalculated(h)<=0)
{
k++;
//--- Show the number of attempts
PrintFormat("%s: k=%d",__FUNCTION__,k);
//--- Wait 50 milliseconds to wait until the indicator is calculated
Sleep(50);
//--- If more than 100 attempt, then something is wrong
if(k>100)
{
//--- Report a problem
PrintFormat("Failed to calculate the indicator for %d attempts!");
//--- Terminate the program operation
return false;
}
}
//--- Everything is ready, the indicator is created and values are calculated
return true;
}
//+------------------------------------------------------------------+
//| Searches for the last 2 zigzag fractures and places to arrays |
//+------------------------------------------------------------------+
bool GetLastTwoFractures(double &get_values[],datetime &get_times[],int handle)
{
double values[]; // An array for the values of the zigzag
datetime times[]; // An array to get time
int size=100; // Size of the array
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


2069 Chart Operations

//--- Copy the last 100 values of the indicator


int copied=CopyBuffer(handle,0,0,size,values);
//--- Check the number of values copied
if(copied<100)
{
PrintFormat("%s: Failed to copy %d values of the indicator with the handle=%d. Error code %d"
__FUNCTION__,size,handle,GetLastError());
return false;
}
//--- Define the order of access to the array as in a timeseries
ArraySetAsSeries(values,true);
//--- Write here the numbers of bars, in which fractures were found
int positions[];
//--- Set array sizes
ArrayResize(get_values,3); ArrayResize(get_times,3); ArrayResize(positions,3);
//--- Counters
int i=0,k=0;
//--- Start to search for fractures
while(i<100)
{
double v=values[i];
//--- We are not interested in empty values
if(v!=0.0)
{
//--- Remember the bar number
positions[k]=i;
//--- Remember the value of a zigzag on the fracture
get_values[k]=values[i];
PrintFormat("%s: Zigzag[%d]=%G",__FUNCTION__,i,values[i]);
//--- Increase the counter
k++;
//--- If two fractures found, break the loop
if(k>2) break;
}
i++;
}
//--- Define the order of access to the arrays as in a timeseries
ArraySetAsSeries(times,true); ArraySetAsSeries(get_times,true);
if(CopyTime(_Symbol,_Period,0,size,times)<=0)
{
PrintFormat("%s: Failed to copy %d values from CopyTime(). Error code %d",
__FUNCTION__,size,GetLastError());
return false;
}
//--- Open the bar open time, on which the last 2 fractures occurred
get_times[0]=times[positions[1]];// The last but one value will be written as the first fracture
get_times[1]=times[positions[2]];// The value third from the end will be the second fracture
PrintFormat("%s: first=%s, second=%s",__FUNCTION__,TimeToString(get_times[1]),TimeToString(get_
//--- Successful

© 2000-2025, MetaQuotes Ltd.


2070 Chart Operations

return true;
}

See also
ChartApplyTemplate(), Resources

© 2000-2025, MetaQuotes Ltd.


2071 Chart Operations

ChartWindowFind
The function returns the number of a subwindow where an indicator is drawn. There are 2 variants of
the function.
1. The function searches in the indicated chart for the subwindow with the specified " short name" of
the indicator (the short name is displayed in the left top part of the subwindow), and it returns the
subwindow number in case of success.
int ChartWindowFind(
long chart_id, // chart identifier
string indicator_shortname // short indicator name, see INDICATOR_SHORTNAME

2. The function must be called from a custom indicator. It returns the number of the subwindow where
the indicator is working.
int ChartWindowFind();

Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
indicator_shortname
[in] S hort name of the indicator.

Return Value

S ubwindow number in case of success. In case of failure the function returns -1.
Note

If the second variant of the function (without parameters) is called from a script or Expert Advisor,
the function returns -1.
Don't mix up the short name of an indicator and a file name, which is specified when an indicator is
created using iCustom() and IndicatorCreate() functions. If the indicator's short name is not set
explicitly, then the name of the file containing the source code of the indicator, is specified in it
during compilation.
It is important to correctly form the short name of an indicator, which is recorded in the
INDICATOR_SHORTNAM E property using the IndicatorS etS tring() function. It is recommended that
the short name contains values of the indicator's input parameters, because the indicator deleted
from a chart in the ChartIndicatorDelete() function is identified by its short name.
Example:

#property script_show_inputs
//--- input parameters
input string shortname="MACD(12,26,9)";
//+------------------------------------------------------------------+
//| Returns number of the chart window with this indicator |
//+------------------------------------------------------------------+
int GetIndicatorSubWindowNumber(long chartID=0,string short_name="")

© 2000-2025, MetaQuotes Ltd.


2072 Chart Operations

{
int window=-1;
//---
if((ENUM_PROGRAM_TYPE)MQL5InfoInteger(MQL5_PROGRAM_TYPE)==PROGRAM_INDICATOR)
{
//--- the function is called from the indicator, name is not required
window=ChartWindowFind();
}
else
{
//--- the function is called from an Expert Advisor or script
window=ChartWindowFind(0,short_name);
if(window==-1) Print(__FUNCTION__+"(): Error = ",GetLastError());
}
//---
return(window);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int window=GetIndicatorSubWindowNumber(0,shortname);
if(window!=-1)
Print("Indicator "+shortname+" is in the window #"+(string)window);
else
Print("Indicator "+shortname+" is not found. window = "+(string)window);
}

See also
ObjectCreate(), ObjectFind()

© 2000-2025, MetaQuotes Ltd.


2073 Chart Operations

ChartTimePriceToXY
Converts the coordinates of a chart from the time/price representation to the X and Y coordinates.
bool ChartTimePriceToXY(
long chart_id, // Chart ID
int sub_window, // The number of the subwindow
datetime time, // Time on the chart
double price, // Price on the chart
int& x, // The X coordinate for the time on the chart
int& y // The Y coordinates for the price on the chart
);

Parameters
chart_id
[in] Chart ID. 0 means the current chart.
sub_window
[in] The number of the chart subwindow. 0 means the main chart window.
time
[in] The time value on the chart, for which the value in pixels along the X axis will be received.
The origin is in the upper left corner of the main chart window.
price
[in] The price value on the chart, for which the value in pixels along the Y axis will be received.
The origin is in the upper left corner of the main chart window.
x
[out] The variable, into which the conversion of time to X will be received.
y
[out] The variable, into which the conversion of price to Y will be received.

Return Value

R eturns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
Example:

#define BAR_NUMBER 0 // number of the bar we get the price and time from

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- copy data of a single bar by the BAR_NUMBER index
MqlRates rates[]={};
if(CopyRates(_Symbol, _Period, BAR_NUMBER, 1, rates)!=1)

© 2000-2025, MetaQuotes Ltd.


2074 Chart Operations

{
PrintFormat("CopyRates() failed for bar %d. Error %d", BAR_NUMBER, GetLastError());
return;
}

//--- convert the obtained price and time into chart pixel coordinates
int x=0, y=0;
ResetLastError();
if(!ChartTimePriceToXY(ChartID(), 0, rates[0].time, rates[0].close, x, y))
{
Print("ChartTimePriceToXY() failed. Error ", GetLastError());
return;
}

//--- print the obtained result in the journal


PrintFormat("For bar[%d] with opening time %s and price %.*f, the chart coordinates are x: %d, y

/*
result:
For bar[0] with opening time 2024.08.09 15:06 and price 1.27378, the chart coordinates are x: 78
*/
}

See also

ChartXYToTimePrice()

© 2000-2025, MetaQuotes Ltd.


2075 Chart Operations

ChartXYToTimePrice
Converts the X and Y coordinates on a chart to the time and price values.
bool ChartXYToTimePrice(
long chart_id, // Chart ID
int x, // The X coordinate on the chart
int y, // The Y coordinate on the chart
int& sub_window, // The number of the subwindow
datetime& time, // Time on the chart
double& price // Price on the chart
);

Parameters
chart_id
[in] Chart ID. 0 means the current chart.
x
[in] The X coordinate.
y
[in] The Y coordinate.
sub_window
[out] The variable, into which the chart subwindow number will be written. 0 means the main
chart window.
time
[out] The time value on the chart, for which the value in pixels along the X axis will be received.
The origin is in the upper left corner of the main chart window.
price
[out] The price value on the chart, for which the value in pixels along the Y axis will be received.
The origin is in the upper left corner of the main chart window.

Return Value

R eturns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
Example:

//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Show the event parameters on the chart

© 2000-2025, MetaQuotes Ltd.


2076 Chart Operations

Comment(__FUNCTION__,": id=",id," lparam=",lparam," dparam=",dparam," sparam=",sparam);


//--- If this is an event of a mouse click on the chart
if(id==CHARTEVENT_CLICK)
{
//--- Prepare variables
int x =(int)lparam;
int y =(int)dparam;
datetime dt =0;
double price =0;
int window=0;
//--- Convert the X and Y coordinates in terms of date/time
if(ChartXYToTimePrice(0,x,y,window,dt,price))
{
PrintFormat("Window=%d X=%d Y=%d => Time=%s Price=%G",window,x,y,TimeToString(dt),pric
//--- Perform reverse conversion: (X,Y) => (Time,Price)
if(ChartTimePriceToXY(0,window,dt,price,x,y))
PrintFormat("Time=%s Price=%G => X=%d Y=%d",TimeToString(dt),price,x,y);
else
Print("ChartTimePriceToXY return error code: ",GetLastError());
//--- delete lines
ObjectDelete(0,"V Line");
ObjectDelete(0,"H Line");
//--- create horizontal and vertical lines of the crosshair
ObjectCreate(0,"H Line",OBJ_HLINE,window,dt,price);
ObjectCreate(0,"V Line",OBJ_VLINE,window,dt,price);
ChartRedraw(0);
}
else
Print("ChartXYToTimePrice return error code: ",GetLastError());
Print("+--------------------------------------------------------------+");
}
}

See also
ChartTimePriceToXY()

© 2000-2025, MetaQuotes Ltd.


2077 Chart Operations

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 _TIM EFRAM ES values. 0 means the current
chart period.

Return Value

If successful, it returns the opened chart ID. Otherwise returns 0.


Note

The maximum possible number of simultaneously open charts in the terminal can't exceed the
CHARTS_M AX value.
Example:

#define CHART_SYMBOL NULL


#define CHART_PERIOD PERIOD_CURRENT

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set a new chart symbol and timeframe
string symbol=CHART_SYMBOL;
if(symbol==NULL)
symbol=Symbol();
ENUM_TIMEFRAMES timeframe = (CHART_PERIOD==PERIOD_CURRENT ? Period() : CHART_PERIOD);

//--- open a new chart with the specified symbol and period
long chart_id=ChartOpen(symbol, timeframe);
if(chart_id==0)
{
Print("ChartOpen() failed. Error ", GetLastError());
return;
}

© 2000-2025, MetaQuotes Ltd.


2078 Chart Operations

//--- print open chart parameters in the journal


PrintFormat("A new chart of the %s symbol has been opened with a period of %s and ChartID %I64u"
symbol, StringSubstr(EnumToString(timeframe), 7), chart_id);
/*
result:
A new chart of the GBPUSD symbol has been opened with a period of M1 and ChartID 133346697706632
*/
}

© 2000-2025, MetaQuotes Ltd.


2079 Chart Operations

ChartFirst
R eturns the ID of the first chart of the client terminal.
long ChartFirst();

Return Value

Chart ID.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the ID of the very first chart opened in the client terminal
long chart_id= ChartFirst();

//--- additionally get the chart symbol and period using the obtained ID
string symbol = ChartSymbol(chart_id);
ENUM_TIMEFRAMES period = ChartPeriod(chart_id);

//--- display the description of the client terminal first chart in the journal
PrintFormat("ID of the first chart of the client terminal: %I64d, chart symbol: %s, chart period
/*
result:
ID of the first chart of the client terminal: 133246248352168440, chart symbol: EURUSD, chart pe
*/
}

© 2000-2025, MetaQuotes Ltd.


2080 Chart Operations

ChartNext
R eturns 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" .

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

© 2000-2025, MetaQuotes Ltd.


2081 Chart Operations

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.

Return Value

If successful, returns true, otherwise false.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- open a new chart with the same symbol and period as the current one
long chart_id=ChartOpen(_Symbol, _Period);
if(chart_id==0)
{
Print("ChartOpen() failed. Error ", GetLastError());
return;
}

//--- print open chart parameters in the journal


PrintFormat("A new chart of the %s symbol has been opened with a period of %s and ChartID %I64u"
_Symbol, StringSubstr(EnumToString(_Period), 7), chart_id);

//--- wait two seconds and close the newly opened chart
PrintFormat("Waiting 3 seconds before closing a newly opened chart with ID %I64d ...", chart_id)
Sleep(3000);
ResetLastError();
if(!ChartClose(chart_id))
{
Print("ChartClose() failed. Error ", GetLastError());
return;
}

//--- print successful chart closure message in the journal


PrintFormat("The chart with ID %I64d was successfully closed", chart_id);
/*
result:
A new chart of the GBPUSD symbol has been opened with a period of M1 and ChartID 133346697706632

© 2000-2025, MetaQuotes Ltd.


2082 Chart Operations

Waiting 3 seconds before closing a newly opened chart with ID 133346697706632016 ...
The chart with ID 133346697706632016 was successfully closed
*/
}

© 2000-2025, MetaQuotes Ltd.


2083 Chart Operations

ChartSymbol
R eturns 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.

Return Value

If chart does not exist, the result will be an empty string.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the current chart symbol and display the obtained value in the journal
string chart_symbol = ChartSymbol();
Print("Current chart symbol: ", chart_symbol);

//--- take the existing (in this case, the current) chart ID
long chart_id=ChartID();
chart_symbol=ChartSymbol(chart_id);
PrintFormat("Chart symbol with ID %I64d: %s", chart_id, chart_symbol);

//--- set a random chart ID when receiving a symbol


chart_symbol = ChartSymbol(1234567890);
if(chart_symbol=="")
Print("The chart with ID 1234567890 does not exist");
else
Print("Chart symbol with ID 1234567890: ", chart_symbol);
/*
result:
Current chart symbol: GBPUSD
Chart symbol with ID 132966427583395104: GBPUSD
The chart with ID 1234567890 does not exist
*/
}

See also

ChartS etS ymbolPeriod

© 2000-2025, MetaQuotes Ltd.


2084 Chart Operations

ChartPeriod
R eturns 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.

Return Value

The function returns one of the ENUM _TIM EFRAM ES values. If chart does not exist, it returns 0.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the current chart period and display the obtained value in the journal
ENUM_TIMEFRAMES period=ChartPeriod();
Print("Current chart period: ", EnumToString(period));

//--- take the existing (in this case, the current) chart ID
long chart_id=ChartID();
period=ChartPeriod(chart_id);
PrintFormat("Chart period with ID %I64d: %s", chart_id, EnumToString(period));

//--- set a random chart ID


period=ChartPeriod(1234567890);
if(period==0)
Print("The chart with ID 1234567890 does not exist");
else
Print("Chart period with ID 1234567890: ", EnumToString(period));
/*
result:
Current chart period: PERIOD_M15
Chart period with ID 133510090240498505: PERIOD_M15
The chart with ID 1234567890 does not exist
*/
}

© 2000-2025, MetaQuotes Ltd.


2085 Chart Operations

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.


Example:

#define WIDTH 50 // rectangle width in bars

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the current chart ID and set the graphical object name
long chart_id = ChartID();
string obj_name = MQLInfoString(MQL_PROGRAM_NAME)+"_RectLabel";

//--- get two rectangle time coordinates


datetime time1 = iTime(_Symbol, _Period, WIDTH);
datetime time2 = iTime(_Symbol, _Period, 0);
if(time1==0 || time2==0)
{
Print("Error getting time ", GetLastError());
return;
}

//--- get the maximum and minimum prices in the range of the rectangle width
double price1 = HighestHigh(_Symbol, _Period, 0, WIDTH);
double price2 = LowestLow(_Symbol, _Period, 0, WIDTH);
if(price1==EMPTY_VALUE || price2==EMPTY_VALUE)
return;

//--- create a rectangle object


Print("Create a wheat-colored rectangle");
if(!ObjectCreate(chart_id, obj_name, OBJ_RECTANGLE, 0, time1, price1, time2, price2))
{
Print("ObjectCreate() failed. Error ", GetLastError());
return;

© 2000-2025, MetaQuotes Ltd.


2086 Chart Operations

//--- fill the rectangle with the original color


ObjectSetInteger(chart_id, obj_name, OBJPROP_FILL, true);
ObjectSetInteger(chart_id, obj_name, OBJPROP_BACK, true);
ObjectSetInteger(chart_id, obj_name, OBJPROP_COLOR, clrWheat);
ChartRedraw();

//--- wait a second, fill the rectangle with the DodgerBlue color and update the chart
Sleep(1000);
Print("Change color to DodgerBlue");
ObjectSetInteger(chart_id, obj_name, OBJPROP_COLOR, clrDodgerBlue);
ChartRedraw();

//--- wait a second, fill the rectangle with the LimeGreen color and update the chart
Sleep(1000);
Print("Change color to LimeGreen");
ObjectSetInteger(chart_id, obj_name, OBJPROP_COLOR, clrLimeGreen);
ChartRedraw();

//--- wait a second, fill the rectangle with the OrangeRed color and update the chart
Sleep(1000);
Print("Change color to OrangeRed");
ObjectSetInteger(chart_id, obj_name, OBJPROP_COLOR, clrOrangeRed);
ChartRedraw();

//--- wait a second, fill the rectangle with the Wheat color and update the chart
Sleep(1000);
Print("Reset color to original");
ObjectSetInteger(chart_id, obj_name, OBJPROP_COLOR, clrWheat);
ChartRedraw();

//--- after three seconds, remove the object from the chart
Sleep(3000);
Print("Delete the rectangle");
ObjectDelete(chart_id, obj_name);
}
//+------------------------------------------------------------------+
//| Return the maximum High in the specified range of bars |
//+------------------------------------------------------------------+
double HighestHigh(const string symbol, const ENUM_TIMEFRAMES timeframe, const uint start, const ui
{
ResetLastError();
int index=iHighest(symbol, timeframe, MODE_HIGH, count, start);
if(index==-1)
{
PrintFormat("%s: iHighest() failed. Error %d",__FUNCTION__, GetLastError());
return(EMPTY_VALUE);
}

© 2000-2025, MetaQuotes Ltd.


2087 Chart Operations

GetLastError();
double price=iHigh(symbol, timeframe, index);
if(price==0)
{
PrintFormat("%s: iHigh() failed. Error %d",__FUNCTION__, GetLastError());
return(EMPTY_VALUE);
}
return(price);
}
//+------------------------------------------------------------------+
//| Return the minimum Low in the specified range of bars |
//+------------------------------------------------------------------+
double LowestLow(const string symbol, const ENUM_TIMEFRAMES timeframe, const uint start, const uint
{
ResetLastError();
int index=iLowest(symbol, timeframe, MODE_LOW, count, start);
if(index==-1)
{
PrintFormat("%s: iLowest() failed. Error %d",__FUNCTION__, GetLastError());
return(EMPTY_VALUE);
}
GetLastError();
double price=iLow(symbol, timeframe, index);
if(price==0)
{
PrintFormat("%s: iLow() failed. Error %d",__FUNCTION__, GetLastError());
return(EMPTY_VALUE);
}
return(price);
}

See also

Objects functions

© 2000-2025, MetaQuotes Ltd.


2088 Chart Operations

ChartSetDouble
S etsa value for a corresponding property of the specified chart. Chart property should be of a double
type. The command is added to chart messages queue and will be executed after processing of all
previous commands.
bool ChartSetDouble(
long chart_id, // Chart ID
ENUM_CHART_PROPERTY_DOUBLE 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 _CHAR T _PR OPER T Y_DOUBL E values (except the
read-only properties).
value
[in] Property value.

Return Value

R eturnstrue if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
Note

The function is asynchronous, which means that the function does not wait for the execution of the
command, which has been successfully added to the queue of specified the chart. Instead, it
immediately returns control. The property will only change after the handling of the appropriate
command from the chart queue. To immediately execute commands from the chart queue, call the
ChartRedraw function.
If you want to immediately change several chart properties at once, then the corresponding
functions (ChartS etS tring, ChartS etDouble, ChartS etS tring) should be executed in one code block,
after which you should call ChartRedraw once.
To check the command execution result, you can use a function, which requests the specified chart
property (ChartGetInteger, ChartGetDouble, ChartS etS tring). However, note that these functions
are synchronous and wait for execution results.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the current chart ID
long chart_id = ChartID();

© 2000-2025, MetaQuotes Ltd.


2089 Chart Operations

//--- save the initial offset of the zero bar from the right edge in percentage and the auto scroll
double shift = ChartGetDouble(chart_id, CHART_SHIFT_SIZE);
bool scroll= ChartGetInteger(chart_id,CHART_AUTOSCROLL);

//--- reset the auto scroll chart flag


ChartSetInteger(chart_id, CHART_AUTOSCROLL, true);
PrintFormat("Initial chart shift size: %.2f", shift);

//--- in the loop from 2.0% to 50.0% with the step of 0.5%
for(int i=20; i<=500; i+=5)
{
//--- set the shift size as i / 10 and print the specified value in the journal
ChartSetDouble(chart_id, CHART_SHIFT_SIZE, i/10.0);
PrintFormat("Set chart shift size to %.1f%%", i/10.0);

//--- keep the chart zero bar at the specified shift distance
ChartNavigate(chart_id, CHART_END, 0);

//--- wait a bit


Sleep(16);
}

//--- set the initial chart shift and auto scroll


Print("Set the chart shift size to the initial value of ", shift);
ChartSetDouble(ChartID(), CHART_SHIFT_SIZE, shift);
ChartSetInteger(chart_id, CHART_AUTOSCROLL, scroll);
}

© 2000-2025, MetaQuotes Ltd.


2090 Chart Operations

ChartSetInteger
S ets a value for a corresponding property of the specified chart. Chart property must be
datetime, int, color, bool or char. The command is added to chart messages queue and will be
executed after processing of all previous commands.
bool ChartSetInteger(
long chart_id, // Chart ID
ENUM_CHART_PROPERTY_INTEGER prop_id, // Property ID
long value // Value
);

S ets a value for a corresponding property of the specified subwindow.


bool ChartSetInteger(
long chart_id, // Chart ID
ENUM_CHART_PROPERTY_INTEGER prop_id, // Property ID
int sub_window, // Subwindow number
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).
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.
value
[in] Property value.

Return Value

R eturnstrue if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
Note

The function is asynchronous, which means that the function does not wait for the execution of the
command, which has been successfully added to the queue of specified the chart. Instead, it
immediately returns control. The property will only change after the handling of the appropriate
command from the chart queue. To immediately execute commands from the chart queue, call the
ChartRedraw function.
If you want to immediately change several chart properties at once, then the corresponding
functions (ChartS etS tring, ChartS etDouble, ChartS etS tring) should be executed in one code block,
after which you should call ChartRedraw once.

© 2000-2025, MetaQuotes Ltd.


2091 Chart Operations

To check the command execution result, you can use a function, which requests the specified chart
property (ChartGetInteger, ChartGetDouble, ChartS etS tring). However, note that these functions
are synchronous and wait for execution results.
Example:

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- Enabling events of mouse movements on the chart window
ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,1);
//--- Forced updating of chart properties ensures readiness for event processing
ChartRedraw();
}
//+------------------------------------------------------------------+
//| MouseState |
//+------------------------------------------------------------------+
string MouseState(uint state)
{
string res;
res+="\nML: " +(((state& 1)== 1)?"DN":"UP"); // mouse left
res+="\nMR: " +(((state& 2)== 2)?"DN":"UP"); // mouse right
res+="\nMM: " +(((state&16)==16)?"DN":"UP"); // mouse middle
res+="\nMX: " +(((state&32)==32)?"DN":"UP"); // mouse first X key
res+="\nMY: " +(((state&64)==64)?"DN":"UP"); // mouse second X key
res+="\nSHIFT: "+(((state& 4)== 4)?"DN":"UP"); // shift key
res+="\nCTRL: " +(((state& 8)== 8)?"DN":"UP"); // control key
return(res);
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
{
if(id==CHARTEVENT_MOUSE_MOVE)
Comment("POINT: ",(int)lparam,",",(int)dparam,"\n",MouseState((uint)sparam));
}

© 2000-2025, MetaQuotes Ltd.


2092 Chart Operations

ChartSetString
S etsa value for a corresponding property of the specified chart. Chart property must be of the string
type. The command is added to chart messages queue and will be executed after processing of all
previous commands.
bool ChartSetString(
long chart_id, // Chart ID
ENUM_CHART_PROPERTY_STRING 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. Its value can be one of the ENUM _CHAR T _PR OPER T Y_S T R ING values
(except the read-only properties).
str_value
[in] Property value string. S tring length cannot exceed 2045 characters (extra characters will be
truncated).

Return Value

R eturnstrue if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
Note

ChartS etS tring can be used for a comment output on the chart instead of the Comment function.
The function is asynchronous, which means that the function does not wait for the execution of the
command, which has been successfully added to the queue of specified the chart. Instead, it
immediately returns control. The property will only change after the handling of the appropriate
command from the chart queue. To immediately execute commands from the chart queue, call the
ChartRedraw function.
If you want to immediately change several chart properties at once, then the corresponding
functions (ChartS etS tring, ChartS etDouble, ChartS etS tring) should be executed in one code block,
after which you should call ChartRedraw once.
To check the command execution result, you can use a function, which requests the specified chart
property (ChartGetInteger, ChartGetDouble, ChartS etS tring). However, note that these functions
are synchronous and wait for execution results.
Example:

void OnTick()
{
//---
double Ask,Bid;

© 2000-2025, MetaQuotes Ltd.


2093 Chart Operations

int Spread;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);
string comment=StringFormat("Display prices:\nAsk = %G\nBid = %G\nSpread = %d",
Ask,Bid,Spread);
ChartSetString(0,CHART_COMMENT,comment);
}

See also
Comment, ChartGetS tring

© 2000-2025, MetaQuotes Ltd.


2094 Chart Operations

ChartGetDouble
R eturnsthe value of a corresponding property of the specified chart. Chart property must be of double
type. There are 2 variants of the function calls.
1. R eturns the property value directly.
double ChartGetDouble(
long chart_id, // Chart ID
ENUM_CHART_PROPERTY_DOUBLE prop_id, // Property ID
int sub_window=0 // subwindow number, if necessary
);

2. R eturns 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
ENUM_CHART_PROPERTY_DOUBLE 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.

Return 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().
Note

The function is synchronous, which means that it waits for the execution of all the commands that
have been added to the chart queue prior to its call.
Example:

void OnStart()

© 2000-2025, MetaQuotes Ltd.


2095 Chart Operations

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

© 2000-2025, MetaQuotes Ltd.


2096 Chart Operations

ChartGetInteger
R eturnsthe 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. R eturns the property value directly.
long ChartGetInteger(
long chart_id, // Chart ID
ENUM_CHART_PROPERTY_INTEGER prop_id, // Property ID
int sub_window=0 // subwindow number, if necessary
);

2. R eturns 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
ENUM_CHART_PROPERTY_INTEGER prop_id, // Property ID
int sub_window=0 // 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 _CHAR T _PR OPER T Y_INT EGER 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.

Return 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().
Note

The function is synchronous, which means that it waits for the execution of all the commands that
have been added to the chart queue prior to its call.
Example:

void OnStart()

© 2000-2025, MetaQuotes Ltd.


2097 Chart Operations

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

© 2000-2025, MetaQuotes Ltd.


2098 Chart Operations

ChartGetString
R eturnsthe 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. R eturns the property value directly.
string ChartGetString(
long chart_id, // Chart ID
ENUM_CHART_PROPERTY_STRING prop_id // Property ID
);

2. R eturns 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
ENUM_CHART_PROPERTY_STRING 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 _CHAR T _PR OPER T Y_S T R ING values.
string_var
[out] Target variable of string type for the requested property.

Return 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

ChartGetS tring can be used for reading comments plotted on the chart using the Comment or
ChartS etS tring functions.
The function is synchronous, which means that it waits for the execution of all the commands that
have been added to the chart queue prior to its call.
Example:

void OnStart()
{
ChartSetString(0,CHART_COMMENT,"Test comment.\nSecond line.\nThird!");
ChartRedraw();

© 2000-2025, MetaQuotes Ltd.


2099 Chart Operations

Sleep(1000);
string comm=ChartGetString(0,CHART_COMMENT);
Print(comm);
}

See also
Comment, ChartS etS tring

© 2000-2025, MetaQuotes Ltd.


2100 Chart Operations

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
ENUM_CHART_POSITION 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_POS ITION values.
shift=0
[in] Number of bars to shift the chart. Positive value means the right shift (to the end of chart),
negative value means the left shift (to the beginning of chart). The zero shift can be used to
navigate to the beginning or end of chart.

Return Value

R eturns true if successful, otherwise returns false.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get handle of the current chart
long handle=ChartID();
string comm="";
if(handle>0) // if successful, additionally set up the chart
{
//--- disable auto scroll
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
//--- set a shift from the right chart border
ChartSetInteger(handle,CHART_SHIFT,true);
//--- draw candlesticks
ChartSetInteger(handle,CHART_MODE,CHART_CANDLES);
//--- set the display mode for tick volumes
ChartSetInteger(handle,CHART_SHOW_VOLUMES,CHART_VOLUME_TICK);

//--- prepare a text to output in Comment()


comm="Scroll 10 bars to the right of the history start";
//--- show comment

© 2000-2025, MetaQuotes Ltd.


2101 Chart Operations

Comment(comm);
//--- scroll 10 bars to the right of the history start
ChartNavigate(handle,CHART_BEGIN,10);
//--- get the number of the first bar visible on the chart (numeration like in timeseries)
long first_bar=ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0);
//--- add line feed character
comm=comm+"\r\n";
//--- add to comment
comm=comm+"The first bar on the chart is number "+IntegerToString(first_bar)+"\r\n";
//--- show comment
Comment(comm);
//--- wait 5 seconds to see how the chart moves
Sleep(5000);

//--- add to the comment text


comm=comm+"\r\n"+"Scroll 10 bars to the left of the right chart border";
Comment(comm);
//--- scroll 10 bars to the left of the right chart border
ChartNavigate(handle,CHART_END,-10);
//--- get the number of the first bar visible on the chart (numeration like in timeseries)
first_bar=ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0);
comm=comm+"\r\n";
comm=comm+"The first bar on the chart is number "+IntegerToString(first_bar)+"\r\n";
Comment(comm);
//--- wait 5 seconds to see how the chart moves
Sleep(5000);

//--- new block of chart scrolling


comm=comm+"\r\n"+"Scroll 300 bars to the right of the history start";
Comment(comm);
//--- scroll 300 bars to the right of the history start
ChartNavigate(handle,CHART_BEGIN,300);
first_bar=ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0);
comm=comm+"\r\n";
comm=comm+"The first bar on the chart is number "+IntegerToString(first_bar)+"\r\n";
Comment(comm);
//--- wait 5 seconds to see how the chart moves
Sleep(5000);

//--- new block of chart scrolling


comm=comm+"\r\n"+"Scroll 300 bars to the left of the right chart border";
Comment(comm);
//--- scroll 300 bars to the left of the right chart border
ChartNavigate(handle,CHART_END,-300);
first_bar=ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0);
comm=comm+"\r\n";
comm=comm+"The first bar on the chart is number "+IntegerToString(first_bar)+"\r\n";
Comment(comm);
}

© 2000-2025, MetaQuotes Ltd.


2102 Chart Operations

© 2000-2025, MetaQuotes Ltd.


2103 Chart Operations

ChartID
R eturns the ID of the current chart.
long ChartID();

Return Value

Value of long type.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- variables for chart identifiers
long curr_chart=ChartFirst();
int i=0;
//--- print the first chart data in the journal
PrintFormat("Chart[%d] ID: %I64d, symbol: %s", i, curr_chart, ChartSymbol(curr_chart));

//--- until the open chart limit is reached (CHARTS_MAX)


while(!IsStopped() && i < CHARTS_MAX)
{
//--- increase the chart counter
i++;
//--- get the next chart ID based on the previous one
curr_chart=ChartNext(curr_chart);

//--- terminate the loop if the end of the chart list is reached
if(curr_chart<0)
break;

//--- print the next chart data in the journal


PrintFormat("Chart[%d] ID: %I64d, symbol: %s", i, curr_chart, ChartSymbol(curr_chart));
}
/*
result:
Chart[0] ID: 133246248352168440, symbol: EURUSD
Chart[1] ID: 133346697706632015, symbol: USDJPY
Chart[2] ID: 133246248352168439, symbol: GBPUSD
Chart[3] ID: 133346697706632009, symbol: RU000A103661
Chart[4] ID: 133346697706632010, symbol: AEM4
Chart[5] ID: 133346697706632011, symbol: AA.SPB
Chart[6] ID: 133346697706632012, symbol: ALLFUTMIX
Chart[7] ID: 133346697706632013, symbol: EURUSD
Chart[8] ID: 133346697706632014, symbol: SBER
*/

© 2000-2025, MetaQuotes Ltd.


2104 Chart Operations

© 2000-2025, MetaQuotes Ltd.


2105 Chart Operations

ChartIndicatorAdd
Adds an indicator with the specified handle into a specified chart window. Indicator and chart should
be generated on the same symbol and time frame.
bool ChartIndicatorAdd(
long chart_id, // chart ID
int sub_window // number of the sub-window
int indicator_handle // handle of the indicator
);

Parameters
chart_id
[in] Chart ID. 0 means the current chart.
sub_window
[in]The number of the chart sub-window. 0 means the main chart window. To add an indicator in
a new window, the parameter must be one greater than the index of the last existing window, i.e.
equal to CHART_W INDOWS_TOTAL. If the value of the parameter is greater than
CHART_W INDOWS_TOTAL, a new window will not be created, and the indicator will not be added.
indicator_handle
[in] The handle of the indicator.

Return Value

The function returns true in case of success, otherwise it returns false. In order to obtain
information about the error, call the GetLastError() function. Error 4114 means that a chart and an
added indicator differ by their symbol or time frame.
Note

If an indicator that should be drawn in a separate subwindow (for example, built-in iM ACD or a
custom indicator with specified #property indicator_separate_window property) is applied to the
main chart window, it may not be visible though it will still be present in the list of indicators. This
means that the scale of the indicator is different from the scale of the price chart, and applied
indicator's values do not fit in the displayed range of the price chart. In this case, GetLastError()
returns zero code indicating the absence of an error. The values of such " invisible" indicator can be
seen in Data W indow and received from other MQL5 applications.
Example:

#property description "Expert Advisor demonstrating the work with ChartIndicatorAdd() function."
#property description "After launching on the chart (and receiving the error in Journal), open"
#property description "the Expert Advisor's properties and specify correct <symbol> and <period> pa
#property description "MACD indicator will be added on the chart."

//--- input parameters


input string symbol="AUDUSD"; // symbol name
input ENUM_TIMEFRAMES period=PERIOD_M12; // time frame
input int fast_ema_period=12; // fast MACD period
input int slow_ema_period=26; // slow MACD period

© 2000-2025, MetaQuotes Ltd.


2106 Chart Operations

input int signal_period=9; // signal period


input ENUM_APPLIED_PRICE apr=PRICE_CLOSE; // price type for MACD calculation

int indicator_handle=INVALID_HANDLE;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
indicator_handle=iMACD(symbol,period,fast_ema_period,slow_ema_period,signal_period,apr);
//--- try to add the indicator on the chart
if(!AddIndicator())
{
//--- AddIndicator() function refused to add the indicator on the chart
int answer=MessageBox("Do you want to add MACD on the chart anyway?",
"Incorrect symbol and/or time frame for adding the indicator",
MB_YESNO // "Yes" and "No" selection buttons will be shown
);
//--- if a user still insists on incorrect usage of ChartIndicatorAdd()
if(answer==IDYES)
{
//--- first of all, a Journal entry will be made about that
PrintFormat("Attention! %s: Trying to add MACD(%s/%s) indicator on %s/%s chart. Receiving
__FUNCTION__,symbol,EnumToString(period),_Symbol,EnumToString(_Period));
//--- receive the number of a new subwindow, to which we will try to add the indicator
int subwindow=(int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);
//--- now make an attempt resulting in error
if(!ChartIndicatorAdd(0,subwindow,indicator_handle))
PrintFormat("Failed to add MACD indicator on %d chart window. Error code %d",
subwindow,GetLastError());
}
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Expert Advisor performs nothing
}
//+------------------------------------------------------------------+
//| Function for checking and adding the indicator on the chart |
//+------------------------------------------------------------------+
bool AddIndicator()
{
//--- displayed message

© 2000-2025, MetaQuotes Ltd.


2107 Chart Operations

string message;
//--- check if the indicator symbol and chart symbol match each other
if(symbol!=_Symbol)
{
message="Displaying the use of Demo_ChartIndicatorAdd() function:";
message=message+"\r\n";
message=message+"Unable to add the indicator calculated on another symbol on the chart.";
message=message+"\r\n";
message=message+"Specify the chart symbol in Expert Advisor's property - "+_Symbol+".";
Alert(message);
//--- premature exit, the indicator will not be added on the chart
return false;
}
//--- check if the indicator's and chart's time frames match each other
if(period!=_Period)
{
message="Unable to add the indicator calculated on another time frame on the chart.";
message=message+"\r\n";
message=message+"Specify the chart time frame in Expert Advisor properties - "+EnumToString(_
Alert(message);
//--- premature exit, the indicator will not be added on the chart
return false;
}
//--- all checks completed, symbol and indicator time frame match the chart
if(indicator_handle==INVALID_HANDLE)
{
Print(__FUNCTION__," Creating MACD indicator");
indicator_handle=iMACD(symbol,period,fast_ema_period,slow_ema_period,signal_period,apr);
if(indicator_handle==INVALID_HANDLE)
{
Print("Failed to create MACD indicator. Error code ",GetLastError());
}
}
//--- reset the error code
ResetLastError();
//--- apply the indicator to the chart
Print(__FUNCTION__," Adding MACD indicator on the chart");
Print("MACD is generated on ",symbol,"/",EnumToString(period));
//--- receive the number of a new subwindow, to which MACD indicator is added
int subwindow=(int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);
PrintFormat("Adding MACD indicator on %d chart window",subwindow);
if(!ChartIndicatorAdd(0,subwindow,indicator_handle))
{
PrintFormat("Failed to add MACD indicator on %d chart window. Error code %d",
subwindow,GetLastError());
}
//--- Indicator added successfully
return(true);
}

© 2000-2025, MetaQuotes Ltd.


2108 Chart Operations

See Also
ChartIndicatorDelete(), ChartIndicatorName(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate()

© 2000-2025, MetaQuotes Ltd.


2109 Chart Operations

ChartIndicatorDelete
R emoves an indicator with a specified name from the specified chart window.
bool ChartIndicatorDelete(
long chart_id, // chart id
int sub_window // number of the subwindow
const string indicator_shortname // short name of the indicator
);

Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
const indicator_shortname
[in] The short name of the indicator which is set in the INDICATOR_SHORTNAM E property with the
IndicatorS etS tring() function. To get the short name of an indicator use the ChartIndicatorName()
function.

Return Value

R eturns true in case of successful deletion of the indicator. Otherwise it returns false. To get error
details use the GetLastError() function.
Note

If two indicators with identical short names exist in the chart subwindow, the first one in a row will
be deleted.
If other indicators on this chart are based on the values of the indicator that is being deleted, such
indicators will also be deleted.
Do not confuse the indicator short name and the file name that is specified when creating an
indicator using functions iCustom() and IndicatorCreate(). If the short name of an indicator is not
set explicitly, then the name of the file containing the source code of the indicator will be specified
during compilation.
Deletion ofan indicator from a chart doesn't mean that its calculation part will be deleted from the
terminal memory. To release the indicator handle use the IndicatorRelease() function.
The indicator's short name should be formed correctly. It will be written to the
INDICATOR_SHORTNAM E property using the IndicatorS etS tring() function. It is recommended that
the short name should contain values of all the input parameters of the indicator, because the
indicator to be deleted from the chart by the ChartIndicatorDelete() function is identified by the
short name.
Example of deleting an indicator after initialization has failed:

//+------------------------------------------------------------------+
//| Demo_ChartIndicatorDelete.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |

© 2000-2025, MetaQuotes Ltd.


2110 Chart Operations

//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
//--- plot Histogram
#property indicator_label1 "Histogram"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int first_param=1;
input int second_param=2;
input int third_param=3;
input bool wrong_init=true;
//--- indicator buffers
double HistogramBuffer[];
string shortname;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
int res=INIT_SUCCEEDED;
//--- Link the HistogramBuffer array to the indicator buffer
SetIndexBuffer(0,HistogramBuffer,INDICATOR_DATA);
//--- Construct a short indicator name based on input parameters
shortname=StringFormat("Demo_ChartIndicatorDelete(%d,%d,%d)",
first_param,second_param,third_param);
IndicatorSetString(INDICATOR_SHORTNAME,shortname);
//--- If forced completion of an indicator is set, return a non-zero value
if(wrong_init) res=INIT_FAILED;
return(res);
}
//+------------------------------------------------------------------+
//| 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[],

© 2000-2025, MetaQuotes Ltd.


2111 Chart Operations

const long &volume[],


const int &spread[])
{
//--- Starting position for working in a loop
int start=prev_calculated-1;
if(start<0) start=0;
//--- Fill in the indicator buffer with values
for(int i=start;i<rates_total;i++)
{
HistogramBuffer[i]=close[i];
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| A handler of the Deinit event |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
PrintFormat("%s: Deinitialization reason code=%d",__FUNCTION__,reason);
if(reason==REASON_INITFAILED)
{
PrintFormat("An indicator with a short name %s (file %s) deletes itself from the chart",short
int window=ChartWindowFind();
bool res=ChartIndicatorDelete(0,window,shortname);
//--- Analyse the result of call of ChartIndicatorDelete()
if(!res)
{
PrintFormat("Failed to delete indicator %s from window #%d. Error code %d",
shortname,window,GetLastError());
}
}
}

See also
ChartIndicatorAdd(), ChartIndicatorName(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate(),
IndicatorS etS tring()

© 2000-2025, MetaQuotes Ltd.


2112 Chart Operations

ChartIndicatorGet
R eturns the handle of the indicator with the specified short name in the specified chart window.
int ChartIndicatorGet(
long chart_id, // Chart ID
int sub_window // The number of the subwindow
const string indicator_shortname // Short name of the indicator
);

Parameters
chart_id
[in] Chart ID. 0 means the current chart.
sub_window
[in] The number of the chart subwindow. 0 means the main chart window.
const indicator_shortname
[in] The short name if the indicator, which is set in the INDICATOR_SHORTNAM E property using
the IndicatorS etS tring() function. To get the short name of an indicator, use the
ChartIndicatorName() function.

Return Value

R eturnsan indicator handle if successful, otherwise returns INVALID_HANDLE. To get information


about the error, call the GetLastError() function.
Note

The indicator handle obtained using the ChartIndicatorGet() function increases the internal indicator
usage counter. The terminal runtime system keeps all indicators, whose counter is greater than
zero, loaded. Therefore, the indicator handle that is no longer needed should be immediately and
explicitly released using IndicatorRelease() in the same program that received it, as shown in the
example below. Otherwise, it will be impossible to find the “abandoned” handle and release it from
another program correctly.
W hen creating an indicator, be careful forming its short name, which is written in the
INDICATOR_SHORTNAM E property using the IndicatorS etS tring() function. It is recommended that a
short name should contain the values of input parameters of the indicator, since the indicator is
identified in the ChartIndicatorGet() function based on its short name.
Another way to identify the indicator is to get a list of its parameters for a given handle using the
IndicatorParameters() function and then to analyze the obtained values.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- The number of windows on the chart (at least one main window is always present)
int windows=(int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);

© 2000-2025, MetaQuotes Ltd.


2113 Chart Operations

//--- Check all windows


for(int w=0;w<windows;w++)
{
//--- the number of indicators in this window/subwindow
int total=ChartIndicatorsTotal(0,w);
//--- Go through all indicators in the window
for(int i=0;i<total;i++)
{
//--- get the short name of an indicator
string name=ChartIndicatorName(0,w,i);
//--- get the handle of an indicator
int handle=ChartIndicatorGet(0,w,name);
//--- Add to log
PrintFormat("Window=%d, index=%d, name=%s, handle=%d",w,i,name,handle);
//--- You should obligatorily release the indicator handle when it is no longer needed
IndicatorRelease(handle);
}
}
}

See also
ChartIndicatorAdd(), ChartIndicatorName(), ChartIndicatorsTotal(), IndicatorParameters()

© 2000-2025, MetaQuotes Ltd.


2114 Chart Operations

ChartIndicatorName
R eturns the short name of the indicator by the number in the indicators list on the specified chart
window.
string ChartIndicatorName(
long chart_id, // chart id
int sub_window // number of the subwindow
int index // index of the indicator in the list of indicators added to the chart subw
);

Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
index
[in] the index of the indicator in the list of indicators. The numeration of indicators start with
zero, i.e. the first indicator in the list
has the 0 index. To obtain the number of indicators in the
list use the ChartIndicatorsTotal() function.

Return Value

The short name of the indicator which is set in the INDICATOR_SHORTNAM E property with the
IndicatorS etS tring() function. To get error details use the GetLastError() function.
Note

Do not confuse the indicator short name and the file name that is specified when creating an
indicator using functions iCustom() and IndicatorCreate(). If the short name of an indicator is not
set explicitly, then the name of the file containing the source code of the indicator will be specified
during compilation.
The indicator's short name should be formed correctly. It will be written to the
INDICATOR_SHORTNAM E property using the IndicatorS etS tring() function. It is recommended that
the short name should contain values of all the input parameters of the indicator, because the
indicator to be deleted from the chart by the ChartIndicatorDelete() function is identified by the
short name.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the current chart ID and the number of its subwindows, including the main window
long chart_id = ChartID();
int wnd_total= (int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);

© 2000-2025, MetaQuotes Ltd.


2115 Chart Operations

//--- iterate over all current chart windows in a loop


for(int w=0; w<wnd_total; w++)
{
//--- get the number of indicators attached to the chart window specified by the loop index
int ind_total=ChartIndicatorsTotal(chart_id, w);

//--- print the header for the selected chart window


PrintFormat("Chart window %d indicators: ", w);

//--- get in the loop and write to the variable all the names of indicators attached to the s
string ind_names="";
for(int i=0; i<ind_total; i++)
{
ind_names+=" "+ChartIndicatorName(chart_id, w, i)+(i<ind_total-1 ? "\n": "");
}
//--- print the obtained list of names of all indicators, attached to the specified chart win
Print(ind_names);
}
/*
result:
Chart window 0 indicators:
AMA(9,2,30)
SAR(0.02,0.20)
Fractals
Chart window 1 indicators:
RSI(14)
AMA(9,2,30)
Chart window 2 indicators:
MFI(14)
*/
}

See also

ChartIndicatorAdd(), ChartIndicatorDelete(), ChartIndicatorsTotal(), iCustom(), IndicatorCreate(),


IndicatorS etS tring()

© 2000-2025, MetaQuotes Ltd.


2116 Chart Operations

ChartIndicatorsTotal
R eturns the number of all indicators applied to the specified chart window.
int ChartIndicatorsTotal(
long chart_id, // chart id
int sub_window // number of the subwindow
);

Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.

Return Value

The number of indicators in the specified chart window. To get error details use the GetLastError()
function.
Note

The function allows going searching through all the indicators attached to the chart. The number of
all the windows of the chart can be obtained from the CHART_W INDOWS_TOTAL property using the
ChartGetInteger() function.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the current chart ID and the number of its subwindows, including the main window
long chart_id = ChartID();
int wnd_total= (int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);

//--- iterate over all current chart windows in a loop


for(int w=0; w<wnd_total; w++)
{
//--- get the number of indicators attached to the chart window specified by the loop index
int ind_total=ChartIndicatorsTotal(chart_id, w);

//--- get the number of indicators attached to the specified chart window
PrintFormat("Chart ID %I64d, subwindow %d. Attached indicators: %d", chart_id, w, ind_total);
}
/*
result:
Chart ID 133246248352168439, subwindow 0. Attached indicators: 3
Chart ID 133246248352168439, subwindow 1. Attached indicators: 2

© 2000-2025, MetaQuotes Ltd.


2117 Chart Operations

Chart ID 133246248352168439, subwindow 2. Attached indicators: 1


*/
}

See also

ChartIndicatorAdd(), ChartIndicatorDelete(), iCustom(), IndicatorCreate(), IndicatorS etS tring()

© 2000-2025, MetaQuotes Ltd.


2118 Chart Operations

ChartWindowOnDropped
R eturns the number (index) of the chart subwindow the Expert Advisor or script has been dropped to.
0 means the main chart window.

int ChartWindowOnDropped();

Return 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

© 2000-2025, MetaQuotes Ltd.


2119 Chart Operations

ChartPriceOnDropped
R eturnsthe price coordinate corresponding to the chart point the Expert Advisor or script has been
dropped to.
double ChartPriceOnDropped();

Return Value

Value of double type.


Example:

double p=ChartPriceOnDropped();
Print("ChartPriceOnDropped() = ",p);

See also
ChartXOnDropped, ChartYOnDropped

© 2000-2025, MetaQuotes Ltd.


2120 Chart Operations

ChartTimeOnDropped
R eturnsthe time coordinate corresponding to the chart point the Expert Advisor or script has been
dropped to.
datetime ChartTimeOnDropped();

Return Value

Value of datetime type.


Example:

datetime t=ChartTimeOnDropped();
Print("Script was dropped on the "+t);

See also
ChartXOnDropped, ChartYOnDropped

© 2000-2025, MetaQuotes Ltd.


2121 Chart Operations

ChartXOnDropped
R eturns the X coordinate of the chart point the Expert Advisor or script has been dropped to.
int ChartXOnDropped();

Return 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
ChartW indowOnDropped, ChartPriceOnDropped, ChartTimeOnDropped

© 2000-2025, MetaQuotes Ltd.


2122 Chart Operations

ChartYOnDropped
R eturns the Y coordinateof the chart point the Expert Advisor or script has been dropped to.
int ChartYOnDropped();

Return Value

The Y coordinate value.


Note

Y axis direction from top to bottom.


Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get and print the X and Y coordinates of the chart point the script was dropped into using th
int x=ChartXOnDropped();
int y=ChartYOnDropped();
PrintFormat("Script dropped to coordinates X = %d, Y = %d", x, y);
/*
result:
Script dropped to coordinates X = 429, Y = 114
*/
}

See also

ChartW indowOnDropped, ChartPriceOnDropped, ChartTimeOnDropped

© 2000-2025, MetaQuotes Ltd.


2123 Chart Operations

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. The command is added to chart messages
queue and will be executed after processing of all previous commands.

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 _TIM EFRAM ES values. 0 means the current
chart period.

Return Value

R eturnstrue if the command has been added to chart queue, otherwise false. To get an information
about the error, call the GetLastError() function.
Note

The symbol/period change leads to the re-initialization of the Expert Advisor attached to a chart.
The call of ChartS etS ymbolPeriod with the same symbol and timeframe can be used to update the
chart (similar to the terminal's Refresh command). In its turn, the chart update triggers re-
calculation of the indicators attached to it. Thus, you are able to calculate an indicator on the chart
even if there are no ticks (e.g., on weekends).
Example:

#define SYMBOL "GBPUSD"


#define PERIOD PERIOD_H1

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the current chart ID, symbol and period
long chart_id= ChartID();
string symbol = Symbol();
ENUM_TIMEFRAMES period = Period();

© 2000-2025, MetaQuotes Ltd.


2124 Chart Operations

//--- report in the journal on replacing the current chart symbol and period with the ones set in S
PrintFormat("Change the %s symbol and the %s period of the chart %I64u to %s %s",
symbol, TimeframeDescrioption(period), chart_id, SYMBOL, TimeframeDescrioption(PERIO

//--- change the chart symbol and period


ChartSetSymbolPeriod(chart_id, SYMBOL, PERIOD);
/*
result:
Change the EURUSD symbol and the M1 period of the chart 133246248352168440 to GBPUSD H1
*/
}
//+------------------------------------------------------------------+
//| Return the chart period description |
//+------------------------------------------------------------------+
string TimeframeDescrioption(const ENUM_TIMEFRAMES timeframe)
{
return(StringSubstr(EnumToString(timeframe), 7));
}

See also

ChartS ymbol, ChartPeriod

© 2000-2025, MetaQuotes Ltd.


2125 Chart Operations

ChartScreenShot
The function provides a screenshot of the chart in its current state in the GIF, PNG or BMP format
depending on specified extension.
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] S creenshot file name. Cannot exceed 63 characters. S creenshot files are placed in the \Files
directory.
width
[in] S creenshot width in pixels.

height
[in] S creenshot height in pixels.

align_mode=ALIGN_RIGHT
[in] Output mode of a narrow screenshot. A value of the ENUM _ALIGN_MODE enumeration.
ALIGN_R IGH T means align to the right margin (the output from the end). ALIGN_L EFT means Left
justify.

Return Value

R eturns 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.
Example:

#property description "The Expert Advisor demonstrates how to create a series of screenshots of the
#property description "chart using the ChartScreenShot() function. For convenience, the file name i
#property description "shown on the chart. The height and width of images is defined through macros

#define WIDTH 800 // Image width to call ChartScreenShot()


#define HEIGHT 600 // Image height to call ChartScreenShot()

© 2000-2025, MetaQuotes Ltd.


2126 Chart Operations

//--- input parameters


input int pictures=5; // The number of images in the series
int mode=-1; // -1 denotes a shift to the right edge of the chart, 1 - to the left
int bars_shift=300;// The number of bars when scrolling the chart using ChartNavigate()
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- Disable chart autoscroll
ChartSetInteger(0,CHART_AUTOSCROLL,false);
//--- Set the shift of the right edge of the chart
ChartSetInteger(0,CHART_SHIFT,true);
//--- Show a candlestick chart
ChartSetInteger(0,CHART_MODE,CHART_CANDLES);
//---
Print("Preparation of the Expert Advisor is completed");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---

}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Show the name of the function, call time and event identifier
Print(__FUNCTION__,TimeCurrent()," id=",id," mode=",mode);
//--- Handle the CHARTEVENT_CLICK event ("A mouse click on the chart")
if(id==CHARTEVENT_CLICK)
{
//--- Initial shift from the chart edge
int pos=0;
//--- Operation with the left chart edge
if(mode>0)
{
//--- Scroll the chart to the left edge
ChartNavigate(0,CHART_BEGIN,pos);
for(int i=0;i<pictures;i++)
{
//--- Prepare a text to show on the chart and a file name

© 2000-2025, MetaQuotes Ltd.


2127 Chart Operations

string name="ChartScreenShot"+"CHART_BEGIN"+string(pos)+".gif";
//--- Show the name on the chart as a comment
Comment(name);
//--- Save the chart screenshot in a file in the terminal_directory\MQL5\Files\
if(ChartScreenShot(0,name,WIDTH,HEIGHT,ALIGN_LEFT))
Print("We've saved the screenshot ",name);
//---
pos+=bars_shift;
//--- Give the user time to look at the new part of the chart
Sleep(3000);
//--- Scroll the chart from the current position bars_shift bars to the right
ChartNavigate(0,CHART_CURRENT_POS,bars_shift);
}
//--- Change the mode to the opposite
mode*=-1;
}
else // Operation with the right chart edge
{
//--- Scroll the chart to the right edge
ChartNavigate(0,CHART_END,pos);
for(int i=0;i<pictures;i++)
{
//--- Prepare a text to show on the chart and a file name
string name="ChartScreenShot"+"CHART_END"+string(pos)+".gif";
//--- Show the name on the chart as a comment
Comment(name);
//--- Save the chart screenshot in a file in the terminal_directory\MQL5\Files\
if(ChartScreenShot(0,name,WIDTH,HEIGHT,ALIGN_RIGHT))
Print("We've saved the screenshot ",name);
//---
pos+=bars_shift;
//--- Give the user time to look at the new part of the chart
Sleep(3000);
//--- Scroll the chart from the current position bars_shift bars to the right
ChartNavigate(0,CHART_CURRENT_POS,-bars_shift);
}
//--- Change the mode to the opposite
mode*=-1;
}
} // End of CHARTEVENT_CLICK event handling
//--- End of the OnChartEvent() handler
}

See also
ChartNavigate(), Resources

© 2000-2025, MetaQuotes Ltd.


2128 Trade Functions

Trade Functions
This is the group of functions intended for managing trading activities.

Before you proceed to study the trade functions of the platform, you must have a clear understanding
of the basic terms: order, deal and position:

· An order is an instruction given to a broker to buy or sell a financial instrument. There are two main
types of orders : Market and Pending. In addition, there are special Take Profit and S top Loss levels.
· A deal is the commercial exchange (buying or selling) of a financial security. Buying is executed at
the demand price (As k), and S ell is performed at the supply price (Bid). A deal can be opened as a
result of market order execution or pending order triggering. Note that in some cases, execution of
an order can result in several deals.
· A position is a trade obligation, i.e. the number of bought or sold contracts of a financial
instrument. A long position is financial security bought expecting the security price go higher. A
short position is an obligation to supply a security expecting the price will fall in future.
General information about trading operations is available in the client terminal help.
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.
Trading can be allowed or prohibited depending on various factors described in the Trade Permission
section.

Function Action

OrderCalcMargin Calculates the margin required for the specified order type, in the
deposit currency
OrderCalcProfit Calculates the profit based on the parameters passed, in the deposit
currency
OrderCheck Checks if there are enough funds to execute the required trade
operation.
OrderS end S ends trade requests to a server
OrderS endAsync Asynchronously sends trade requests without waiting for the trade
response of the trade server
PositionsTotal R eturns the number of open positions
PositionGetS ymbol R eturns the symbol corresponding to the open position
PositionS elect Chooses an open position for further working with it
PositionS electByTicket S elects a position to work with by the ticket number specified in it
PositionGetDouble R eturns the requested property of an open position (double)
PositionGetInteger R eturns the requested property of an open position (datetime or int)
PositionGetS tring R eturns the requested property of an open position (string)

© 2000-2025, MetaQuotes Ltd.


2129 Trade Functions

Function Action

PositionGetTicket R eturnsthe ticket of the position with the specified index in the list
of open positions
OrdersTotal R eturns the number of orders
OrderGetTicket R eturn the tick et of a corresponding order
OrderS elect S elects a order for further working with it
OrderGetDouble R eturns the requested property of the order (double)
OrderGetInteger R eturns the requested property of the order (datetime or int)
OrderGetS tring R eturns the requested property of the order (string)
H istoryS elect R etrieves the history of transactions and orders for the specified
period of the server time
H istoryS electByPosition R equests the history of deals with a specified position identifier.
H istoryOrderS elect S elects an order in the history for further working with it
H istoryOrdersTotal R eturns the number of orders in the history
H istoryOrderGetTick et R eturn order ticket of a corresponding order in the history
H istoryOrderGetDouble R eturns the requested property of an order in the history (double)
H istoryOrderGetInteger R eturns the requested property of an order in the history (datetime
or int)
H istoryOrderGetS tring R eturns the requested property of an order in the history (string)
H istoryDealS elect S electsa deal in the history for further calling it through appropriate
functions
H istoryDealsTotal R eturns the number of deals in the history
H istoryDealGetTick et R eturns a ticket of a corresponding deal in the history
H istoryDealGetDouble R eturns the requested property of a deal in the history (double)
H istoryDealGetInteger R eturns the requested property of a deal in the history (datetime or
int)
H istoryDealGetS tring R eturns the requested property of a deal in the history (string)

© 2000-2025, MetaQuotes Ltd.


2130 Trade Functions

OrderCalcMargin
The function calculates the margin required for the specified order type, on the current account, in the
current market environment not taking into account current pending orders and open positions. It
allows the evaluation of margin for the trade operation planned. The value is returned in the account
currency.
bool OrderCalcMargin(
ENUM_ORDER_TYPE action, // type of order
string symbol, // symbol name
double volume, // volume
double price, // open price
double& margin // variable for obtaining the margin value
);

Parameters
action
[in] The order type, can be one of the values of the ENUM _ORDER_TYPE enumeration.
symbol
[in] S ymbol name.

volume
[in] Volume of the trade operation.
price
[in] Open price.
margin
[out] The variable, to which the value of the required margin will be written in case the function
is successfully executed. The calculation is performed as if there were no pending orders and open
positions on the current account. The margin value depends on many factors, and can differ in
different market environments.

Return Value

The function returns true in case of success ; otherwise it returns false. In order to obtain
information about the error, call the GetLastError() function.
Example:

#define VOLUME 1.0 // order volume


#define DEVIATION 100 // distance for setting a pending order
#define STOP_LIMIT 50 // order StopLimit distance

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string currency=AccountInfoString(ACCOUNT_CURRENCY);

© 2000-2025, MetaQuotes Ltd.


2131 Trade Functions

int array_types[8]={ORDER_TYPE_BUY,
ORDER_TYPE_SELL,
ORDER_TYPE_BUY_LIMIT,
ORDER_TYPE_SELL_LIMIT,
ORDER_TYPE_BUY_STOP,
ORDER_TYPE_SELL_STOP,
ORDER_TYPE_BUY_STOP_LIMIT,
ORDER_TYPE_SELL_STOP_LIMIT };

//--- in a loop by the order type array


for(int i=0; i<(int)array_types.Size(); i++)
{
//--- depending on the order type, get ORDER_TYPE_BUY or ORDER_TYPE_SELL type
ENUM_ORDER_TYPE type=MarketOrderByOrderType((ENUM_ORDER_TYPE)array_types[i]);

//--- depending on the order type, get the price


double price=PriceByOrderType(_Symbol, type);

//--- get the amount of margin required for the order type specified in 'action'
double margin=EMPTY_VALUE;
ResetLastError();
if(!OrderCalcMargin(type, _Symbol, VOLUME, price, margin))
{
Print("OrderCalcMargin() failed. Error ",GetLastError());
continue;
}
//--- print the result in the journal
PrintFormat("Margin required for %.2f %s order at price %.*f on %s symbol: %.2f %s", VOLUME,
}
/*
result:
Margin required for 1.00 Buy order at price 1.31668 on GBPUSD symbol: 1316.68 USD
Margin required for 1.00 Sell order at price 1.31661 on GBPUSD symbol: 1316.61 USD
Margin required for 1.00 Buy Limit order at price 1.31568 on GBPUSD symbol: 1315.68 USD
Margin required for 1.00 Sell Limit order at price 1.31761 on GBPUSD symbol: 1317.61 USD
Margin required for 1.00 Buy Stop order at price 1.31768 on GBPUSD symbol: 1317.68 USD
Margin required for 1.00 Sell Stop order at price 1.31561 on GBPUSD symbol: 1315.61 USD
Margin required for 1.00 Buy Stop Limit order at price 1.31718 on GBPUSD symbol: 1317.18 USD
Margin required for 1.00 Sell Stop Limit order at price 1.31611 on GBPUSD symbol: 1316.11 USD
*/
}
//+------------------------------------------------------------------+
//| Return the Buy or Sell order type |
//+------------------------------------------------------------------+
ENUM_ORDER_TYPE MarketOrderByOrderType(ENUM_ORDER_TYPE type)
{
switch(type)
{
case ORDER_TYPE_BUY : case ORDER_TYPE_BUY_LIMIT : case ORDER_TYPE_BUY_STOP : case ORDER_TY

© 2000-2025, MetaQuotes Ltd.


2132 Trade Functions

return(ORDER_TYPE_BUY);
case ORDER_TYPE_SELL : case ORDER_TYPE_SELL_LIMIT : case ORDER_TYPE_SELL_STOP : case ORDER_TY
return(ORDER_TYPE_SELL);
}
return(WRONG_VALUE);
}
//+------------------------------------------------------------------+
//| Return open price by order type |
//+------------------------------------------------------------------+
double PriceByOrderType(const string symbol, const ENUM_ORDER_TYPE order_type)
{
int digits=0;
double point=0;
MqlTick tick={};

//--- get the symbol Point value


ResetLastError();
if(!SymbolInfoDouble(symbol, SYMBOL_POINT, point))
{
Print("SymbolInfoDouble() failed. Error ", GetLastError());
return 0;
}

//--- get the symbol Digits value


long value=0;
if(!SymbolInfoInteger(symbol, SYMBOL_DIGITS, value))
{
Print("SymbolInfoInteger() failed. Error ", GetLastError());
return 0;
}
digits=(int)value;

//--- get the last prices by symbol


if(!SymbolInfoTick(symbol, tick))
{
Print("SymbolInfoTick() failed. Error ", GetLastError());
return 0;
}

//--- return the price depending on the order type


switch(order_type)
{
case ORDER_TYPE_BUY : return(tick.ask);
case ORDER_TYPE_SELL : return(tick.bid);
case ORDER_TYPE_BUY_LIMIT : return(NormalizeDouble(tick.ask - DEVIATION * point, digi
case ORDER_TYPE_SELL_LIMIT : return(NormalizeDouble(tick.bid + DEVIATION * point, digi
case ORDER_TYPE_BUY_STOP : return(NormalizeDouble(tick.ask + DEVIATION * point, digi
case ORDER_TYPE_SELL_STOP : return(NormalizeDouble(tick.bid - DEVIATION * point, digi
case ORDER_TYPE_BUY_STOP_LIMIT : return(NormalizeDouble(tick.ask + DEVIATION * point - STO

© 2000-2025, MetaQuotes Ltd.


2133 Trade Functions

case ORDER_TYPE_SELL_STOP_LIMIT : return(NormalizeDouble(tick.bid - DEVIATION * point + STO


default : return(0);
}
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE order_type)
{
switch(order_type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
case ORDER_TYPE_BUY_LIMIT : return("Buy Limit");
case ORDER_TYPE_SELL_LIMIT : return("Sell Limit");
case ORDER_TYPE_BUY_STOP : return("Buy Stop");
case ORDER_TYPE_SELL_STOP : return("Sell Stop");
case ORDER_TYPE_BUY_STOP_LIMIT : return("Buy Stop Limit");
case ORDER_TYPE_SELL_STOP_LIMIT : return("Sell Stop Limit");
case ORDER_TYPE_CLOSE_BY : return("Close By");
default : return("Unknown order type");
}
}
//+------------------------------------------------------------------+

See also
OrderS end(), Order Properties, Trade Operation Types

© 2000-2025, MetaQuotes Ltd.


2134 Trade Functions

OrderCalcProfit
The function calculates the profit for the current account, in the current market conditions, based on
the parameters passed. The function is used for pre-evaluation of the result of a trade operation. The
value is returned in the account currency.
bool OrderCalcProfit(
ENUM_ORDER_TYPE action, // type of the order (ORDER_TYPE_BUY or ORDER_TYPE_SELL)
string symbol, // symbol name
double volume, // volume
double price_open, // open price
double price_close, // close price
double& profit // variable for obtaining the profit value
);

Parameters
action
[in] Type of the order, can be one of the two values of the ENUM _ORDER_T YPE enumeration:
ORDER_TYPE_BUY or ORDER_TYPE_SELL.
symbol
[in] S ymbol name.

volume
[in] Volume of the trade operation.
price_open
[in] Open price.
price_close
[in] Close price.
profit
[out] The variable, to which the calculated value of the profit will be written in case the function
is successfully executed. The estimated profit value depends on many factors, and can differ in
different market environments.

Return Value

The function returns true in case of success ; otherwise it returns false. If an invalid order type is
specified, the function will return false. In order to obtain information about the error, call
GetLastError().

Example:

#define VOLUME 1.0 // order volume


#define DEVIATION 100 // number of points before the close price

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


2135 Trade Functions

void OnStart()
{
string currency_profit=SymbolInfoString(_Symbol,SYMBOL_CURRENCY_PROFIT); // profit currency
double close_price=ChartPriceOnDropped(); // the price coordinate, corresponding to the point wh

//---
for(int i=0; i<=ORDER_TYPE_SELL; i++)
{
ENUM_ORDER_TYPE order_type=(ENUM_ORDER_TYPE)i; // order type: 0 - Buy, 1 - Se
double open_price=PriceOpenByOrderType(_Symbol, order_type); // open price: for Buy - Ask,

//--- if the open price is not received, continue the loop


if(open_price==0)
continue;

//--- if the close price is zero (the script was not launched by dragging onto the chart), ca
if(close_price==0)
close_price=(order_type==ORDER_TYPE_BUY ? open_price + DEVIATION * _Point : open_price - D

//--- calculate the approximate profit size for the current account and market environment ba
double profit=0;
ResetLastError();
if(!OrderCalcProfit(order_type, _Symbol, VOLUME, open_price, close_price, profit))
{
Print("OrderCalcProfit() failed. Error ", GetLastError());
continue;
}

//--- print the received profit value in the journal


PrintFormat("Estimated profit for %.2f %s position on %s with opening price of %.*f and closi
VOLUME, OrderTypeDescription(order_type), _Symbol, _Digits, open_price, _Digits,

}
/*
result:
Estimated profit for 1.00 Buy position on EURUSD with opening price of 1.10757 and closing price
Estimated profit for 1.00 Sell position on EURUSD with opening price of 1.10753 and closing pric
*/
}
//+------------------------------------------------------------------+
//| Return open price by order type |
//+------------------------------------------------------------------+
double PriceOpenByOrderType(const string symbol, const ENUM_ORDER_TYPE order_type)
{
MqlTick tick={};

//--- get the last prices by symbol


if(!SymbolInfoTick(symbol, tick))
{

© 2000-2025, MetaQuotes Ltd.


2136 Trade Functions

Print("SymbolInfoTick() failed. Error ", GetLastError());


return 0;
}

//--- return the price depending on the order type


switch(order_type)
{
case ORDER_TYPE_BUY : return(tick.ask);
case ORDER_TYPE_SELL : return(tick.bid);
default : return(0);
}
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE order_type)
{
switch(order_type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
default : return("Unknown order type");
}
}

See also
OrderS end(), Order Properties, Trade Operation Types

© 2000-2025, MetaQuotes Ltd.


2137 Trade Functions

OrderCheck
The OrderCheck() function checks if there are enough money to execute a required trade operation.
The check results are placed to the fields of the M qlTradeCheckResult structure.
bool OrderCheck(
MqlTradeRequest& request, // request structure
MqlTradeCheckResult& result // result structure
);

Parameters
request
[in] Pointer to the structure of the M qlTradeRequest type, which describes the required trade
action.
result
[in,out] Pointer to the structure of the M qlTradeCheckResult type, to which the check result will
be placed.

Return Value

If funds are not enough for the operation, or parameters are filled out incorrectly, the function
returns false. In case of a successful basic check of structures (check of pointers), it returns true.
However, this is not an indication that the requested trade operation is sure to be successfully
executed . For a more detailed description of the function execution result, analyze the fields of the
result structure.
In order to obtain information about the error, call the GetLastError() function.
Example:

#define DEVIATION 5 // allowed deviation from the price


#define VOLUME 1.0 // order volume
#define EXPERT_MAGIC 123 // MagicNumber
#define DIRECTION ORDER_TYPE_BUY // opened position direction (ORDER_TYPE_BUY or ORDER_TYPE_S

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the request, verification and result structures
MqlTradeRequest request={};
MqlTradeCheckResult check ={};
MqlTradeResult result ={};

//--- prepare trade request parameters


PrepareRequest(_Symbol, DIRECTION, VOLUME, request);

//--- check trade request parameters


ResetLastError();

© 2000-2025, MetaQuotes Ltd.


2138 Trade Functions

bool res=OrderCheck(request, check);


if(!res)
{
PrintFormat("Trade request verification completed with error %d\nServer retcode: %u, comment:
return;
}

//--- trade request check was successful - display the description of the trade request verificatio
Print("Trade request verification completed successfully");
MqlTradeCheckResultPrint(check, 14);

//--- send a trade request


if(!OrderSend(request, result))
Print("OrderSend error ", GetLastError()); // if unable to send the request, display the e

//--- information about the operation


PrintFormat("Trade request result: retcode=%u, deal=%I64u, order=%I64u", result.retcode, result.
/*
result with disabled auto trading in the client terminal:
Trade request verification completed with error 4752
Server retcode: 10027, comment: AutoTrading disabled by client

enable auto trading and check again on a closed market:


Experts automated trading is enabled
Trade request verification completed successfully
Retcode: 0
Balance: 10779.50 USD
Equity: 10779.50 USD
Profit: 0.00 USD
Margin: 1104.79 USD
Margin free: 9674.71 USD
Margin level: 975.71 %
Comment: Done
OrderSend error 4756
Trade request result: retcode=10018, deal=0, order=0

check on the open market:


Trade request verification completed successfully
Retcode: 0
Balance: 10779.50 USD
Equity: 10779.50 USD
Profit: 0.00 USD
Margin: 110.46 USD
Margin free: 10669.04 USD
Margin level: 9758.74 %
Comment: Done
Trade request result: retcode=10009, deal=2777010968, order=2802818813
*/
}

© 2000-2025, MetaQuotes Ltd.


2139 Trade Functions

//+------------------------------------------------------------------+
//| Prepare parameters for a trade request |
//+------------------------------------------------------------------+
void PrepareRequest(const string symbol, const ENUM_ORDER_TYPE order_type, const double volume, Mql
{
ENUM_ORDER_TYPE type=(DIRECTION !=ORDER_TYPE_BUY ? ORDER_TYPE_SELL : DIRECTION);
double price=(DIRECTION==ORDER_TYPE_BUY ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDou
//--- request parameters
request.action = TRADE_ACTION_DEAL; // trading operation type
request.symbol = symbol; // symbol
request.volume = volume; // volume
request.type = type; // order type
request.price = price; // open price
request.deviation = DEVIATION; // allowed deviation from the price
request.magic = EXPERT_MAGIC; // order MagicNumber
}
//+------------------------------------------------------------------+
//| Print the fields of the trade request |
//| verification result in the journal |
//+------------------------------------------------------------------+
void MqlTradeCheckResultPrint(const MqlTradeCheckResult &check, const uint header_width=0)
{
//--- get the account currency and the number of decimal places for the account currency
string currency=AccountInfoString(ACCOUNT_CURRENCY);
int digits =(int)AccountInfoInteger(ACCOUNT_CURRENCY_DIGITS);

//--- define the header text and the width of the header field
//--- if the header width is passed to the function equal to zero, then the width will be the size
string header="Retcode:";
uint w=(header_width==0 ? header.Length()+1 : header_width);
//--- display the return code with the header of the specified width in the journal
PrintFormat("%-*s%-u", w, header, check.retcode);

//--- display the balance value after executing a trade operation in the journal
header="Balance:";
w=(header_width==0 ? header.Length()+1 : header_width);
PrintFormat("%-*s%-.*f %s", w, header, digits, check.balance, currency);

//--- display the equity value after executing a trade operation in the journal
header="Equity:";
w=(header_width==0 ? header.Length()+1 : header_width);
PrintFormat("%-*s%-.*f %s", w, header, digits, check.equity, currency);

//--- display the floating profit value after executing a trading operation in the journal
header="Profit:";
w=(header_width==0 ? header.Length()+1 : header_width);
PrintFormat("%-*s%-.*f %s", w, header, digits, check.profit, currency);

//--- display the amount of margin, required for the necessary trading operation, in the journal

© 2000-2025, MetaQuotes Ltd.


2140 Trade Functions

header="Margin:";
w=(header_width==0 ? header.Length()+1 : header_width);
PrintFormat("%-*s%-.*f %s", w, header, digits, check.margin, currency);

//--- display the value of equity to be left after conducting a trading operation in the journal
header="Margin free:";
w=(header_width==0 ? header.Length()+1 : header_width);
PrintFormat("%-*s%-.*f %s", w, header, digits, check.margin_free, currency);

//--- display the margin level to be set after completing the required trading operation in the jou
header="Margin level:";
w=(header_width==0 ? header.Length()+1 : header_width);
PrintFormat("%-*s%-.2f %%", w, header, check.margin_level);

//--- display the comment on the response code and error description in the journal
header="Comment:";
w=(header_width==0 ? header.Length()+1 : header_width);
PrintFormat("%-*s%-s", w, header, check.comment);
}

See also
OrderS end(), Trade Operation Types, Trade Request S tructure, S tructure of Request Check Results,
S tructure of a Trade R equest R esult

© 2000-2025, MetaQuotes Ltd.


2141 Trade Functions

OrderSend
The OrderS end() function is used for executing trade operations by sending requests to a trade server.
bool OrderSend(
MqlTradeRequest& request, // query structure
MqlTradeResult& result // structure of the answer
);

Parameters
request
[in] Pointer to a structure of M qlTradeRequest type describing the trade activity of the client.
result
[in,out] Pointer to a structure of M qlTradeResult type describing the result of trade operation in
case of a successful completion (if true is returned).

Return Value

In case of a successful basic check of structures (index checking) returns true. However, 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

The trade requests go through several stages of checking on a trade server. First of all, it checks if
all the required fields of the request parameter are filled out correctly. If there are no errors, the
server accepts the order for further processing. If the order is successfully accepted by the trade
server, the OrderS end() function returns true.
It is recommended to check the request before sending it to a trade server. To check requests, use
the OrderCheck() function. It checks if there are enough funds to execute the trade operation, and
returns many useful parameters in the results of trade request checking:
· return code containing information about errors in the check ed request;
· balance value that will appear after the trade operation is executed;
· equity value that will appear after the trade operation is executed;
· floating point value that will appear after the trade operation is executed;
· margin required for the trade operation;
· amount of free equity that will remain after the execution of the trade operation;
· the margin level that will be set after the trade operation is executed;
· comment to the reply code, error description.

W hen sending a mark et order (M qlTradeR equest.action=T RADE_ACTION_DEAL), the successful result
of the OrderS end() function does not mean that the order has been executed (appropriate trades
have been performed). In this case, 'true' means only that the order has been successfully placed in
the trading system for further execution. The trade server can fill in the deal or order field values in
the returned result structure, if it is aware of these data when forming a response to an OrderS end()

call. Generally, event(s) of executing trades corresponding to an order may happen after sending a
response to the OrderS end() call. Therefore, for any type of a trade request, when receiving the
OrderS end() execution result, we should first check the retcode trade server response code and the

© 2000-2025, MetaQuotes Ltd.


2142 Trade Functions

retcode_external external system response code (if necessary) available in the obtained result
structure.
Each accepted order is stored on the trade server awaiting processing until one of the conditions for
its execution occurs :
· expiration,
· appearance of an opposite request,
· order execution when the execution price appears,
· a request to cancel the order is received.
At the moment of the order processing, the trade server sends to the terminal a message about the
occurrence of the Trade event, which can be processed by the OnTrade() function.
The result of executing the trade request on a server sent by OrderS end() function can be tracked by
OnTradeTransaction handler. It should be noted that OnTradeTransaction handler will be called
several times when executing one trade request.
For example, when sending a market buy order, it is handled, an appropriate buy order is created
for the account, the order is then executed and removed from the list of the open ones, then it is
added to the orders history, an appropriate deal is added to the history and a new position is
created. OnTradeTransaction function will be called for each of these events.
Example:

//--- value for ORDER_MAGIC


input long order_magic=55555;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- make sure that the account is demo
if(AccountInfoInteger(ACCOUNT_TRADE_MODE)==ACCOUNT_TRADE_MODE_REAL)
{
Alert("Script operation is not allowed on a live account!");
return;
}
//--- place or delete order
if(GetOrdersTotalByMagic(order_magic)==0)
{
//--- no current orders - place an order
uint res=SendRandomPendingOrder(order_magic);
Print("Return code of the trade server ",res);
}
else // there are orders - delete orders
{
DeleteAllOrdersByMagic(order_magic);
}
//---
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


2143 Trade Functions

//| Receives the current number of orders with specified ORDER_MAGIC |


//+------------------------------------------------------------------+
int GetOrdersTotalByMagic(long const magic_number)
{
ulong order_ticket;
int total=0;
//--- go through all pending orders
for(int i=0;i<OrdersTotal();i++)
if((order_ticket=OrderGetTicket(i))>0)
if(magic_number==OrderGetInteger(ORDER_MAGIC)) total++;
//---
return(total);
}
//+------------------------------------------------------------------+
//| Deletes all pending orders with specified ORDER_MAGIC |
//+------------------------------------------------------------------+
void DeleteAllOrdersByMagic(long const magic_number)
{
ulong order_ticket;
//--- go through all pending orders
for(int i=OrdersTotal()-1;i>=0;i--)
if((order_ticket=OrderGetTicket(i))>0)
//--- order with appropriate ORDER_MAGIC
if(magic_number==OrderGetInteger(ORDER_MAGIC))
{
MqlTradeResult result={};
MqlTradeRequest request={};
request.order=order_ticket;
request.action=TRADE_ACTION_REMOVE;
OrderSend(request,result);
//--- write the server reply to log
Print(__FUNCTION__,": ",result.comment," reply code ",result.retcode);
}
//---
}
//+------------------------------------------------------------------+
//| Sets a pending order in a random way |
//+------------------------------------------------------------------+
uint SendRandomPendingOrder(long const magic_number)
{
//--- prepare a request
MqlTradeRequest request={};
request.action=TRADE_ACTION_PENDING; // setting a pending order
request.magic=magic_number; // ORDER_MAGIC
request.symbol=_Symbol; // symbol
request.volume=0.1; // volume in 0.1 lots
request.sl=0; // Stop Loss is not specified
request.tp=0; // Take Profit is not specified
//--- form the order type

© 2000-2025, MetaQuotes Ltd.


2144 Trade Functions

request.type=GetRandomType(); // order type


//--- form the price for the pending order
request.price=GetRandomPrice(request.type); // open price
//--- send a trade request
MqlTradeResult result={};
OrderSend(request,result);
//--- write the server reply to log
Print(__FUNCTION__,":",result.comment);
if(result.retcode==10016) Print(result.bid,result.ask,result.price);
//--- return code of the trade server reply
return result.retcode;
}
//+------------------------------------------------------------------+
//| Returns type of a pending order in a random way |
//+------------------------------------------------------------------+
ENUM_ORDER_TYPE GetRandomType()
{
int t=MathRand()%4;
//--- 0<=t<4
switch(t)
{
case(0):return(ORDER_TYPE_BUY_LIMIT);
case(1):return(ORDER_TYPE_SELL_LIMIT);
case(2):return(ORDER_TYPE_BUY_STOP);
case(3):return(ORDER_TYPE_SELL_STOP);
}
//--- incorrect value
return(WRONG_VALUE);
}
//+------------------------------------------------------------------+
//| Returns price in a random way |
//+------------------------------------------------------------------+
double GetRandomPrice(ENUM_ORDER_TYPE type)
{
int t=(int)type;
//--- stop levels for the symbol
int distance=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
//--- receive data of the last tick
MqlTick last_tick={};
SymbolInfoTick(_Symbol,last_tick);
//--- calculate price according to the type
double price;
if(t==2 || t==5) // ORDER_TYPE_BUY_LIMIT or ORDER_TYPE_SELL_STOP
{
price=last_tick.bid; // depart from price Bid
price=price-(distance+(MathRand()%10)*5)*_Point;
}
else // ORDER_TYPE_SELL_LIMIT or ORDER_TYPE_BUY_STOP
{

© 2000-2025, MetaQuotes Ltd.


2145 Trade Functions

price=last_tick.ask; // depart from price Ask


price=price+(distance+(MathRand()%10)*5)*_Point;
}
//---
return(price);
}

See also
Trade Operation Types, Trade Request S tructure, S tructure of Request Check Results, S tructure of a
Trade Request Result

© 2000-2025, MetaQuotes Ltd.


2146 Trade Functions

OrderSendAsync
The OrderS endAsync() function is used for conducting asynchronous trade operations without waiting
for the trade server's response to a sent request. The function is designed for high-frequency trading,
when under the terms of the trading algorithm it is unacceptable to waste time waiting for a response
from the server.
bool OrderSendAsync(
MqlTradeRequest& request, // Request structure
MqlTradeResult& result // Response structure
);

Parameters
request
[in] A pointer to a structure of the M qlTradeRequest type that describes the trade action of the
client.
result
[in,out] A pointer to a structure of the M qlTradeResult type that describes the result of a trade
operation in case of successful execution of the function (if true is returned).

Return Value

R eturns true if the request is sent to a trade server. In case the request is not sent, it returns false.
In case the request is sent, in the result variable the response code contains
TRADE_RETCODE_PLACED value (code 10008) – " order placed" . S uccessful execution means only the
fact of sending, but does not give any guarantee that the request has reached the trade server and
has been accepted for processing. W hen processing the received request, a trade server sends a
reply to a client terminal notifying of change in the current state of positions, orders and deals,
which leads to the generation of the Trade event.
The result of executing the trade request on a server sent by OrderS endAsync() function can be
tracked by OnTradeTransaction handler. It should be noted that OnTradeTransaction handler will be
called several times when executing one trade request.
For example, when sending a market buy order, it is handled, an appropriate buy order is created
for the account, the order is then executed and removed from the list of the open ones, then it is
added to the orders history, an appropriate deal is added to the history and a new position is
created. OnTradeTransaction function will be called for each of these events. To get such a data,
the function parameters should be analyzed:
· trans - this parameter gets M qlTradeTransaction structure describing a trade transaction applied
to a trade account;
· request - this parameter gets M qlTradeR equest structure describing the trade request resulted in
a trade transaction;
· result - this parameter gets M qlTradeR esult structure describing a trade request execution result.

Note

In terms of purposes and parameters, the function is similar to OrderS end(), but unlike it, it is
asynchronous, i.e. does not hold the program operation while waiting for the function execution
result. You can compare the rate of trade operations of these two functions using the sample Expert
Advisor.

© 2000-2025, MetaQuotes Ltd.


2147 Trade Functions

Example:

#property description "Expert Advisor for sending trade requests "


" using OrderSendAsync() function.\r\n"
#property description "Handling trading events using"
" OnTrade() and OnTradeTransaction() handler functions is displayed\r\n"
#property description "Expert Advisor parameters allow setting Magic Number"
" (unique ID) "
#property description "and the mode of displaying messages in Experts log. All details are displaye
//--- input parameters
input int MagicNumber=1234567; // Expert Advisor ID
input bool DescriptionModeFull=true; // Detailed output mode
//--- variable for using in HistorySelect() call
datetime history_start;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- check if autotrading is allowed
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
{
Alert("Autotrading in the terminal is disabled, Expert Advisor will be removed.");
ExpertRemove();
return(-1);
}
//--- unable to trade on a real account
if(AccountInfoInteger(ACCOUNT_TRADE_MODE)==ACCOUNT_TRADE_MODE_REAL)
{
Alert("Expert Advisor cannot trade on a real account!");
ExpertRemove();
return(-2);
}
//--- check if it is possible to trade on this account (for example, trading is impossible when usi
if(!AccountInfoInteger(ACCOUNT_TRADE_ALLOWED))
{
Alert("Trading on this account is disabled");
ExpertRemove();
return(-3);
}
//--- save the time of launching the Expert Advisor for receiving trading history
history_start=TimeCurrent();
//---
CreateBuySellButtons();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


2148 Trade Functions

void OnDeinit(const int reason)


{
//--- delete all graphical objects
ObjectDelete(0,"Buy");
ObjectDelete(0,"Sell");
//---
}
//+------------------------------------------------------------------+
//| TradeTransaction function |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
//--- heading named after trading event's handler function
Print("=> ",__FUNCTION__," at ",TimeToString(TimeCurrent(),TIME_SECONDS));
//--- receive transaction type as enumeration value
ENUM_TRADE_TRANSACTION_TYPE type=trans.type;
//--- if transaction is a result of request handling
if(type==TRADE_TRANSACTION_REQUEST)
{
//--- display transaction name
Print(EnumToString(type));
//--- then display the string description of the handled request
Print("------------RequestDescription\r\n",
RequestDescription(request,DescriptionModeFull));
//--- and show description of the request result
Print("------------ ResultDescription\r\n",
TradeResultDescription(result,DescriptionModeFull));
}
else // display full description of the transaction for transactions of another type
{
Print("------------ TransactionDescription\r\n",
TransactionDescription(trans,DescriptionModeFull));
}
//---
}
//+------------------------------------------------------------------+
//| Trade function |
//+------------------------------------------------------------------+
void OnTrade()
{
//--- static members for storing trading account status
static int prev_positions=0,prev_orders=0,prev_deals=0,prev_history_orders=0;
//--- request trading history
bool update=HistorySelect(history_start,TimeCurrent());
PrintFormat("HistorySelect(%s , %s) = %s",
TimeToString(history_start),TimeToString(TimeCurrent()),(string)update);
//--- heading named after trading event's handler function

© 2000-2025, MetaQuotes Ltd.


2149 Trade Functions

Print("=> ",__FUNCTION__," at ",TimeToString(TimeCurrent(),TIME_SECONDS));


//--- display handler's name and the number of orders at the moment of handling
int curr_positions=PositionsTotal();
int curr_orders=OrdersTotal();
int curr_deals=HistoryOrdersTotal();
int curr_history_orders=HistoryDealsTotal();
//--- display the number of orders, positions, deals, as well as changes in parentheses
PrintFormat("PositionsTotal() = %d (%+d)",
curr_positions,(curr_positions-prev_positions));
PrintFormat("OrdersTotal() = %d (%+d)",
curr_orders,curr_orders-prev_orders);
PrintFormat("HistoryOrdersTotal() = %d (%+d)",
curr_deals,curr_deals-prev_deals);
PrintFormat("HistoryDealsTotal() = %d (%+d)",
curr_history_orders,curr_history_orders-prev_history_orders);
//--- insert a string break to view the log more conveniently
Print("");
//--- save the account status
prev_positions=curr_positions;
prev_orders=curr_orders;
prev_deals=curr_deals;
prev_history_orders=curr_history_orders;
//---
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- handling CHARTEVENT_CLICK event ("Clicking the chart")
if(id==CHARTEVENT_OBJECT_CLICK)
{
Print("=> ",__FUNCTION__,": sparam = ",sparam);
//--- minimum volume for a deal
double volume_min=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
//--- if "Buy" button is pressed, then buy
if(sparam=="Buy")
{
PrintFormat("Buy %s %G lot",_Symbol,volume_min);
BuyAsync(volume_min);
//--- unpress the button
ObjectSetInteger(0,"Buy",OBJPROP_STATE,false);
}
//--- if "Sell" button is pressed, then sell
if(sparam=="Sell")
{

© 2000-2025, MetaQuotes Ltd.


2150 Trade Functions

PrintFormat("Sell %s %G lot",_Symbol,volume_min);
SellAsync(volume_min);
//--- unpress the button
ObjectSetInteger(0,"Sell",OBJPROP_STATE,false);
}
ChartRedraw();
}
//---
}
//+------------------------------------------------------------------+
//| Returns the text description of a transaction |
//+------------------------------------------------------------------+
string TransactionDescription(const MqlTradeTransaction &trans,
const bool detailed=true)
{
//--- prepare a string for returning from the function
string desc=EnumToString(trans.type)+"\r\n";
//--- all possible data is added in detailed mode
if(detailed)
{
desc+="Symbol: "+trans.symbol+"\r\n";
desc+="Deal ticket: "+(string)trans.deal+"\r\n";
desc+="Deal type: "+EnumToString(trans.deal_type)+"\r\n";
desc+="Order ticket: "+(string)trans.order+"\r\n";
desc+="Order type: "+EnumToString(trans.order_type)+"\r\n";
desc+="Order state: "+EnumToString(trans.order_state)+"\r\n";
desc+="Order time type: "+EnumToString(trans.time_type)+"\r\n";
desc+="Order expiration: "+TimeToString(trans.time_expiration)+"\r\n";
desc+="Price: "+StringFormat("%G",trans.price)+"\r\n";
desc+="Price trigger: "+StringFormat("%G",trans.price_trigger)+"\r\n";
desc+="Stop Loss: "+StringFormat("%G",trans.price_sl)+"\r\n";
desc+="Take Profit: "+StringFormat("%G",trans.price_tp)+"\r\n";
desc+="Volume: "+StringFormat("%G",trans.volume)+"\r\n";
}
//--- return a received string
return desc;
}
//+------------------------------------------------------------------+
//| Returns the text description of the trade request |
//+------------------------------------------------------------------+
string RequestDescription(const MqlTradeRequest &request,
const bool detailed=true)
{
//--- prepare a string for returning from the function
string desc=EnumToString(request.action)+"\r\n";
//--- add all available data in detailed mode
if(detailed)
{
desc+="Symbol: "+request.symbol+"\r\n";

© 2000-2025, MetaQuotes Ltd.


2151 Trade Functions

desc+="Magic Number: "+StringFormat("%d",request.magic)+"\r\n";


desc+="Order ticket: "+(string)request.order+"\r\n";
desc+="Order type: "+EnumToString(request.type)+"\r\n";
desc+="Order filling: "+EnumToString(request.type_filling)+"\r\n";
desc+="Order time type: "+EnumToString(request.type_time)+"\r\n";
desc+="Order expiration: "+TimeToString(request.expiration)+"\r\n";
desc+="Price: "+StringFormat("%G",request.price)+"\r\n";
desc+="Deviation points: "+StringFormat("%G",request.deviation)+"\r\n";
desc+="Stop Loss: "+StringFormat("%G",request.sl)+"\r\n";
desc+="Take Profit: "+StringFormat("%G",request.tp)+"\r\n";
desc+="Stop Limit: "+StringFormat("%G",request.stoplimit)+"\r\n";
desc+="Volume: "+StringFormat("%G",request.volume)+"\r\n";
desc+="Comment: "+request.comment+"\r\n";
}
//--- return the received string
return desc;
}
//+------------------------------------------------------------------+
//| Returns the text description of request handling result |
//+------------------------------------------------------------------+
string TradeResultDescription(const MqlTradeResult &result,
const bool detailed=true)
{
//--- prepare the string for returning from the function
string desc="Retcode "+(string)result.retcode+"\r\n";
//--- add all available data in detailed mode
if(detailed)
{
desc+="Request ID: "+StringFormat("%d",result.request_id)+"\r\n";
desc+="Order ticket: "+(string)result.order+"\r\n";
desc+="Deal ticket: "+(string)result.deal+"\r\n";
desc+="Volume: "+StringFormat("%G",result.volume)+"\r\n";
desc+="Price: "+StringFormat("%G",result.price)+"\r\n";
desc+="Ask: "+StringFormat("%G",result.ask)+"\r\n";
desc+="Bid: "+StringFormat("%G",result.bid)+"\r\n";
desc+="Comment: "+result.comment+"\r\n";
}
//--- return the received string
return desc;
}
//+------------------------------------------------------------------+
//| Create two buttons for buying and selling |
//+------------------------------------------------------------------+
void CreateBuySellButtons()
{
//--- check the object named "Buy"
if(ObjectFind(0,"Buy")>=0)
{
//--- if the found object is not a button, delete it

© 2000-2025, MetaQuotes Ltd.


2152 Trade Functions

if(ObjectGetInteger(0,"Buy",OBJPROP_TYPE)!=OBJ_BUTTON)
ObjectDelete(0,"Buy");
}
else
ObjectCreate(0,"Buy",OBJ_BUTTON,0,0,0); // create "Buy" button
//--- configure "Buy" button
ObjectSetInteger(0,"Buy",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSetInteger(0,"Buy",OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,"Buy",OBJPROP_YDISTANCE,50);
ObjectSetInteger(0,"Buy",OBJPROP_XSIZE,70);
ObjectSetInteger(0,"Buy",OBJPROP_YSIZE,30);
ObjectSetString(0,"Buy",OBJPROP_TEXT,"Buy");
ObjectSetInteger(0,"Buy",OBJPROP_COLOR,clrRed);
//--- check presence of the object named "Sell"
if(ObjectFind(0,"Sell")>=0)
{
//--- if the found object is not a button, delete it
if(ObjectGetInteger(0,"Sell",OBJPROP_TYPE)!=OBJ_BUTTON)
ObjectDelete(0,"Sell");
}
else
ObjectCreate(0,"Sell",OBJ_BUTTON,0,0,0); // create "Sell" button
//--- configure "Sell" button
ObjectSetInteger(0,"Sell",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSetInteger(0,"Sell",OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,"Sell",OBJPROP_YDISTANCE,100);
ObjectSetInteger(0,"Sell",OBJPROP_XSIZE,70);
ObjectSetInteger(0,"Sell",OBJPROP_YSIZE,30);
ObjectSetString(0,"Sell",OBJPROP_TEXT,"Sell");
ObjectSetInteger(0,"Sell",OBJPROP_COLOR,clrBlue);
//--- perform forced update of the chart to see the buttons immediately
ChartRedraw();
//---
}
//+------------------------------------------------------------------+
//| Buy using OrderSendAsync() asynchronous function |
//+------------------------------------------------------------------+
void BuyAsync(double volume)
{
//--- prepare the request
MqlTradeRequest req={};
req.action =TRADE_ACTION_DEAL;
req.symbol =_Symbol;
req.magic =MagicNumber;
req.volume =0.1;
req.type =ORDER_TYPE_BUY;
req.price =SymbolInfoDouble(req.symbol,SYMBOL_ASK);
req.deviation =10;
req.comment ="Buy using OrderSendAsync()";

© 2000-2025, MetaQuotes Ltd.


2153 Trade Functions

MqlTradeResult res={};
if(!OrderSendAsync(req,res))
{
Print(__FUNCTION__,": error ",GetLastError(),", retcode = ",res.retcode);
}
//---
}
//+------------------------------------------------------------------+
//| Sell using OrderSendAsync() asynchronous function |
//+------------------------------------------------------------------+
void SellAsync(double volume)
{
//--- prepare the request
MqlTradeRequest req={};
req.action =TRADE_ACTION_DEAL;
req.symbol =_Symbol;
req.magic =MagicNumber;
req.volume =0.1;
req.type =ORDER_TYPE_SELL;
req.price =SymbolInfoDouble(req.symbol,SYMBOL_BID);
req.deviation =10;
req.comment ="Sell using OrderSendAsync()";
MqlTradeResult res={};
if(!OrderSendAsync(req,res))
{
Print(__FUNCTION__,": error ",GetLastError(),", retcode = ",res.retcode);
}
//---
}
//+------------------------------------------------------------------+

Example of displaying messages in " Experts" log:

12:52:52 ExpertAdvisor (EURUSD,H1) => OnChartEvent: sparam = Sell


12:52:52 ExpertAdvisor (EURUSD,H1) Sell EURUSD 0.01 lot
12:52:52 ExpertAdvisor (EURUSD,H1) => OnTradeTransaction at 09:52:53
12:52:52 ExpertAdvisor (EURUSD,H1) TRADE_TRANSACTION_REQUEST
12:52:52 ExpertAdvisor (EURUSD,H1) ------------RequestDescription
12:52:52 ExpertAdvisor (EURUSD,H1) TRADE_ACTION_DEAL
12:52:52 ExpertAdvisor (EURUSD,H1) Symbol: EURUSD
12:52:52 ExpertAdvisor (EURUSD,H1) Magic Number: 1234567
12:52:52 ExpertAdvisor (EURUSD,H1) Order ticket: 16361998
12:52:52 ExpertAdvisor (EURUSD,H1) Order type: ORDER_TYPE_SELL
12:52:52 ExpertAdvisor (EURUSD,H1) Order filling: ORDER_FILLING_FOK
12:52:52 ExpertAdvisor (EURUSD,H1) Order time type: ORDER_TIME_GTC
12:52:52 ExpertAdvisor (EURUSD,H1) Order expiration: 1970.01.01 00:00
12:52:52 ExpertAdvisor (EURUSD,H1) Price: 1.29313
12:52:52 ExpertAdvisor (EURUSD,H1) Deviation points: 10
12:52:52 ExpertAdvisor (EURUSD,H1) Stop Loss: 0

© 2000-2025, MetaQuotes Ltd.


2154 Trade Functions

12:52:52 ExpertAdvisor (EURUSD,H1) Take Profit: 0


12:52:52 ExpertAdvisor (EURUSD,H1) Stop Limit: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Volume: 0.1
12:52:52 ExpertAdvisor (EURUSD,H1) Comment: Sell using OrderSendAsync()
12:52:52 ExpertAdvisor (EURUSD,H1)
12:52:52 ExpertAdvisor (EURUSD,H1) ------------ ResultDescription
12:52:52 ExpertAdvisor (EURUSD,H1) Retcode 10009
12:52:52 ExpertAdvisor (EURUSD,H1) Request ID: 2
12:52:52 ExpertAdvisor (EURUSD,H1) Order ticket: 16361998
12:52:52 ExpertAdvisor (EURUSD,H1) Deal ticket: 15048668
12:52:52 ExpertAdvisor (EURUSD,H1) Volume: 0.1
12:52:52 ExpertAdvisor (EURUSD,H1) Price: 1.29313
12:52:52 ExpertAdvisor (EURUSD,H1) Ask: 1.29319
12:52:52 ExpertAdvisor (EURUSD,H1) Bid: 1.29313
12:52:52 ExpertAdvisor (EURUSD,H1) Comment:
12:52:52 ExpertAdvisor (EURUSD,H1)
12:52:52 ExpertAdvisor (EURUSD,H1) HistorySelect( 09:34 , 09:52) = true
12:52:52 ExpertAdvisor (EURUSD,H1) => OnTrade at 09:52:53
12:52:52 ExpertAdvisor (EURUSD,H1) PositionsTotal() = 1 (+1)
12:52:52 ExpertAdvisor (EURUSD,H1) OrdersTotal() = 0 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) HistoryOrdersTotal() = 2 (+2)
12:52:52 ExpertAdvisor (EURUSD,H1) HistoryDealsTotal() = 2 (+2)
12:52:52 ExpertAdvisor (EURUSD,H1)
12:52:52 ExpertAdvisor (EURUSD,H1) => OnTradeTransaction at 09:52:53
12:52:52 ExpertAdvisor (EURUSD,H1) ------------ TransactionDescription
12:52:52 ExpertAdvisor (EURUSD,H1) TRADE_TRANSACTION_ORDER_ADD
12:52:52 ExpertAdvisor (EURUSD,H1) Symbol: EURUSD
12:52:52 ExpertAdvisor (EURUSD,H1) Deal ticket: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Deal type: DEAL_TYPE_BUY
12:52:52 ExpertAdvisor (EURUSD,H1) Order ticket: 16361998
12:52:52 ExpertAdvisor (EURUSD,H1) Order type: ORDER_TYPE_SELL
12:52:52 ExpertAdvisor (EURUSD,H1) Order state: ORDER_STATE_STARTED
12:52:52 ExpertAdvisor (EURUSD,H1) Order time type: ORDER_TIME_GTC
12:52:52 ExpertAdvisor (EURUSD,H1) Order expiration: 1970.01.01 00:00
12:52:52 ExpertAdvisor (EURUSD,H1) Price: 1.29313
12:52:52 ExpertAdvisor (EURUSD,H1) Price trigger: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Stop Loss: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Take Profit: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Volume: 0.1
12:52:52 ExpertAdvisor (EURUSD,H1)
12:52:52 ExpertAdvisor (EURUSD,H1) => OnTradeTransaction at 09:52:53
12:52:52 ExpertAdvisor (EURUSD,H1) ------------ TransactionDescription
12:52:52 ExpertAdvisor (EURUSD,H1) TRADE_TRANSACTION_ORDER_DELETE
12:52:52 ExpertAdvisor (EURUSD,H1) Symbol: EURUSD
12:52:52 ExpertAdvisor (EURUSD,H1) Deal ticket: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Deal type: DEAL_TYPE_BUY
12:52:52 ExpertAdvisor (EURUSD,H1) Order ticket: 16361998
12:52:52 ExpertAdvisor (EURUSD,H1) Order type: ORDER_TYPE_SELL
12:52:52 ExpertAdvisor (EURUSD,H1) Order state: ORDER_STATE_STARTED

© 2000-2025, MetaQuotes Ltd.


2155 Trade Functions

12:52:52 ExpertAdvisor (EURUSD,H1) Order time type: ORDER_TIME_GTC


12:52:52 ExpertAdvisor (EURUSD,H1) Order expiration: 1970.01.01 00:00
12:52:52 ExpertAdvisor (EURUSD,H1) Price: 1.29313
12:52:52 ExpertAdvisor (EURUSD,H1) Price trigger: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Stop Loss: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Take Profit: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Volume: 0.1
12:52:52 ExpertAdvisor (EURUSD,H1)
12:52:52 ExpertAdvisor (EURUSD,H1) HistorySelect( 09:34 , 09:52) = true
12:52:52 ExpertAdvisor (EURUSD,H1) => OnTrade at 09:52:53
12:52:52 ExpertAdvisor (EURUSD,H1) PositionsTotal() = 1 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) OrdersTotal() = 0 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) HistoryOrdersTotal() = 2 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) HistoryDealsTotal() = 2 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1)
12:52:52 ExpertAdvisor (EURUSD,H1) => OnTradeTransaction at 09:52:53
12:52:52 ExpertAdvisor (EURUSD,H1) ------------ TransactionDescription
12:52:52 ExpertAdvisor (EURUSD,H1) TRADE_TRANSACTION_HISTORY_ADD
12:52:52 ExpertAdvisor (EURUSD,H1) Symbol: EURUSD
12:52:52 ExpertAdvisor (EURUSD,H1) Deal ticket: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Deal type: DEAL_TYPE_BUY
12:52:52 ExpertAdvisor (EURUSD,H1) Order ticket: 16361998
12:52:52 ExpertAdvisor (EURUSD,H1) Order type: ORDER_TYPE_SELL
12:52:52 ExpertAdvisor (EURUSD,H1) Order state: ORDER_STATE_FILLED
12:52:52 ExpertAdvisor (EURUSD,H1) Order time type: ORDER_TIME_GTC
12:52:52 ExpertAdvisor (EURUSD,H1) Order expiration: 1970.01.01 00:00
12:52:52 ExpertAdvisor (EURUSD,H1) Price: 1.29313
12:52:52 ExpertAdvisor (EURUSD,H1) Price trigger: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Stop Loss: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Take Profit: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Volume: 0
12:52:52 ExpertAdvisor (EURUSD,H1)
12:52:52 ExpertAdvisor (EURUSD,H1) HistorySelect( 09:34 , 09:52) = true
12:52:52 ExpertAdvisor (EURUSD,H1) => OnTrade at 09:52:53
12:52:52 ExpertAdvisor (EURUSD,H1) PositionsTotal() = 1 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) OrdersTotal() = 0 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) HistoryOrdersTotal() = 2 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) HistoryDealsTotal() = 2 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1)
12:52:52 ExpertAdvisor (EURUSD,H1) => OnTradeTransaction at 09:52:53
12:52:52 ExpertAdvisor (EURUSD,H1) ------------ TransactionDescription
12:52:52 ExpertAdvisor (EURUSD,H1) TRADE_TRANSACTION_DEAL_ADD
12:52:52 ExpertAdvisor (EURUSD,H1) Symbol: EURUSD
12:52:52 ExpertAdvisor (EURUSD,H1) Deal ticket: 15048668
12:52:52 ExpertAdvisor (EURUSD,H1) Deal type: DEAL_TYPE_SELL
12:52:52 ExpertAdvisor (EURUSD,H1) Order ticket: 16361998
12:52:52 ExpertAdvisor (EURUSD,H1) Order type: ORDER_TYPE_BUY
12:52:52 ExpertAdvisor (EURUSD,H1) Order state: ORDER_STATE_STARTED
12:52:52 ExpertAdvisor (EURUSD,H1) Order time type: ORDER_TIME_GTC

© 2000-2025, MetaQuotes Ltd.


2156 Trade Functions

12:52:52 ExpertAdvisor (EURUSD,H1) Order expiration: 1970.01.01 00:00


12:52:52 ExpertAdvisor (EURUSD,H1) Price: 1.29313
12:52:52 ExpertAdvisor (EURUSD,H1) Price trigger: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Stop Loss: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Take Profit: 0
12:52:52 ExpertAdvisor (EURUSD,H1) Volume: 0.1
12:52:52 ExpertAdvisor (EURUSD,H1)
12:52:52 ExpertAdvisor (EURUSD,H1) HistorySelect( 09:34 , 09:52) = true
12:52:52 ExpertAdvisor (EURUSD,H1) => OnTrade at 09:52:53
12:52:52 ExpertAdvisor (EURUSD,H1) PositionsTotal() = 1 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) OrdersTotal() = 0 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) HistoryOrdersTotal() = 2 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1) HistoryDealsTotal() = 2 (+0)
12:52:52 ExpertAdvisor (EURUSD,H1)

© 2000-2025, MetaQuotes Ltd.


2157 Trade Functions

PositionsTotal
R eturns the number of open positions.
int PositionsTotal();

Return Value

Value of int type.


Note

For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get and print the number of open positions on the account in the journal
int total=PositionsTotal();
Print("Number of open positions on account: ", total);
/*
result:
Number of open positions on account: 2
*/
}

See also
PositionGetS ymbol(), PositionS elect(), Position Properties

© 2000-2025, MetaQuotes Ltd.


2158 Trade Functions

PositionGetSymbol
R eturns the symbol corresponding to the open position and automatically selects the position for
further working with it using functions PositionGetDouble, PositionGetInteger, PositionGetS tring.
string PositionGetSymbol(
int index // Number in the list of positions
);

Parameters
index
[in] Number of the position in the list of open positions.

Return Value

Value of the string type. If the position was not found, an empty string will be returned. To get an
error code, call the GetLastError() function.
Note

For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get the number of open positions on the account
int total=PositionsTotal();
for(int i=0; i<total; i++)
{
//--- get position symbol by i loop index
ResetLastError();
string symbol=PositionGetSymbol(i);

//--- if the position symbol is successfully received, then the position at the i index becom
//--- and we can obtain its properties using PositionGetDouble, PositionGetInteger and Positi
if(symbol!="")
{
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
PrintFormat("Position symbol at index %d: %s, position type: %s", i, symbol, StringSubstr(
}
else

© 2000-2025, MetaQuotes Ltd.


2159 Trade Functions

{
PrintFormat("PositionGetSymbol(%d) failed. Error %d", i, GetLastError());
continue;
}
}
/*
result:
Position symbol at index 0: GBPUSD, position type: SELL
Position symbol at index 1: EURUSD, position type: BUY
*/
}

See also
PositionsTotal(), PositionS elect(), Position Properties

© 2000-2025, MetaQuotes Ltd.


2160 Trade Functions

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

Parameters
symbol
[in] Name of the financial security.

Return Value

Value of the bool type.


Note

For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol. In this case, PositionS elect will select a position with the lowest ticket.
Function PositionS elect() copies data about a position into the program environment, and further
calls of PositionGetDouble(), PositionGetInteger() and PositionGetS tring() return the earlier copied
data. This means that the position itself may no longer exist (or its volume, direction, etc. has
changed), but data of this position still can be obtained. To ensure receipt of fresh data about a
position, it is recommended to call PositionS elect() right before referring to them.
Example:

#define SYMBOL_NAME "EURUSD"

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- select a position on a specified symbol
if(!PositionSelect(SYMBOL_NAME))
{
PrintFormat("PositionSelect(%s) failed. Error %d",SYMBOL_NAME, GetLastError());
return;
}

//--- if a position is selected, we can obtain its data using PositionGetDouble(), PositionGetInteg
//--- get the selected position ticket
ResetLastError();

© 2000-2025, MetaQuotes Ltd.


2161 Trade Functions

long ticket=PositionGetInteger(POSITION_TICKET);
if(ticket==0)
{
PrintFormat("Failed to get %s position ticket. Error %d", SYMBOL_NAME, GetLastError());
return;
}

//--- if a ticket is successfully received, print the selected position symbol and ticket in the jo
PrintFormat("The position that is selected on the %s symbol has ticket %I64d", SYMBOL_NAME, tick
/*
result:
The position that is selected on the EURUSD symbol has ticket 2810846623
*/
}

See also
PositionGetS ymbol(), PositionsTotal(), Position Properties

© 2000-2025, MetaQuotes Ltd.


2162 Trade Functions

PositionSelectByTicket
S electsan open position to work with based on the ticket number specified in the position. If
successful, returns true. Returns false if the function failed. Call GetLastError() for error details.
bool PositionSelectByTicket(
ulong ticket // Position ticket
);

Parameters
ticket
[in] Position ticket.

Return Value

A value of the bool type.


Note

The PositionS electByTicket() function copies position data to the program environment. Further calls
of PositionGetDouble(), PositionGetInteger() and PositionGetS tring() return the previously copied
data. Even if a position does not exist already (or its size, direction etc. has changed), the data may
still be received sometimes. To make sure that you receive valid position data, it is recommended
to call PositionS electByTicket() before you access the data.
Example:

#define EXPERT_MAGIC 123456 // MagicNumber

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare and initialize the request and result structures
MqlTradeRequest request={};
MqlTradeResult result ={};

//--- fill in trade request parameters to open a long position


request.action = TRADE_ACTION_DEAL; // trading operation type
request.symbol = Symbol(); // symbol
request.volume = 0.1; // volume of 0.1 lot
request.type = ORDER_TYPE_BUY; // order type
request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // open price
request.deviation = 5; // allowed deviation from the price
request.magic = EXPERT_MAGIC; // order MagicNumber

//--- send a request. If failed to send a request, display the error code and complete operation
if(!OrderSend(request, result))
{
PrintFormat("OrderSend error ", GetLastError());

© 2000-2025, MetaQuotes Ltd.


2163 Trade Functions

return;
}

//--- display operation data


PrintFormat("Trade request result: retcode: %u, deal: %I64u, order: %I64u", result.retcode, resu

//--- get the position ticket from the trade operation result and select the position by ticket
//--- the ticket of a newly opened position corresponds to the ticket of the order that generated t
ulong ticket=result.order;
ResetLastError();
if(!PositionSelectByTicket(ticket))
{
PrintFormat("PositionSelectByTicket(%I64u) failed. Error %d", ticket, GetLastError());
return;
}

//--- display the data of a position, selected by ticket, in the journal


ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
long time = PositionGetInteger(POSITION_TIME_MSC);
double price = PositionGetDouble(POSITION_PRICE_OPEN);
double volume= PositionGetDouble(POSITION_VOLUME);
string symbol= PositionGetString(POSITION_SYMBOL);
int digits= (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
PrintFormat("Current selected position: %s %.2f %s #%I64u at %.*f, %s",
symbol, volume, (type==POSITION_TYPE_BUY ? "Buy" : "Sell"), ticket, digits, price, T
/*
result:
Trade request result: retcode: 10009, deal: 2778100901, order: 2803905975
Current selected position: EURUSD 0.10 Buy #2803905975 at 1.10672, 2024.09.02 12:09:51.239
*/
}
//+------------------------------------------------------------------+
//| Return time with milliseconds |
//+------------------------------------------------------------------+
string TimeMscToString(const long time_msc, int flags=TIME_DATE|TIME_MINUTES|TIME_SECONDS)
{
return(TimeToString(time_msc/1000, flags) + "." + IntegerToString(time_msc %1000, 3, '0'));
}

See also
PositionGetS ymbol(), PositionsTotal(), Position Properties

© 2000-2025, MetaQuotes Ltd.


2164 Trade Functions

PositionGetDouble
The function returns the requested property of an open position, pre-selected using PositionGetS ymbol
or PositionS elect. 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_DOUBLE property_id // Property identifier
);

2. R eturnstrue or false, depending on the success of the function execution. If successful, the value
of the property is placed in a receiving variable passed by reference by the last parameter.
bool PositionGetDouble(
ENUM_POSITION_PROPERTY_DOUBLE 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 _POS ITION_PR OPER T Y_DOUBL E enumeration.

double_var
[out] Variable of the double type, accepting the value of the requested property.

Return Value

Value of the double type. If the function fails, 0 is returned.


Note

For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about a position, it is recommended to call PositionS elect() right
before referring to them.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- in a loop by all account positions

© 2000-2025, MetaQuotes Ltd.


2165 Trade Functions

int total=PositionsTotal();
for(int i=0; i<total; i++)
{
//--- get the ticket of the next position by automatically selecting a position to access its
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;

//--- get the position type and display the header for the list of position real properties
string type=(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE ? "Buy" : "Sell");
PrintFormat("Double properties of an open position %s #%I64u:", type, ticket);

//--- print all the real properties of the selected position under the header
PositionPropertiesDoublePrint(15);
}
/*
result:
Double properties of an open position Buy #2807075208:
Volume: 1.00
Price open: 1.10516
StopLoss: 0.00000
TakeProfit: 0.00000
Price current: 1.10518
Swap: 0.00
Profit: 2.00 USD
*/
}
//+------------------------------------------------------------------+
//| Display real properties of the selected position in the journal |
//+------------------------------------------------------------------+
void PositionPropertiesDoublePrint(const uint header_width=0)
{
uint w=0;
string header="";
double value=0;

//--- get the account currency, position symbol and the number of decimal places for the symbol
string currency=AccountInfoString(ACCOUNT_CURRENCY);
string symbol =PositionGetString(POSITION_SYMBOL);
int digits =(int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);

//--- define the header text and the width of the header field
//--- if the header width is passed to the function equal to zero, then the width will be the size
header="Volume:";
w=(header_width==0 ? header.Length()+1 : header_width);
//--- get and display the position volume with the specified header width in the journal
if(!PositionGetDouble(POSITION_VOLUME, value))
return;
PrintFormat("%-*s%-.2f", w, header, value);

© 2000-2025, MetaQuotes Ltd.


2166 Trade Functions

//--- display the position price value in the journal


header="Price open:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!PositionGetDouble(POSITION_PRICE_OPEN, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

//--- display the StopLoss value in the journal


header="StopLoss:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!PositionGetDouble(POSITION_SL, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

//--- display the TakeProfit value in the journal


header="TakeProfit:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!PositionGetDouble(POSITION_TP, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

//--- display the 'Price current' value in the journal


header="Price current:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!PositionGetDouble(POSITION_PRICE_CURRENT, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

//--- display the accumulated swap value in the journal


header="Swap:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!PositionGetDouble(POSITION_SWAP, value))
return;
PrintFormat("%-*s%-.2f", w, header, value);

//--- display the current profit value to the journal


header="Profit:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!PositionGetDouble(POSITION_PROFIT, value))
return;
PrintFormat("%-*s%-.2f %s", w, header, value, currency);
}

See also
PositionGetS ymbol(), PositionS elect(), Position Properties

© 2000-2025, MetaQuotes Ltd.


2167 Trade Functions

PositionGetInteger
The function returns the requested property of an open position, pre-selected using PositionGetS ymbol
or PositionS elect. 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_INTEGER property_id // Property identifier
);

2. R eturnstrue 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_INTEGER 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 _POS ITION_PR OPER T Y_INT EGER enumeration.

long_var
[out] Variable of the long type accepting the value of the requested property.

Return Value

Value of the long type. If the function fails, 0 is returned.


Note

For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about a position, it is recommended to call PositionS elect() right
before referring to them.
Example:

//+------------------------------------------------------------------+
//| Trade function |
//+------------------------------------------------------------------+
void OnTrade()
{
//--- check if a position is present and display the time of its changing

© 2000-2025, MetaQuotes Ltd.


2168 Trade Functions

if(PositionSelect(_Symbol))
{
//--- receive position ID for further work
ulong position_ID=PositionGetInteger(POSITION_IDENTIFIER);
Print(_Symbol," position #",position_ID);
//--- receive the time of position forming in milliseconds since 01.01.1970
long create_time_msc=PositionGetInteger(POSITION_TIME_MSC);
PrintFormat("Position #%d POSITION_TIME_MSC = %i64 milliseconds => %s",position_ID,
create_time_msc,TimeToString(create_time_msc/1000));
//--- receive the time of the position's last change in seconds since 01.01.1970
long update_time_sec=PositionGetInteger(POSITION_TIME_UPDATE);
PrintFormat("Position #%d POSITION_TIME_UPDATE = %i64 seconds => %s",
position_ID,update_time_sec,TimeToString(update_time_sec));
//--- receive the time of the position's last change in milliseconds since 01.01.1970
long update_time_msc=PositionGetInteger(POSITION_TIME_UPDATE_MSC);
PrintFormat("Position #%d POSITION_TIME_UPDATE_MSC = %i64 milliseconds => %s",
position_ID,update_time_msc,TimeToString(update_time_msc/1000));
}
//---
}

See also
PositionGetS ymbol(), PositionS elect(), Position Properties

© 2000-2025, MetaQuotes Ltd.


2169 Trade Functions

PositionGetString
The function returns the requested property of an open position, pre-selected using PositionGetS ymbol
or PositionS elect. The position property should be of the string type. There are 2 variants of the
function.
1. Immediately returns the property value.
string PositionGetString(
ENUM_POSITION_PROPERTY_STRING property_id // Property identifier
);

2. R eturnstrue 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_STRING property_id, // Property identifier
string& string_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 _POS ITION_PR OPER T Y_S T R ING enumeration.

string_var
[out] Variable of the string type accepting the value of the requested property.

Return Value

Value of the string type. If the function fails, an empty string is returned.
Note

For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about a position, it is recommended to call PositionS elect() right
before referring to them.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- in a loop by all account positions

© 2000-2025, MetaQuotes Ltd.


2170 Trade Functions

int total=PositionsTotal();
for(int i=0; i<total; i++)
{
//--- get the ticket of the next position by automatically selecting a position to access its
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;

//--- get the position type and display the header for the list of position string properties
string type=(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE ? "Buy" : "Sell");
PrintFormat("String properties of an open position %s #%I64u:", type, ticket);

//--- print all the string properties of the selected position under the header
PositionPropertiesStringPrint(15);
}
/*
result:
String properties of an open position Buy #2810798881:
Symbol: EURUSD
Comment: Test PositionGetString
External ID:
*/
}
//+------------------------------------------------------------------+
//| Display string properties of the selected position in the journal|
//+------------------------------------------------------------------+
void PositionPropertiesStringPrint(const uint header_width=0)
{
uint w=0;
string header="";
string value="";

//--- define the header text and the width of the header field
//--- if the header width is passed to the function equal to zero, then the width will be the size
header="Symbol:";
w=(header_width==0 ? header.Length()+1 : header_width);
//--- get and display the position symbol with the specified header width in the journal
if(!PositionGetString(POSITION_SYMBOL, value))
return;
PrintFormat("%-*s%-s", w, header, value);

//--- display the position comment in the journal


header="Comment:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!PositionGetString(POSITION_COMMENT, value))
return;
PrintFormat("%-*s%-s", w, header, value);

//--- display the position ID in an external system in the journal

© 2000-2025, MetaQuotes Ltd.


2171 Trade Functions

header="External ID:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!PositionGetString(POSITION_EXTERNAL_ID, value))
return;
PrintFormat("%-*s%-s", w, header, value);
}

See also
PositionGetS ymbol(), PositionS elect(), Position Properties

© 2000-2025, MetaQuotes Ltd.


2172 Trade Functions

PositionGetTicket
The function returns the ticket of a position with the specified index in the list of open positions and
automatically selects the position to work with using functions PositionGetDouble, PositionGetInteger,
PositionGetS tring.
ulong PositionGetTicket(
int index // The number of a position in the list
);

Parameters
index
[in] The index of a position in the list of open positions, numeration starts with 0.

Return Value

The ticket of the position. Returns 0 if the function fails.


Note

For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about a position, it is recommended to call PositionS elect() right
before referring to them.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- in a loop by all account positions
int total=PositionsTotal();
for(int i=0; i<total; i++)
{
//--- get the ticket of the next position by automatically selecting a position to access its
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;

//--- get the position type and display the description of the selected position to the journ
string type=(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE ? "Buy" : "Sell");
PrintFormat("[%d] Selected position %s #%I64u", i, type, ticket);
}
/*

© 2000-2025, MetaQuotes Ltd.


2173 Trade Functions

result:
[0] Selected position Sell #2810802718
[1] Selected position Buy #2810802919
*/
}

See also
PositionGetS ymbol(), PositionS elect(), Position Properties

© 2000-2025, MetaQuotes Ltd.


2174 Trade Functions

OrdersTotal
R eturns the number of current orders.
int OrdersTotal();

Return Value

Value of the int type.


Note

Do not confuse current pending orders with positions, which are also displayed on the " Trade" tab of
the " Toolbox" of the client terminal. An order is a request to conduct a transaction, while a position
is a result of one or more deals.
For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get and print in the journal the number of active pending orders on the account
int total=OrdersTotal();
Print("Number of active pending orders on the account: ", total);
/*
result:
Number of active pending orders on the account: 2
*/
}

See also
OrderS elect(), OrderGetTicket(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2175 Trade Functions

OrderGetTicket
R eturnsticket of a corresponding order and automatically selects the order for further working with it
using functions.
ulong OrderGetTicket(
int index // Number in the list of orders
);

Parameters
index
[in] Number of an order in the list of current orders.

Return Value

Value of the ulong type. If the function fails, 0 is returned.


Note

Do not confuse current pending orders with positions, which are also displayed on the " Trade" tab of
the " Toolbox" of the client terminal. An order is a request to conduct a transaction, while a position
is a result of one or more deals.
For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
Function OrderGetTicket() copies data about an order into the program environment, and further
calls of OrderGetDouble(), OrderGetInteger(), OrderGetS tring() return the earlier copied data. This
means that the order itself may no longer exist (or its open price, S top Loss /Take Profit levels or
expiration has changed), but data of this order still can be obtained. To ensure receipt of fresh data
about an order, it is recommended to call OrderGetTicket() right before referring to them.
Example:

void OnStart()
{
//--- variables for returning values from order properties
ulong ticket;
double open_price;
double initial_volume;
datetime time_setup;
string symbol;
string type;
long order_magic;
long positionID;
//--- number of current pending orders
uint total=OrdersTotal();

© 2000-2025, MetaQuotes Ltd.


2176 Trade Functions

//--- go through orders in a loop


for(uint i=0;i<total;i++)
{
//--- return order ticket by its position in the list
if((ticket=OrderGetTicket(i))>0)
{
//--- return order properties
open_price =OrderGetDouble(ORDER_PRICE_OPEN);
time_setup =(datetime)OrderGetInteger(ORDER_TIME_SETUP);
symbol =OrderGetString(ORDER_SYMBOL);
order_magic =OrderGetInteger(ORDER_MAGIC);
positionID =OrderGetInteger(ORDER_POSITION_ID);
initial_volume=OrderGetDouble(ORDER_VOLUME_INITIAL);
type =EnumToString(ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE)));
//--- prepare and show information about the order
printf("#ticket %d %s %G %s at %G was set up at %s",
ticket, // order ticket
type, // type
initial_volume, // placed volume
symbol, // symbol
open_price, // specified open price
TimeToString(time_setup)// time of order placing
);
}
}
//---
}

See also
OrdersTotal(), OrderS elect(), OrderGetInteger()

© 2000-2025, MetaQuotes Ltd.


2177 Trade Functions

OrderSelect
S elects an order to work with. Returns true if the function has been successfully completed. Returns
false if the function completion has failed. For more information about an error call GetLastError().
bool OrderSelect(
ulong ticket // Order ticket
);

Parameters
ticket
[in] Order ticket.

Return Value

Value of the bool type.


Note

Do not confuse current pending orders with positions, which are also displayed on the " Trade" tab of
the " Toolbox" of the client terminal.
For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
Function OrderS elect() copies data about an order into the program environment, and further calls
of OrderGetDouble(), OrderGetInteger(), OrderGetS tring() return the earlier copied data. This
means that the order itself may no longer exist (or its open price, S top Loss /Take Profit levels or
expiration has changed), but data of this order still can be obtained. To ensure receipt of fresh data
about an order, it is recommended to call OrderS elect() right before referring to them.
Example:

#define EXPERT_MAGIC 123456


#define OFFSET 50 // offset from the current price to place the order
#define DIRECTION ORDER_TYPE_BUY_LIMIT // order type
#define VOLUME 1.0 // volume
#define DEVIATION 2 // allowed deviation from the price

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//-- declare and initialize the trade request, result and variables
MqlTradeRequest request={};
MqlTradeResult result ={};

© 2000-2025, MetaQuotes Ltd.


2178 Trade Functions

double order_price=0;

//--- pending order placing parameters


request.action = TRADE_ACTION_PENDING; // trading operation typ
request.symbol = _Symbol; // symbol
request.volume = VOLUME; // volume
request.deviation = DEVIATION; // allowed deviation fro
request.magic = EXPERT_MAGIC; // order MagicNumber

//--- check operation type


switch(DIRECTION)
{
case ORDER_TYPE_BUY_LIMIT :
request.type = ORDER_TYPE_BUY_LIMIT; // order type
order_price = SymbolInfoDouble(_Symbol, SYMBOL_ASK)-OFFSET*_Point;// open price
request.price= NormalizeDouble(order_price, _Digits); // normalized open price
break;
case ORDER_TYPE_SELL_LIMIT :
request.type = ORDER_TYPE_SELL_LIMIT; // order type
order_price = SymbolInfoDouble(_Symbol, SYMBOL_BID)+OFFSET*_Point;// open price
request.price= NormalizeDouble(order_price,_Digits); // normalized open price
break;
case ORDER_TYPE_BUY_STOP :
request.type = ORDER_TYPE_BUY_STOP; // order type
order_price = SymbolInfoDouble(_Symbol, SYMBOL_ASK)+OFFSET*_Point;// open price
request.price= NormalizeDouble(order_price,_Digits); // normalized open price
break;
case ORDER_TYPE_SELL_STOP :
request.type = ORDER_TYPE_SELL_STOP; // order type
order_price = SymbolInfoDouble(_Symbol, SYMBOL_BID)-OFFSET*_Point;// open price
request.price= NormalizeDouble(order_price,_Digits); // normalized open price
break;
default: // if non-pending or StopLimit order is selected
Alert("This example is only for placing pending orders BuyLimit, SellLimit, BuyStop and Sel
break;
}

//--- send a request. If failed to send a request, display the error code and complete operation
if(!OrderSend(request, result))
{
Print("OrderSend error ", GetLastError());
return;
}

//--- display operation data


PrintFormat("Trade request result: retcode=%u, order=%I64u", result.retcode, result.order);

//--- get the order ticket from the trade operation result and select the order by ticket
ulong ticket=result.order;

© 2000-2025, MetaQuotes Ltd.


2179 Trade Functions

ResetLastError();
if(!OrderSelect(ticket))
{
PrintFormat("OrderSelect(%I64u) failed. Error %d", ticket, GetLastError());
return;
}

//--- display the data of the order, selected by ticket, in the journal
ENUM_ORDER_TYPE type = (ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE);
long time = OrderGetInteger(ORDER_TIME_SETUP_MSC);
double price = OrderGetDouble(ORDER_PRICE_OPEN);
double volume= OrderGetDouble(ORDER_VOLUME_CURRENT);
string symbol= OrderGetString(ORDER_SYMBOL);
int digits= (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
PrintFormat("Current selected order: %s %.2f %s #%I64u at %.*f, %s",
symbol, volume, OrderTypeDescription(type), ticket, digits, price, TimeMscToString(t
/*
result:
Trade request result: retcode=10009, order=2811006719
Current selected order: EURUSD 1.00 Buy Limit #2811006719 at 1.10550, 2024.09.04 10:38:28.563
*/
}
//+------------------------------------------------------------------+
//| Return time with milliseconds |
//+------------------------------------------------------------------+
string TimeMscToString(const long time_msc, int flags=TIME_DATE|TIME_MINUTES|TIME_SECONDS)
{
return(TimeToString(time_msc/1000, flags) + "." + IntegerToString(time_msc %1000, 3, '0'));
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE type)
{
switch(type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
case ORDER_TYPE_BUY_LIMIT : return("Buy Limit");
case ORDER_TYPE_SELL_LIMIT : return("Sell Limit");
case ORDER_TYPE_BUY_STOP : return("Buy Stop");
case ORDER_TYPE_SELL_STOP : return("Sell Stop");
case ORDER_TYPE_BUY_STOP_LIMIT : return("Buy Stop Limit");
case ORDER_TYPE_SELL_STOP_LIMIT : return("Sell Stop Limit");
default : return("Unknown order type");
}
}

See also

© 2000-2025, MetaQuotes Ltd.


2180 Trade Functions

OrderGetInteger(), OrderGetDouble(), OrderGetS tring(), OrderCalcProfit(), OrderGetTicket(), Order


Properties

© 2000-2025, MetaQuotes Ltd.


2181 Trade Functions

OrderGetDouble
R eturns the requested property of an order, pre-selected using OrderGetTicket or OrderS elect. The
order property must be of the double type. There are 2 variants of the function.
1. Immediately returns the property value.
double OrderGetDouble(
ENUM_ORDER_PROPERTY_DOUBLE property_id // Property identifier
);

2. R eturns true or false, depending on the success of a function. If successful, the value of the
property is placed in a target variable passed by reference by the last parameter.
bool OrderGetDouble(
ENUM _ORDER_PR OPER T Y_DOUBL E property_id, // Property identifier
double& double_var // Here we accept the property value
);

Parameters
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM _ORDER_PR OPER T Y_DOUBL E enumeration.

double_var
[out] Variable of the double type that accepts the value of the requested property.

Return Value

Value of the double type. If the function fails, 0 is returned.


Note

Do not confuse current pending orders with positions, which are also displayed on the " Trade" tab of
the " Toolbox" of the client terminal.
For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about an order, it is recommended to call OrderS elect() right before
referring to them.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{

© 2000-2025, MetaQuotes Ltd.


2182 Trade Functions

//--- in a loop by the list of all account orders


int total=OrdersTotal();
for(int i=0; i<total; i++)
{
//--- get the order ticket in the list by the loop index
ulong ticket=OrderGetTicket(i);
if(ticket==0)
continue;

//--- get the order type and display the header for the list of real properties of the select
string type=OrderTypeDescription((ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE));
PrintFormat("Double properties of an active pending order %s #%I64u:", type, ticket);

//--- print all the real properties of the selected order under the header
OrderPropertiesDoublePrint(16);
}
/*
result:
Double properties of an active pending order Sell Limit #2812000714:
Volume initial: 1.00
Volume current: 1.00
Price open: 145.282
StopLoss: 0.000
TakeProfit: 0.000
Price current: 145.044
StopLimit: 0.000
Double properties of an active pending order Buy Limit #2812001112:
Volume initial: 1.00
Volume current: 1.00
Price open: 144.836
StopLoss: 0.000
TakeProfit: 0.000
Price current: 145.051
StopLimit: 0.000
Double properties of an active pending order Buy Stop #2812001488:
Volume initial: 0.50
Volume current: 0.50
Price open: 1.10642
StopLoss: 0.00000
TakeProfit: 0.00000
Price current: 1.10530
StopLimit: 0.00000
Double properties of an active pending order Sell Stop #2812001712:
Volume initial: 0.50
Volume current: 0.50
Price open: 1.10374
StopLoss: 0.00000
TakeProfit: 0.00000
Price current: 1.10525

© 2000-2025, MetaQuotes Ltd.


2183 Trade Functions

StopLimit: 0.00000
*/
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE type)
{
switch(type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
case ORDER_TYPE_BUY_LIMIT : return("Buy Limit");
case ORDER_TYPE_SELL_LIMIT : return("Sell Limit");
case ORDER_TYPE_BUY_STOP : return("Buy Stop");
case ORDER_TYPE_SELL_STOP : return("Sell Stop");
case ORDER_TYPE_BUY_STOP_LIMIT : return("Buy Stop Limit");
case ORDER_TYPE_SELL_STOP_LIMIT : return("Sell Stop Limit");
default : return("Unknown order type");
}
}
//+------------------------------------------------------------------+
//| Display real properties of the selected order in the journal |
//+------------------------------------------------------------------+
void OrderPropertiesDoublePrint(const uint header_width=0)
{
//--- get the order symbol and the number of decimal places for the symbol
string symbol = OrderGetString(ORDER_SYMBOL);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);

//--- display the initial volume when placing an order with a header of the specified width in the
OrderPropertyPrint("Volume initial:",header_width,2,ORDER_VOLUME_INITIAL);

//--- display the unfulfilled order volume in the journal


OrderPropertyPrint("Volume current:",header_width,2,ORDER_VOLUME_CURRENT);

//--- display the price, specified in the order, in the journal


OrderPropertyPrint("Price open:",header_width,digits,ORDER_PRICE_OPEN);

//--- display the StopLoss level in the journal


OrderPropertyPrint("StopLoss:",header_width,digits,ORDER_SL);

//--- display the TakeProfit level in the journal


OrderPropertyPrint("TakeProfit:",header_width,digits,ORDER_TP);

//--- display the current price by the order symbol in the journal
OrderPropertyPrint("Price current:",header_width,digits,ORDER_PRICE_CURRENT);

//--- display the Limit order price, when StopLimit order is activated, in the journal

© 2000-2025, MetaQuotes Ltd.


2184 Trade Functions

OrderPropertyPrint("StopLimit:",header_width,digits,ORDER_PRICE_STOPLIMIT);
}
//+------------------------------------------------------------------+
//| Display the order real property value in the journal |
//+------------------------------------------------------------------+
void OrderPropertyPrint(const string header, uint header_width, int digits, ENUM_ORDER_PROPERTY_DOU
{
double value=0;
if(!OrderGetDouble(property, value))
PrintFormat("Cannot get property %s, error=%d", EnumToString(property), GetLastError());
else
{
//--- if the header width is passed to the function equal to zero, then the width will be the
uint w=(header_width==0 ? header.Length()+1 : header_width);
PrintFormat("%-*s%-.*f", w, header, digits, value);
}
}

See also
OrdersTotal(), OrderGetTicket(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2185 Trade Functions

OrderGetInteger
R eturns the requested order property, pre-selected using OrderGetTicket or OrderS elect. Order
property must be of the datetime, int type. There are 2 variants of the function.
1. Immediately returns the property value.
long OrderGetInteger(
ENUM_ORDER_PROPERTY_INTEGER property_id // Property identifier
);

2. R eturns true or false depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool OrderGetInteger(
ENUM_ORDER_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);

Parameters
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM _ORDER_PR OPER T Y_INT EGER enumeration.

long_var
[out] Variable of the long type that accepts the value of the requested property.

Return Value

Value of the long type. If the function fails, 0 is returned.


Note

Do not confuse current pending orders with positions, which are also displayed on the " Trade" tab of
the " Toolbox" of the client terminal.
For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about an order, it is recommended to call OrderS elect() right before
referring to them.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{

© 2000-2025, MetaQuotes Ltd.


2186 Trade Functions

//--- in a loop by the list of all account orders


int total=OrdersTotal();
for(int i=0; i<total; i++)
{
//--- get the order ticket in the list by the loop index
ulong ticket=OrderGetTicket(i);
if(ticket==0)
continue;

//--- get the order type and display the header for the list of real properties of the select
string type=OrderTypeDescription((ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE));
PrintFormat("Integer properties of an active pending order %s #%I64u:", type, ticket);

//--- print all the integer properties of the selected order under the header
OrderPropertiesIntegerPrint(17);
}
/*
result:
Integer properties of an active pending order Buy Limit #2812945317:
Ticket: 2812945317
Time setup: 2024.09.04 19:17:16
Type: Buy Limit
State: Placed
Time expiration: 0
Time done: 0
Time setup msc: 2024.09.04 19:17:16.686
Time done msc: 0
Type filling: Return
Type time: Time GTC
Magic: 0
Reason: Client
Position ID: 0
Position By ID: 0
*/
}
//+------------------------------------------------------------------+
//| Display integer properties of the selected order in the journal |
//+------------------------------------------------------------------+
void OrderPropertiesIntegerPrint(const uint header_width=0)
{
uint w=0;
string header="";
long value=0;

//--- display order ticket in the journal


OrderPropertyPrint("Ticket:", header_width, ORDER_TICKET);

//--- display the order placement time in the journal


OrderPropertyPrint("Time setup:", header_width, ORDER_TIME_SETUP);

© 2000-2025, MetaQuotes Ltd.


2187 Trade Functions

//--- display the order type in the journal


OrderPropertyPrint("Type:", header_width, ORDER_TYPE);

//--- display the order status in the journal


OrderPropertyPrint("State:", header_width, ORDER_STATE);

//--- display the order expiration time in the journal


OrderPropertyPrint("Time expiration:", header_width, ORDER_TIME_EXPIRATION);

//--- display the order execution/expiration time in the journal


OrderPropertyPrint("Time done:", header_width, ORDER_TIME_DONE);

//--- display the time of placing an order for execution in milliseconds since 01.01.1970 in the jo
OrderPropertyPrint("Time setup msc:", header_width, ORDER_TIME_SETUP_MSC);

//--- display the order execution/expiration time in milliseconds since 01.01.1970 in the journal
OrderPropertyPrint("Time done msc:", header_width, ORDER_TIME_DONE_MSC);

//--- display the execution type by residue in the journal


OrderPropertyPrint("Type filling:", header_width, ORDER_TYPE_FILLING);

//--- display the order lifetime in the journal


OrderPropertyPrint("Type time:", header_width, ORDER_TYPE_TIME);

//--- display the ID of the EA, that placed an order, in the journal
OrderPropertyPrint("Magic:", header_width, ORDER_MAGIC);

//--- display order reason or source in the journal


OrderPropertyPrint("Reason:", header_width, ORDER_REASON);

//--- display the ID of the position, set on the order during its execution, in the journal
OrderPropertyPrint("Position ID:", header_width, ORDER_POSITION_ID);

//--- display the opposite position ID for ORDER_TYPE_CLOSE_BY type orders in the journal
OrderPropertyPrint("Position By ID:", header_width, ORDER_POSITION_BY_ID);
}
//+------------------------------------------------------------------+
//| Display the order integer property value in the journal |
//+------------------------------------------------------------------+
void OrderPropertyPrint(const string header, uint header_width, ENUM_ORDER_PROPERTY_INTEGER propert
{
string svalue="";
long lvalue=0;
if(!OrderGetInteger(property, lvalue))
PrintFormat("Cannot get property %s, error=%d", EnumToString(property), GetLastError());
else
{
switch(property)

© 2000-2025, MetaQuotes Ltd.


2188 Trade Functions

{
case ORDER_TICKET :
case ORDER_MAGIC :
case ORDER_POSITION_ID :
case ORDER_POSITION_BY_ID :
svalue=(string)lvalue;
break;

case ORDER_TIME_SETUP :
case ORDER_TIME_EXPIRATION :
case ORDER_TIME_DONE :
svalue=(lvalue!=0 ? TimeToString((datetime)lvalue, TIME_DATE|TIME_MINUTES|TIME_SECONDS)
break;

case ORDER_TIME_SETUP_MSC :
case ORDER_TIME_DONE_MSC :
svalue=(lvalue!=0 ? TimeMscToString(lvalue) : "0");
break;

case ORDER_TYPE :
svalue=OrderTypeDescription((ENUM_ORDER_TYPE)lvalue);
break;
case ORDER_STATE :
svalue=OrderStateDescription((ENUM_ORDER_STATE)lvalue);
break;
case ORDER_TYPE_FILLING :
svalue=OrderTypeFillingDescription((ENUM_ORDER_TYPE_FILLING)lvalue);
break;
case ORDER_TYPE_TIME :
svalue=OrderTypeTimeDescription((ENUM_ORDER_TYPE_TIME)lvalue);
break;
case ORDER_REASON :
svalue=OrderReasonDescription((ENUM_ORDER_REASON)lvalue);
break;

default :
svalue="Unknown property";
break;
}

//--- if the header width is passed to the function equal to zero, then the width will be the
uint w=(header_width==0 ? header.Length()+1 : header_width);
PrintFormat("%-*s%-s", w, header, svalue);
}
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE type)

© 2000-2025, MetaQuotes Ltd.


2189 Trade Functions

{
switch(type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
case ORDER_TYPE_BUY_LIMIT : return("Buy Limit");
case ORDER_TYPE_SELL_LIMIT : return("Sell Limit");
case ORDER_TYPE_BUY_STOP : return("Buy Stop");
case ORDER_TYPE_SELL_STOP : return("Sell Stop");
case ORDER_TYPE_BUY_STOP_LIMIT : return("Buy Stop Limit");
case ORDER_TYPE_SELL_STOP_LIMIT : return("Sell Stop Limit");
default : return("Unknown order type: "+(string)type);
}
}
//+------------------------------------------------------------------+
//| Return the order status description |
//+------------------------------------------------------------------+
string OrderStateDescription(ENUM_ORDER_STATE state)
{
switch(state)
{
case ORDER_STATE_STARTED : return("Started");
case ORDER_STATE_PLACED : return("Placed");
case ORDER_STATE_CANCELED : return("Canceled");
case ORDER_STATE_PARTIAL : return("Partial");
case ORDER_STATE_FILLED : return("Filled");
case ORDER_STATE_REJECTED : return("Rejected");
case ORDER_STATE_EXPIRED : return("Expired");
case ORDER_STATE_REQUEST_ADD : return("Request Add");
case ORDER_STATE_REQUEST_MODIFY : return("Request Modify");
case ORDER_STATE_REQUEST_CANCEL : return("Request Cancel");
default : return("Unknown state: "+(string)state);
}
}
//+------------------------------------------------------------------+
//| Return the description of the order volume filling policy |
//+------------------------------------------------------------------+
string OrderTypeFillingDescription(const ENUM_ORDER_TYPE_FILLING type)
{
switch(type)
{
case ORDER_FILLING_FOK : return("Fill or Kill");
case ORDER_FILLING_IOC : return("Immediate or Cancel");
case ORDER_FILLING_BOC : return("Book or Cancel");
case ORDER_FILLING_RETURN : return("Return");
default : return("Unknown type filling: "+(string)type);
}
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


2190 Trade Functions

//| Return the order expiration date description |


//+------------------------------------------------------------------+
string OrderTypeTimeDescription(const ENUM_ORDER_TYPE_TIME type)
{
switch(type)
{
case ORDER_TIME_GTC : return("Time GTC");
case ORDER_TIME_DAY : return("Time Day");
case ORDER_TIME_SPECIFIED : return("Time Specified");
case ORDER_TIME_SPECIFIED_DAY : return("Time Specified Day");
default : return("Unknown type time: "+(string)type);
}
}
//+------------------------------------------------------------------+
//| Return the order placement reason description |
//+------------------------------------------------------------------+
string OrderReasonDescription(const ENUM_ORDER_REASON reason)
{
switch(reason)
{
case ORDER_REASON_CLIENT : return("Client");
case ORDER_REASON_MOBILE : return("Mobile");
case ORDER_REASON_WEB : return("Web");
case ORDER_REASON_EXPERT : return("Expert");
case ORDER_REASON_SL : return("Stop Loss");
case ORDER_REASON_TP : return("Take Profit");
case ORDER_REASON_SO : return("Stop Out");
default : return("Unknown reason: "+(string)reason);
}
}
//+------------------------------------------------------------------+
//| Return time with milliseconds |
//+------------------------------------------------------------------+
string TimeMscToString(const long time_msc, int flags=TIME_DATE|TIME_MINUTES|TIME_SECONDS)
{
return(TimeToString(time_msc/1000, flags) + "." + IntegerToString(time_msc %1000, 3, '0'));
}

See also
OrdersTotal(), OrderGetTicket(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2191 Trade Functions

OrderGetString
R eturnsthe requested order property, pre-selected using OrderGetTicket or OrderS elect. The order
property must be of the string type. There are 2 variants of the function.
1. Immediately returns the property value.
string OrderGetString(
ENUM_ORDER_PROPERTY_STRING property_id // Property identifier
);

2. R eturns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool OrderGetString(
ENUM_ORDER_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);

Parameters
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM _ORDER_PR OPER T Y_S T R ING enumeration.
string_var
[out] Variable of the string type that accepts the value of the requested property.

Return Value

Value of the string type.


Note

Do not confuse current pending orders with positions, which are also displayed on the " Trade" tab of
the " Toolbox" of the client terminal.
For the " netting " interpretation of positions (ACCOUNT_M ARGIN_MODE_RETAIL_NETTING and
ACCOUNT _M ARGIN_MODE_EXCHANGE), only one position can exist for a symbol at any moment of
time. This position is a result of one or more deals. Do not confuse positions with valid pending
orders, which are also displayed on the Trading tab of the Toolbox window.
If individual positions are allowed (ACCOUNT_M ARGIN_MODE_RETAIL_HEDGING), multiple positions
can be open for one symbol.
To ensure receipt of fresh data about an order, it is recommended to call OrderS elect() right before
referring to them.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{

© 2000-2025, MetaQuotes Ltd.


2192 Trade Functions

//--- in a loop by the list of all account orders


int total=OrdersTotal();
for(int i=0; i<total; i++)
{
//--- get the order ticket in the list by the loop index
ulong ticket=OrderGetTicket(i);
if(ticket==0)
continue;

//--- get the order type and display the header for the list of string properties of the sele
string type=OrderTypeDescription((ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE));
PrintFormat("String properties of an active pending order %s #%I64u:", type, ticket);

//--- print all the string properties of the selected order under the header
OrderPropertiesStringPrint(13);
}
/*
result:
String properties of an active pending order Sell Limit #2813781342:
Comment: Test OrderGetString
Symbol: EURUSD
External ID:
*/
}
//+------------------------------------------------------------------+
//| Display string properties of the selected order in the journal |
//+------------------------------------------------------------------+
void OrderPropertiesStringPrint(const uint header_width=0)
{
//--- display the comment in the journal
OrderPropertyPrint("Comment:", header_width, ORDER_COMMENT);

//--- display a symbol the order has been placed for in the journal
OrderPropertyPrint("Symbol:", header_width, ORDER_SYMBOL);

//--- display the order ID in an external system in the journal


OrderPropertyPrint("External ID:", header_width, ORDER_EXTERNAL_ID);
}
//+------------------------------------------------------------------+
//| Display the order string property value in the journal |
//+------------------------------------------------------------------+
void OrderPropertyPrint(const string header, uint header_width, ENUM_ORDER_PROPERTY_STRING property
{
string value="";
if(!OrderGetString(property, value))
PrintFormat("Cannot get property %s, error=%d", EnumToString(property), GetLastError());
else
{
//--- if the header width is passed to the function equal to zero, then the width will be the

© 2000-2025, MetaQuotes Ltd.


2193 Trade Functions

uint w=(header_width==0 ? header.Length()+1 : header_width);


PrintFormat("%-*s%-s", w, header, value);
}
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE type)
{
switch(type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
case ORDER_TYPE_BUY_LIMIT : return("Buy Limit");
case ORDER_TYPE_SELL_LIMIT : return("Sell Limit");
case ORDER_TYPE_BUY_STOP : return("Buy Stop");
case ORDER_TYPE_SELL_STOP : return("Sell Stop");
case ORDER_TYPE_BUY_STOP_LIMIT : return("Buy Stop Limit");
case ORDER_TYPE_SELL_STOP_LIMIT : return("Sell Stop Limit");
default : return("Unknown order type: "+(string)type);
}
}

See also
OrdersTotal(), OrderGetTicket(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2194 Trade Functions

HistorySelect
R etrieves the history of deals and orders for the specified period of server time.
bool HistorySelect(
datetime from_date, // From date
datetime to_date // To date
);

Parameters
from_date
[in] S tart date of the request.
to_date
[in] End date of the request.

Return Value

It returns true if successful, otherwise returns false.


Note

H istoryS elect()
creates a list of orders and a list of trades in a mql5-program, for further referring
to the list elements using corresponding functions. The deals list size can be returned using the
H istoryDealsTotal() function; the size of the list of orders in the history can be obtained using
H istoryOrdersTotal(). S election in the list of orders should be better performed by
H istoryOrderGetTick et(), for items in the list of deals H istoryDealGetTick et() suits better.

After using HistoryOrderS elect(), the list of history orders available to the mql5 program is reset and
filled again by the found order, if the search of an order by the ticket has been completed
successfully. The same applies to the list of deals available to the mql5 program - it is reset by
H istoryDealS elect() and filled again in case of a successful receipt of a deal by tick et number.

Example:

void OnStart()
{
color BuyColor =clrBlue;
color SellColor=clrRed;
//--- request trade history
HistorySelect(0,TimeCurrent());
//--- create objects
string name;
uint total=HistoryDealsTotal();
ulong ticket=0;
double price;
double profit;
datetime time;
string symbol;
long type;
long entry;
//--- for all deals

© 2000-2025, MetaQuotes Ltd.


2195 Trade Functions

for(uint i=0;i<total;i++)
{
//--- try to get deals ticket
if((ticket=HistoryDealGetTicket(i))>0)
{
//--- get deals properties
price =HistoryDealGetDouble(ticket,DEAL_PRICE);
time =(datetime)HistoryDealGetInteger(ticket,DEAL_TIME);
symbol=HistoryDealGetString(ticket,DEAL_SYMBOL);
type =HistoryDealGetInteger(ticket,DEAL_TYPE);
entry =HistoryDealGetInteger(ticket,DEAL_ENTRY);
profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);
//--- only for current symbol
if(price && time && symbol==Symbol())
{
//--- create price object
name="TradeHistory_Deal_"+string(ticket);
if(entry) ObjectCreate(0,name,OBJ_ARROW_RIGHT_PRICE,0,time,price,0,0);
else ObjectCreate(0,name,OBJ_ARROW_LEFT_PRICE,0,time,price,0,0);
//--- set object properties
ObjectSetInteger(0,name,OBJPROP_SELECTABLE,0);
ObjectSetInteger(0,name,OBJPROP_BACK,0);
ObjectSetInteger(0,name,OBJPROP_COLOR,type?BuyColor:SellColor);
if(profit!=0) ObjectSetString(0,name,OBJPROP_TEXT,"Profit: "+string(profit));
}
}
}
//--- apply on chart
ChartRedraw();
}

See also
H istoryOrderS elect(), H istoryDealS elect()

© 2000-2025, MetaQuotes Ltd.


2196 Trade Functions

HistorySelectByPosition
R etrieves the history of deals and orders having the specified position identifier.
bool HistorySelectByPosition(
long position_id // position identifier - POSITION_IDENTIFIER
);

Parameters
position_id
[in] Position identifier that is set to every executed order and every deal.

Return Value

It returns true if successful, otherwise returns false.


Note

Do not confuse orders of a trading history with current pending orders that appear on the " Trade"
tab of the " Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of " Toolbox" of the client terminal.
H istoryS electByPosition()creates in a mql5 program a list of orders and a list of deals with a
specified position identifier for further reference to the elements of the list using the appropriate
functions. To know the size of the list of deals, use function HistoryDealsTotal(), the size of the list
of orders in the history can be obtained using HistoryOrdersTotal(). To run through elements of the
orders list, use HistoryOrderGetTicket(), for elements of the deals list - HistoryDealGetTicket().
After using HistoryOrderS elect(), list of history orders available to the mql5 program is reset and
filled again with the found order, if search of an order by its ticket was successful. The same refers
to the list of deals available to the mql5 program - it is reset by function HistoryDealS elect() and is
filled out again if a deal was found successfully by the ticket number.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
long pos_id_array[]; // array for storing position IDs

//--- request the entire history


if(!HistorySelect(0, TimeCurrent()))
{
Print("HistorySelect() failed. Error ", GetLastError());
return;
}

//--- collect all Position IDs from pending orders only in the array
int total=HistoryOrdersTotal();
for(int i=0; i<total; i++)

© 2000-2025, MetaQuotes Ltd.


2197 Trade Functions

{
ulong ticket=HistoryOrderGetTicket(i);
if(ticket==0)
continue;
ENUM_ORDER_TYPE type=(ENUM_ORDER_TYPE)HistoryOrderGetInteger(ticket, ORDER_TYPE);
long pos_id=HistoryOrderGetInteger(ticket, ORDER_POSITION_ID);
if(type<=ORDER_TYPE_SELL || pos_id==0)
continue;

int size=ArraySize(pos_id_array);
if(ArrayResize(pos_id_array, size+1)==size+1)
pos_id_array[size]=pos_id;
}

//--- by list of position IDs in the array


total=ArraySize(pos_id_array);
for(int i=0; i<total; i++)
{
//--- print the header, as well as the position order and deal list
long position_id=pos_id_array[i];
Print("List of orders and deals for position with ID: ", position_id);
HistorySelectByPositionProcess(position_id);
}
/*
result:
List of orders and deals for position with ID: 1819629924
[0] Order Sell Limit #1819629924
[1] Order Buy #1819633194
[0] Entry In Deal Sell #1794972472
[1] Entry Out Deal Buy #1794975589
List of orders and deals for position with ID: 1841753970
[0] Order Sell Stop #1841753970
[1] Order Buy #1842322160
[0] Entry In Deal Sell #1817242142
[1] Entry Out Deal Buy #1817765341
*/
}
//+------------------------------------------------------------------+
//| Select history of orders and deals by position ID and |
//| prints a list of orders and deals for the position in the journal|
//+------------------------------------------------------------------+
bool HistorySelectByPositionProcess(const long position_id)
{
//--- request the history of deals and orders having the specified position ID
if(!HistorySelectByPosition(position_id))
{
PrintFormat("HistorySelectByPosition(%I64d) failed. Error %d", position_id, GetLastError());
return(false);
}

© 2000-2025, MetaQuotes Ltd.


2198 Trade Functions

//--- print a list of position orders


int orders_total=HistoryOrdersTotal();
for(int i=0; i<orders_total; i++)
{
ulong ticket=HistoryOrderGetTicket(i);
if(ticket==0)
continue;
ENUM_ORDER_TYPE order_type=(ENUM_ORDER_TYPE)HistoryOrderGetInteger(ticket, ORDER_TYPE);
PrintFormat(" [%d] Order %s #%I64u", i, OrderTypeDescription(order_type), ticket);
}

//--- print a list of position deals in the journal


int deals_total =HistoryDealsTotal();
for(int i=0; i<deals_total; i++)
{
ulong ticket=HistoryDealGetTicket(i);
if(ticket==0)
continue;
ENUM_DEAL_ENTRY deal_entry=(ENUM_DEAL_ENTRY)HistoryDealGetInteger(ticket, DEAL_ENTRY);
ENUM_DEAL_TYPE deal_type= (ENUM_DEAL_TYPE)HistoryDealGetInteger(ticket, DEAL_TYPE);
if(deal_type!=DEAL_TYPE_BUY && deal_type!=DEAL_TYPE_SELL)
continue;
PrintFormat(" [%d] Entry %s Deal %s #%I64u", i, DealEntryDescription(deal_entry), DealTypeDe
}
return(true);
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE type)
{
switch(type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
case ORDER_TYPE_BUY_LIMIT : return("Buy Limit");
case ORDER_TYPE_SELL_LIMIT : return("Sell Limit");
case ORDER_TYPE_BUY_STOP : return("Buy Stop");
case ORDER_TYPE_SELL_STOP : return("Sell Stop");
case ORDER_TYPE_BUY_STOP_LIMIT : return("Buy Stop Limit");
case ORDER_TYPE_SELL_STOP_LIMIT : return("Sell Stop Limit");
default : return("Unknown order type: "+(string)type);
}
}
//+------------------------------------------------------------------+
//| Return the position deal type description |
//+------------------------------------------------------------------+
string DealTypeDescription(const ENUM_DEAL_TYPE type)

© 2000-2025, MetaQuotes Ltd.


2199 Trade Functions

{
switch(type)
{
//--- return the description of the Buy and Sell deals only,
//--- since all other types do not apply to the position
case DEAL_TYPE_BUY : return("Buy");
case DEAL_TYPE_SELL : return("Sell");
default : return("Unknown deal type: "+(string)type);
}
}
//+------------------------------------------------------------------+
//| Return position change method |
//+------------------------------------------------------------------+
string DealEntryDescription(const ENUM_DEAL_ENTRY entry)
{
switch(entry)
{
case DEAL_ENTRY_IN : return("In");
case DEAL_ENTRY_OUT : return("Out");
case DEAL_ENTRY_INOUT : return("InOut");
case DEAL_ENTRY_OUT_BY : return("Out by");
case DEAL_ENTRY_STATE : return("Status record");
default : return("Unknown deal entry: "+(string)entry);
}
}

See also
H istoryS elect(), H istoryOrderGetTick et(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2200 Trade Functions

HistoryOrderSelect
S electsan order from the history for further calling it through appropriate functions. It returns true if
the function has been successfully completed. Returns false if the function has failed. For more details
on error call GetLastError().
bool HistoryOrderSelect(
ulong ticket // Order ticket
);

Parameters
ticket
[in] Order ticket.

Return Value

R eturns true if successful, otherwise false.


Note

Do not confuse orders of a trading history with current pending orders that appear on the " Trade"
tab of the " Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of " Toolbox" of the client terminal.
H istoryOrderS elect()clears in a mql5-program the list of orders from a history, available for calls,
and copies to it a single order, if the execution of HistoryOrderS elect () has been completed
successfully. If you need to go through all orders selected by HistoryS elect(), you should better use
H istoryOrderGetTick et().

Example:

#define TICKET 1819621374 // ticket of any known order, for example, from the account histor
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- select a historical order by the ticket specified in TICKET
if(!HistoryOrderSelect(TICKET))
{
PrintFormat("HistoryOrderSelect(%I64u) failed. Error %d", TICKET, GetLastError());
return;
}

//--- if an order is successfully selected, get its data and display the order description in the j
ENUM_ORDER_TYPE order_type = (ENUM_ORDER_TYPE)HistoryOrderGetInteger(TICKET, ORDER_TYPE);
ENUM_ORDER_STATE order_state = (ENUM_ORDER_STATE)HistoryOrderGetInteger(TICKET, ORDER_STATE);
ENUM_ORDER_REASON order_reason= (ENUM_ORDER_REASON)HistoryOrderGetInteger(TICKET, ORDER_REASON);
long order_time = HistoryOrderGetInteger(TICKET, ORDER_TIME_SETUP_MSC);
string order_symbol=HistoryOrderGetString(TICKET, ORDER_SYMBOL);
double order_vol_init=HistoryOrderGetDouble(TICKET, ORDER_VOLUME_INITIAL);

© 2000-2025, MetaQuotes Ltd.


2201 Trade Functions

double order_vol_curr=HistoryOrderGetDouble(TICKET, ORDER_VOLUME_CURRENT);


PrintFormat("%s Order %.2f/%s %s #%I64u %s by %s at %s",
order_symbol, order_vol_init, (order_vol_curr>0 ? DoubleToString(order_vol_curr,2) :
OrderTypeDescription(order_type), TICKET, OrderStateDescription(order_state),
OrderReasonDescription(order_reason), TimeMscToString(order_time));
/*
result for various specified tickets:
EURUSD Order 0.50/0.50 Buy Limit #2812894647 Canceled by Client at 2024.09.04 19:02:31.793
EURUSD Order 0.10/0 Sell #1753011743 Filled by Take Profit at 2023.06.12 17:04:20.353
GBPUSD Order 0.10/0 Buy #1819621374 Filled by Client at 2023.07.24 06:16:25.746
*/
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE type)
{
switch(type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
case ORDER_TYPE_BUY_LIMIT : return("Buy Limit");
case ORDER_TYPE_SELL_LIMIT : return("Sell Limit");
case ORDER_TYPE_BUY_STOP : return("Buy Stop");
case ORDER_TYPE_SELL_STOP : return("Sell Stop");
case ORDER_TYPE_BUY_STOP_LIMIT : return("Buy Stop Limit");
case ORDER_TYPE_SELL_STOP_LIMIT : return("Sell Stop Limit");
default : return("Unknown order type: "+(string)type);
}
}
//+------------------------------------------------------------------+
//| Return the order status description |
//+------------------------------------------------------------------+
string OrderStateDescription(ENUM_ORDER_STATE state)
{
switch(state)
{
case ORDER_STATE_STARTED : return("Started");
case ORDER_STATE_PLACED : return("Placed");
case ORDER_STATE_CANCELED : return("Canceled");
case ORDER_STATE_PARTIAL : return("Partial");
case ORDER_STATE_FILLED : return("Filled");
case ORDER_STATE_REJECTED : return("Rejected");
case ORDER_STATE_EXPIRED : return("Expired");
case ORDER_STATE_REQUEST_ADD : return("Request Add");
case ORDER_STATE_REQUEST_MODIFY : return("Request Modify");
case ORDER_STATE_REQUEST_CANCEL : return("Request Cancel");
default : return("Unknown state: "+(string)state);
}

© 2000-2025, MetaQuotes Ltd.


2202 Trade Functions

}
//+------------------------------------------------------------------+
//| Return the order placement reason description |
//+------------------------------------------------------------------+
string OrderReasonDescription(const ENUM_ORDER_REASON reason)
{
switch(reason)
{
case ORDER_REASON_CLIENT : return("Client");
case ORDER_REASON_MOBILE : return("Mobile");
case ORDER_REASON_WEB : return("Web");
case ORDER_REASON_EXPERT : return("Expert");
case ORDER_REASON_SL : return("Stop Loss");
case ORDER_REASON_TP : return("Take Profit");
case ORDER_REASON_SO : return("Stop Out");
default : return("Unknown reason: "+(string)reason);
}
}
//+------------------------------------------------------------------+
//| Return time with milliseconds |
//+------------------------------------------------------------------+
string TimeMscToString(const long time_msc, int flags=TIME_DATE|TIME_MINUTES|TIME_SECONDS)
{
return(TimeToString(time_msc/1000, flags) + "." + IntegerToString(time_msc %1000, 3, '0'));
}

See also
H istoryS elect(), H istoryOrderGetTick et(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2203 Trade Functions

HistoryOrdersTotal
R eturnsthe number of orders in the history. Prior to calling HistoryOrdersTotal(), first it is necessary
to receive the history of deals and orders using the HistoryS elect() or HistoryS electByPosition()
function.
int HistoryOrdersTotal();

Return Value

Value of the int type.


Note

Do not confuse orders of a trading history with current pending orders that appear on the " Trade"
tab of the " Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of " Toolbox" of the client terminal.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- request all the existing history on the account
if(!HistorySelect(0, TimeCurrent()))
{
Print("HistorySelect() failed. Error ", GetLastError());
return;
}

//--- get the number of orders in the list and display it in the journal
int total=HistoryOrdersTotal();
Print("Number of historical orders on the account: ", total);
/*
result:
Number of historical orders on the account: 496
*/
}

See also
H istoryS elect(), H istoryOrderS elect(), H istoryOrderGetTick et(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2204 Trade Functions

HistoryOrderGetTicket
R eturn the tick et ofa corresponding order in the history. Prior to calling HistoryOrderGetTicket(), first
it is necessary to receive the history of deals and orders using the HistoryS elect() or
H istoryS electByPosition() function.

ulong HistoryOrderGetTicket(
int index // Number in the list of orders
);

Parameters
index
[in] Number of the order in the list of orders.

Return Value

Value of the ulong type. If the function fails, 0 is returned.


Note

Do not confuse orders of a trading history with current pending orders that appear on the " Trade"
tab of the " Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of " Toolbox" of the client terminal.
Example:

void OnStart()
{
datetime from=0;
datetime to=TimeCurrent();
//--- request the entire history
HistorySelect(from,to);
//--- variables for returning values from order properties
ulong ticket;
double open_price;
double initial_volume;
datetime time_setup;
datetime time_done;
string symbol;
string type;
long order_magic;
long positionID;
//--- number of current pending orders
uint total=HistoryOrdersTotal();
//--- go through orders in a loop
for(uint i=0;i<total;i++)
{
//--- return order ticket by its position in the list
if((ticket=HistoryOrderGetTicket(i))>0)
{
//--- return order properties

© 2000-2025, MetaQuotes Ltd.


2205 Trade Functions

open_price =HistoryOrderGetDouble(ticket,ORDER_PRICE_OPEN);
time_setup =(datetime)HistoryOrderGetInteger(ticket,ORDER_TIME_SETUP);
time_done =(datetime)HistoryOrderGetInteger(ticket,ORDER_TIME_DONE);
symbol =HistoryOrderGetString(ticket,ORDER_SYMBOL);
order_magic =HistoryOrderGetInteger(ticket,ORDER_MAGIC);
positionID =HistoryOrderGetInteger(ticket,ORDER_POSITION_ID);
initial_volume=HistoryOrderGetDouble(ticket,ORDER_VOLUME_INITIAL);
type =GetOrderType(HistoryOrderGetInteger(ticket,ORDER_TYPE));
//--- prepare and show information about the order
printf("#ticket %d %s %G %s at %G was set up at %s => done at %s, pos ID=%d",
ticket, // order ticket
type, // type
initial_volume, // placed volume
symbol, // symbol
open_price, // specified open price
TimeToString(time_setup),// time of order placing
TimeToString(time_done), // time of order execution or deletion
positionID // ID of a position , to which the deal of the order is in
);
}
}
//---
}
//+------------------------------------------------------------------+
//| Returns the string name of the order type |
//+------------------------------------------------------------------+
string GetOrderType(long type)
{
string str_type="unknown operation";
switch(type)
{
case (ORDER_TYPE_BUY): return("buy");
case (ORDER_TYPE_SELL): return("sell");
case (ORDER_TYPE_BUY_LIMIT): return("buy limit");
case (ORDER_TYPE_SELL_LIMIT): return("sell limit");
case (ORDER_TYPE_BUY_STOP): return("buy stop");
case (ORDER_TYPE_SELL_STOP): return("sell stop");
case (ORDER_TYPE_BUY_STOP_LIMIT): return("buy stop limit");
case (ORDER_TYPE_SELL_STOP_LIMIT):return("sell stop limit");
}
return(str_type);
}

See also
H istoryS elect(), H istoryOrdersTotal(), H istoryOrderS elect(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2206 Trade Functions

HistoryOrderGetDouble
R eturns the requested order property. The order property must be of the double type. There are 2
variants of the function.
1. Immediately returns the property value.
double HistoryOrderGetDouble(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_DOUBLE property_id // Property identifier
);

2. R eturns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryOrderGetDouble(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);

Parameters
ticket_number
[in] Order ticket.
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM _ORDER_PR OPER T Y_DOUBL E enumeration.

double_var
[out] Variable of the double type that accepts the value of the requested property.

Return Value

Value of the double type.


Note

Do not confuse orders of a trading history with current pending orders that appear on the " Trade"
tab of the " Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of " Toolbox" of the client terminal.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- request deal and order history
if(!HistorySelect(0, TimeCurrent()))
{

© 2000-2025, MetaQuotes Ltd.


2207 Trade Functions

Print("HistorySelect() failed. Error ", GetLastError());


return;
}

//--- in a loop by the list of all historical orders on the account


int total=HistoryOrdersTotal();
for(int i=0; i<total; i++)
{
//--- get the order ticket in the list by the loop index
ulong ticket=HistoryOrderGetTicket(i);
if(ticket==0)
continue;

//--- get the order type and display the header for the list of real properties of the select
string type=OrderTypeDescription((ENUM_ORDER_TYPE)HistoryOrderGetInteger(ticket, ORDER_TYPE))
PrintFormat("Double properties of an history order %s #%I64u:", type, ticket);

//--- print all the real properties of the selected order under the header
HistoryOrderPropertiesDoublePrint(ticket, 16);
}
/*
result:
Double properties of an history order Sell #2810847541:
Volume initial: 0.50
Volume current: 0.00
Price open: 1.10491
StopLoss: 0.00000
TakeProfit: 0.00000
Price current: 1.10491
StopLimit: 0.00000
Double properties of an history order Buy Limit #2811003507:
Volume initial: 1.00
Volume current: 1.00
Price open: 1.10547
StopLoss: 0.00000
TakeProfit: 0.00000
Price current: 1.10591
StopLimit: 0.00000
*/
}
//+------------------------------------------------------------------+
//| Display real properties of the |
//| selected historical order in the journal |
//+------------------------------------------------------------------+
void HistoryOrderPropertiesDoublePrint(const long ticket, const uint header_width=0)
{
uint w=0;
string header="";
double value=0;

© 2000-2025, MetaQuotes Ltd.


2208 Trade Functions

//--- get the order symbol and the number of decimal places for the symbol
string symbol = HistoryOrderGetString(ticket, ORDER_SYMBOL);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);

//--- define the header text and the width of the header field
//--- if the header width is passed to the function equal to zero, then the width will be the size
header="Volume initial:";
w=(header_width==0 ? header.Length()+1 : header_width);
//--- get and display the initial volume when placing an order with a header of the specified width
if(!HistoryOrderGetDouble(ticket, ORDER_VOLUME_INITIAL, value))
return;
PrintFormat("%-*s%-.2f", w, header, value);

//--- display the unfulfilled order volume in the journal


header="Volume current:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryOrderGetDouble(ticket, ORDER_VOLUME_CURRENT, value))
return;
PrintFormat("%-*s%-.2f", w, header, value);

//--- display the price, specified in the order, in the journal


header="Price open:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryOrderGetDouble(ticket, ORDER_PRICE_OPEN, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

//--- display the StopLoss level in the journal


header="StopLoss:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryOrderGetDouble(ticket, ORDER_SL, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

//--- display the TakeProfit level in the journal


header="TakeProfit:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryOrderGetDouble(ticket, ORDER_TP, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

//--- display the current price by the order symbol in the journal
header="Price current:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryOrderGetDouble(ticket, ORDER_PRICE_CURRENT, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

© 2000-2025, MetaQuotes Ltd.


2209 Trade Functions

//--- display the Limit order price, when StopLimit order is activated, in the journal
header="StopLimit:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryOrderGetDouble(ticket, ORDER_PRICE_STOPLIMIT, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE type)
{
switch(type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
case ORDER_TYPE_BUY_LIMIT : return("Buy Limit");
case ORDER_TYPE_SELL_LIMIT : return("Sell Limit");
case ORDER_TYPE_BUY_STOP : return("Buy Stop");
case ORDER_TYPE_SELL_STOP : return("Sell Stop");
case ORDER_TYPE_BUY_STOP_LIMIT : return("Buy Stop Limit");
case ORDER_TYPE_SELL_STOP_LIMIT : return("Sell Stop Limit");
default : return("Unknown order type");
}
}

See also
H istoryS elect(), H istoryOrdersTotal(), H istoryOrderS elect(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2210 Trade Functions

HistoryOrderGetInteger
R eturns the requested property of an order. The order property must be of datetime, int type. There
are 2 variants of the function.
1. Immediately returns the property value.
long HistoryOrderGetInteger(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_INTEGER property_id // Property identifier
);

2. R eturns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryOrderGetInteger(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);

Parameters
ticket_number
[in] Order ticket.
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM _ORDER_PR OPER T Y_INT EGER enumeration.

long_var
[out] Variable of the long type that accepts the value of the requested property.

Return Value

Value of the long type.


Note

Do not confuse orders of a trading history with current pending orders that appear on the " Trade"
tab of the " Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of " Toolbox" of the client terminal.
Example:

//+------------------------------------------------------------------+
//| Trade function |
//+------------------------------------------------------------------+
void OnTrade()
{
//--- receive the last order's ticket from week's trading history
ulong last_order=GetLastOrderTicket();
if(HistoryOrderSelect(last_order))

© 2000-2025, MetaQuotes Ltd.


2211 Trade Functions

{
//--- time of placing an order in milliseconds since 01.01.1970
long time_setup_msc=HistoryOrderGetInteger(last_order,ORDER_TIME_SETUP_MSC);
PrintFormat("Order #%d ORDER_TIME_SETUP_MSC=%i64 => %s",
last_order,time_setup_msc,TimeToString(time_setup_msc/1000));
//--- order execution/cancellation time in milliseconds since 01.01.1970
long time_done_msc=HistoryOrderGetInteger(last_order,ORDER_TIME_DONE_MSC);
PrintFormat("Order #%d ORDER_TIME_DONE_MSC=%i64 => %s",
last_order,time_done_msc,TimeToString(time_done_msc/1000));
}
else // notify on failure
PrintFormat("HistoryOrderSelect() failed for #%d. Eror code=%d",
last_order,GetLastError());

//---
}
//+------------------------------------------------------------------+
//| Returns the last order ticket in history or -1 |
//+------------------------------------------------------------------+
ulong GetLastOrderTicket()
{
//--- request history for the last 7 days
if(!GetTradeHistory(7))
{
//--- notify on unsuccessful call and return -1
Print(__FUNCTION__," HistorySelect() returned false");
return -1;
}
//---
ulong first_order,last_order,orders=HistoryOrdersTotal();
//--- work with orders if there are any
if(orders>0)
{
Print("Orders = ",orders);
first_order=HistoryOrderGetTicket(0);
PrintFormat("first_order = %d",first_order);
if(orders>1)
{
last_order=HistoryOrderGetTicket((int)orders-1);
PrintFormat("last_order = %d",last_order);
return last_order;
}
return first_order;
}
//--- no order found, return -1
return -1;
}
//+--------------------------------------------------------------------------+
//| Requests history for the last days and returns false in case of failure |

© 2000-2025, MetaQuotes Ltd.


2212 Trade Functions

//+--------------------------------------------------------------------------+
bool GetTradeHistory(int days)
{
//--- set a week period to request trade history
datetime to=TimeCurrent();
datetime from=to-days*PeriodSeconds(PERIOD_D1);
ResetLastError();
//--- make a request and check the result
if(!HistorySelect(from,to))
{
Print(__FUNCTION__," HistorySelect=false. Error code=",GetLastError());
return false;
}
//--- history received successfully
return true;
}

See also
H istoryS elect(), H istoryOrdersTotal(), H istoryOrderS elect(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2213 Trade Functions

HistoryOrderGetString
R eturnsthe requested property of an order. The order property must be of the string type. There are 2
variants of the function.
1. Immediately returns the property value.
string HistoryOrderGetString(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_STRING property_id // Property identifier
);

2. R eturns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryOrderGetString(
ulong ticket_number, // Ticket
ENUM_ORDER_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);

Parameters
ticket_number
[in] Order ticket.
property_id
[in] Identifier of the order property. The value can be one of the values of the
ENUM _ORDER_PR OPER T Y_S T R ING enumeration.
string_var
[out] Variable of the string type.

Return Value

Value of the string type.


Note

Do not confuse orders of a trading history with current pending orders that appear on the " Trade"
tab of the " Toolbox" bar. The list of orders that were canceled or have led to a transaction, can be
viewed in the "History" tab of " Toolbox" of the client terminal.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- request deal and order history
if(!HistorySelect(0, TimeCurrent()))
{

© 2000-2025, MetaQuotes Ltd.


2214 Trade Functions

Print("HistorySelect() failed. Error ", GetLastError());


return;
}

//--- in a loop by the list of all historical orders on the account


int total=HistoryOrdersTotal();
for(int i=0; i<total; i++)
{
//--- get the order ticket in the list by the loop index
ulong ticket=HistoryOrderGetTicket(i);
if(ticket==0)
continue;

//--- get the order type and display the header for the list of string properties of the sele
string type=OrderTypeDescription((ENUM_ORDER_TYPE)HistoryOrderGetInteger(ticket, ORDER_TYPE))
PrintFormat("String properties of an history order %s #%I64u:", type, ticket);

//--- print all the string properties of the selected order under the header
HistoryOrderPropertiesStringPrint(ticket, 16);
}
/*
result:
String properties of an history order Buy #2646074112:
Comment: [tp 1.09137]
Symbol: EURUSD
External ID:
String properties of an history order Buy #2646131906:
Comment:
Symbol: EURUSD
External ID:
*/
}
//+------------------------------------------------------------------+
//| Display string properties of the |
//| selected historical order in the journal |
//+------------------------------------------------------------------+
void HistoryOrderPropertiesStringPrint(const long ticket, const uint header_width=0)
{
uint w=0;
string header="";
string value="";

//--- define the header text and the width of the header field
//--- if the header width is passed to the function equal to zero, then the width will be the size
header="Comment:";
w=(header_width==0 ? header.Length()+1 : header_width);
//--- get and display the comment with the specified header width in the journal
if(!HistoryOrderGetString(ticket, ORDER_COMMENT, value))
return;

© 2000-2025, MetaQuotes Ltd.


2215 Trade Functions

PrintFormat("%-*s%-s", w, header, value);

//--- display a symbol the order has been placed for in the journal
header="Symbol:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryOrderGetString(ticket, ORDER_SYMBOL, value))
return;
PrintFormat("%-*s%-s", w, header, value);

//--- display the order ID in an external system in the journal


header="External ID:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryOrderGetString(ticket, ORDER_EXTERNAL_ID, value))
return;
PrintFormat("%-*s%-s", w, header, value);
}
//+------------------------------------------------------------------+
//| Return the order type description |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE type)
{
switch(type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
case ORDER_TYPE_BUY_LIMIT : return("Buy Limit");
case ORDER_TYPE_SELL_LIMIT : return("Sell Limit");
case ORDER_TYPE_BUY_STOP : return("Buy Stop");
case ORDER_TYPE_SELL_STOP : return("Sell Stop");
case ORDER_TYPE_BUY_STOP_LIMIT : return("Buy Stop Limit");
case ORDER_TYPE_SELL_STOP_LIMIT : return("Sell Stop Limit");
default : return("Unknown order type: "+(string)type);
}
}

See also
H istoryS elect(), H istoryOrdersTotal(), H istoryOrderS elect(), Order Properties

© 2000-2025, MetaQuotes Ltd.


2216 Trade Functions

HistoryDealSelect
S electsa deal in the history for further calling it through appropriate functions. It returns true if the
function has been successfully completed. Returns false if the function has failed. For more details on
error call GetLastError().
bool HistoryDealSelect(
ulong ticket // Deal ticket
);

Parameters
ticket
[in] Deal tick et.

Return Value

R eturns true if successful, otherwise false.


Note

Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
H istoryDealS elect()clears in a mql5-program the list of deals available for reference, and copies the
single deal, if the execution of HistoryDealS elect() has been completed successfully. If you need to
go through all deals selected by the HistoryS elect() function, you should better use
H istoryDealGetTick et().

Example:

#define TICKET 2620919264 // ticket of any known deal, for example, from the terminal accoun

long ExtTicket=TICKET; // set the specified ticket to the variable from the macro substit
// or handle deals in the OnTradeTransaction() handler in the EA:
//+------------------------------------------------------------------+
//| Expert TradeTransaction handler |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
const MqlTradeRequest& request,
const MqlTradeResult& result)
{
//--- if a transaction is adding a deal to history
if(trans.type==TRADE_TRANSACTION_DEAL_ADD)
{
//--- select a deal by ticket, get its data and display the deal description in the journal
HistoryDealSelectProcess(trans.deal);
}
}

//+------------------------------------------------------------------+
//| Script program start function |

© 2000-2025, MetaQuotes Ltd.


2217 Trade Functions

//+------------------------------------------------------------------+
void OnStart()
{
//--- select a deal by ticket, get its data and display the deal description in the journal
HistoryDealSelectProcess(ExtTicket);
/*
result:
(Position ID #2645974677) EURUSD Deal Out 0.10 Buy #2620919264 by order #2646028969 at 1.09178,
*/
}
//+------------------------------------------------------------------+
//| Select a deal by ticket and print the deal data in the journal |
//+------------------------------------------------------------------+
void HistoryDealSelectProcess(const ulong deal_ticket)
{
//--- select a historical deal by the ticket specified in deal_ticket
ResetLastError();
if(!HistoryDealSelect(deal_ticket))
{
PrintFormat("HistoryDealSelect(%I64u) failed. Error %d", deal_ticket, GetLastError());
return;
}

//--- if a deal is successfully selected, get its data and display the deal description in the jour
ENUM_DEAL_TYPE deal_type = (ENUM_DEAL_TYPE)HistoryDealGetInteger(ExtTicket, DEAL_TYPE);
ENUM_DEAL_ENTRY deal_entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(ExtTicket, DEAL_ENTRY);
ENUM_DEAL_REASON deal_reason= (ENUM_DEAL_REASON)HistoryDealGetInteger(ExtTicket, DEAL_REASON);
long deal_time = HistoryDealGetInteger(ExtTicket, DEAL_TIME_MSC);
long deal_order = HistoryDealGetInteger(ExtTicket, DEAL_ORDER);
long deal_pos_id= HistoryDealGetInteger(ExtTicket, DEAL_POSITION_ID);
string deal_symbol= HistoryDealGetString(ExtTicket, DEAL_SYMBOL);
double deal_volume= HistoryDealGetDouble(ExtTicket, DEAL_VOLUME);
double deal_price = HistoryDealGetDouble(ExtTicket, DEAL_PRICE);
int digits = (int)SymbolInfoInteger(deal_symbol, SYMBOL_DIGITS);

PrintFormat("(Position ID #%I64d) %s Deal %s %.2f %s #%I64u by order #%I64d at %.*f, %s",


deal_pos_id, deal_symbol, DealEntryDescription(deal_entry), deal_volume,
DealTypeDescription(deal_type), ExtTicket, deal_order, digits, deal_price,
TimeMscToString(deal_time));
}
//+------------------------------------------------------------------+
//| Return the deal type description |
//+------------------------------------------------------------------+
string DealTypeDescription(const ENUM_DEAL_TYPE type)
{
switch(type)
{
case DEAL_TYPE_BUY : return("Buy");
case DEAL_TYPE_SELL : return("Sell");

© 2000-2025, MetaQuotes Ltd.


2218 Trade Functions

case DEAL_TYPE_BALANCE : return("Balance");


case DEAL_TYPE_CREDIT : return("Credit");
case DEAL_TYPE_CHARGE : return("Additional charge");
case DEAL_TYPE_CORRECTION : return("Correction");
case DEAL_TYPE_BONUS : return("Bonus");
case DEAL_TYPE_COMMISSION : return("Additional commission");
case DEAL_TYPE_COMMISSION_DAILY : return("Daily commission");
case DEAL_TYPE_COMMISSION_MONTHLY : return("Monthly commission");
case DEAL_TYPE_COMMISSION_AGENT_DAILY : return("Daily agent commission");
case DEAL_TYPE_COMMISSION_AGENT_MONTHLY: return("Monthly agent commission");
case DEAL_TYPE_INTEREST : return("Interest rate");
case DEAL_TYPE_BUY_CANCELED : return("Canceled buy deal");
case DEAL_TYPE_SELL_CANCELED : return("Canceled sell deal");
case DEAL_DIVIDEND : return("Dividend operations");
case DEAL_DIVIDEND_FRANKED : return("Franked (non-taxable) dividend operations")
case DEAL_TAX : return("Tax charges");
default : return("Unknown deal type: "+(string)type);
}
}
//+------------------------------------------------------------------+
//| Return position change method |
//+------------------------------------------------------------------+
string DealEntryDescription(const ENUM_DEAL_ENTRY entry)
{
switch(entry)
{
case DEAL_ENTRY_IN : return("In");
case DEAL_ENTRY_OUT : return("Out");
case DEAL_ENTRY_INOUT : return("Reverce");
case DEAL_ENTRY_OUT_BY : return("Out by");
case DEAL_ENTRY_STATE : return("Status record");
default : return("Unknown deal entry: "+(string)entry);
}
}
//+------------------------------------------------------------------+
//| Return time with milliseconds |
//+------------------------------------------------------------------+
string TimeMscToString(const long time_msc, int flags=TIME_DATE|TIME_MINUTES|TIME_SECONDS)
{
return(TimeToString(time_msc/1000, flags) + "." + IntegerToString(time_msc %1000, 3, '0'));
}

See also
H istoryS elect(), H istoryDealGetTick et(), Deal Properties

© 2000-2025, MetaQuotes Ltd.


2219 Trade Functions

HistoryDealsTotal
R eturns the number of deal in history. Prior to calling HistoryDealsTotal(), first it is necessary to
receive the history of deals and orders using the HistoryS elect() or HistoryS electByPosition() function.
int HistoryDealsTotal();

Return Value

Value of the int type.


Note

Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- request all the existing history on the account
if(!HistorySelect(0, TimeCurrent()))
{
Print("HistorySelect() failed. Error ", GetLastError());
return;
}

//--- get the number of deals in the list and display it in the journal
int total=HistoryDealsTotal();
Print("Number of historical deals on the account: ", total);
/*
result:
Number of historical deals on the account: 339
*/
}

See also
H istoryS elect(), H istoryDealGetTick et(), Deal Properties

© 2000-2025, MetaQuotes Ltd.


2220 Trade Functions

HistoryDealGetTicket
The function selects a deal for further processing and returns the deal ticket in history. Prior to calling
H istoryDealGetTick et(), first it is necessary to receive the history of deals and orders using the
H istoryS elect() or H istoryS electByPosition() function.

ulong HistoryDealGetTicket(
int index // ticket deal
);

Parameters
index
[in] Number of a deal in the list of deals

Return Value

Value of the ulong type. If the function fails, 0 is returned.


Note

Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
Example:

void OnStart()
{
ulong deal_ticket; // deal ticket
ulong order_ticket; // ticket of the order the deal was executed on
datetime transaction_time; // time of a deal execution
long deal_type ; // type of a trade operation
long position_ID; // position ID
string deal_description; // operation description
double volume; // operation volume
string symbol; // symbol of the deal
//--- set the start and end date to request the history of deals
datetime from_date=0; // from the very beginning
datetime to_date=TimeCurrent();// till the current moment
//--- request the history of deals in the specified period
HistorySelect(from_date,to_date);
//--- total number in the list of deals
int deals=HistoryDealsTotal();
//--- now process each trade
for(int i=0;i<deals;i++)
{
deal_ticket= HistoryDealGetTicket(i);
volume= HistoryDealGetDouble(deal_ticket,DEAL_VOLUME);
transaction_time=(datetime)HistoryDealGetInteger(deal_ticket,DEAL_TIME);
order_ticket= HistoryDealGetInteger(deal_ticket,DEAL_ORDER);
deal_type= HistoryDealGetInteger(deal_ticket,DEAL_TYPE);
symbol= HistoryDealGetString(deal_ticket,DEAL_SYMBOL);

© 2000-2025, MetaQuotes Ltd.


2221 Trade Functions

position_ID= HistoryDealGetInteger(deal_ticket,DEAL_POSITION_ID);
deal_description= GetDealDescription(deal_type,volume,symbol,order_ticket,position_I
//--- perform fine formatting for the deal number
string print_index=StringFormat("% 3d",i);
//--- show information on the deal
Print(print_index+": deal #",deal_ticket," at ",transaction_time,deal_description);
}
}
//+------------------------------------------------------------------+
//| Returns the string description of the operation |
//+------------------------------------------------------------------+
string GetDealDescription(long deal_type,double volume,string symbol,long ticket,long pos_ID)
{
string descr;
//---
switch(deal_type)
{
case DEAL_TYPE_BALANCE: return ("balance");
case DEAL_TYPE_CREDIT: return ("credit");
case DEAL_TYPE_CHARGE: return ("charge");
case DEAL_TYPE_CORRECTION: return ("correction");
case DEAL_TYPE_BUY: descr="buy"; break;
case DEAL_TYPE_SELL: descr="sell"; break;
case DEAL_TYPE_BONUS: return ("bonus");
case DEAL_TYPE_COMMISSION: return ("additional commission");
case DEAL_TYPE_COMMISSION_DAILY: return ("daily commission");
case DEAL_TYPE_COMMISSION_MONTHLY: return ("monthly commission");
case DEAL_TYPE_COMMISSION_AGENT_DAILY: return ("daily agent commission");
case DEAL_TYPE_COMMISSION_AGENT_MONTHLY: return ("monthly agent commission");
case DEAL_TYPE_INTEREST: return ("interest rate");
case DEAL_TYPE_BUY_CANCELED: descr="cancelled buy deal"; break;
case DEAL_TYPE_SELL_CANCELED: descr="cancelled sell deal"; break;
}
descr=StringFormat("%s %G %s (order #%d, position ID %d)",
descr, // current description
volume, // deal volume
symbol, // deal symbol
ticket, // ticket of the order that caused the deal
pos_ID // ID of a position, in which the deal is included
);
return(descr);
//---
}

See also
H istoryS elect(), H istoryDealsTotal(), H istoryDealS elect(), Deal Properties

© 2000-2025, MetaQuotes Ltd.


2222 Trade Functions

HistoryDealGetDouble
R eturns the requested property of a deal. The deal property must be of the double type. There are 2
variants of the function.
1. Immediately returns the property value.
double HistoryDealGetDouble(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_DOUBLE property_id // Property identifier
);

2. R eturns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryDealGetDouble(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_DOUBLE property_id, // Property identifier
double& double_var // Here we accept the property value
);

Parameters
ticket_number
[in] Deal tick et.

property_id
[in] Identifier of a deal property. The value can be one of the values of the
ENUM _DEAL _PR OPER T Y_DOUBL E enumeration.

double_var
[out] Variable of the double type that accepts the value of the requested property.

Return Value

Value of the double type.


Note

Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- request deal and order history
if(!HistorySelect(0, TimeCurrent()))
{
Print("HistorySelect() failed. Error ", GetLastError());

© 2000-2025, MetaQuotes Ltd.


2223 Trade Functions

return;
}

//--- in a loop by the list of deals in the account history


int total=HistoryDealsTotal();
for(int i=0; i<total; i++)
{
//--- get the ticket of the next deal (the deal is automatically selected to get its properti
ulong ticket=HistoryDealGetTicket(i);
if(ticket==0)
continue;

//--- get the type and direction of the deal and display the header for the list of real prop
string type=DealTypeDescription((ENUM_DEAL_TYPE)HistoryDealGetInteger(ticket, DEAL_TYPE));
string entry=DealEntryDescription((ENUM_DEAL_ENTRY)HistoryDealGetInteger(ticket, DEAL_ENTRY))
PrintFormat("Double properties of an deal %s entry %s #%I64u:", type, entry, ticket);

//--- print all the real properties of the selected deal under the header
HistoryDealPropertiesDoublePrint(ticket, 12);
}
/*
real:
Double properties of an deal Buy entry In #2785070622:
Volume: 0.50
Price: 1.10480
Commission: 0.00
Swap: 0.00
Profit: 0.00 USD
Fee: 0.00
StopLoss: 0.00000
TakeProfit: 0.00000
Double properties of an deal Sell entry Out #2785071538:
Volume: 0.50
Price: 1.10491
Commission: 0.00
Swap: 0.00
Profit: 5.50 USD
Fee: 0.00
StopLoss: 0.00000
TakeProfit: 0.00000
*/
}
//+------------------------------------------------------------------+
//| Display real properties of the selected deal in the journal |
//+------------------------------------------------------------------+
void HistoryDealPropertiesDoublePrint(const ulong ticket, const uint header_width=0)
{
uint w=0;
string header="";

© 2000-2025, MetaQuotes Ltd.


2224 Trade Functions

double value=0;

//--- get the deal symbol, profit currency and the number of decimal places for the symbol
string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
string currency= SymbolInfoString(symbol, SYMBOL_CURRENCY_PROFIT);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);

//--- define the header text and the width of the header field
//--- if the header width is passed to the function equal to zero, then the width will be the size
header="Volume:";
w=(header_width==0 ? header.Length()+1 : header_width);
//--- get and display the deal volume with the specified header width in the journal
if(!HistoryDealGetDouble(ticket, DEAL_VOLUME, value))
return;
PrintFormat("%-*s%-.2f", w, header, value);

//--- display the deal price in the journal


header="Price:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryDealGetDouble(ticket, DEAL_PRICE, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

//--- display the deal commission in the journal


header="Commission:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryDealGetDouble(ticket, DEAL_COMMISSION, value))
return;
PrintFormat("%-*s%-.2f", w, header, value);

//--- display the accumulated swap in the journal when closing


header="Swap:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryDealGetDouble(ticket, DEAL_SWAP, value))
return;
PrintFormat("%-*s%-.2f", w, header, value);

//--- display the deal financial result in the journal


header="Profit:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryDealGetDouble(ticket, DEAL_PROFIT, value))
return;
PrintFormat("%-*s%-.2f %s", w, header, value, currency);

//--- display the deal fee in the journal


header="Fee:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryDealGetDouble(ticket, DEAL_FEE, value))
return;

© 2000-2025, MetaQuotes Ltd.


2225 Trade Functions

PrintFormat("%-*s%-.2f", w, header, value);

//--- display the StopLoss level in the journal


header="StopLoss:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryDealGetDouble(ticket, DEAL_SL, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);

//--- display the TakeProfit level in the journal


header="TakeProfit:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryDealGetDouble(ticket, DEAL_TP, value))
return;
PrintFormat("%-*s%-.*f", w, header, digits, value);
}
//+------------------------------------------------------------------+
//| Return the deal type description |
//+------------------------------------------------------------------+
string DealTypeDescription(const ENUM_DEAL_TYPE type)
{
switch(type)
{
case DEAL_TYPE_BUY : return("Buy");
case DEAL_TYPE_SELL : return("Sell");
case DEAL_TYPE_BALANCE : return("Balance");
case DEAL_TYPE_CREDIT : return("Credit");
case DEAL_TYPE_CHARGE : return("Additional charge");
case DEAL_TYPE_CORRECTION : return("Correction");
case DEAL_TYPE_BONUS : return("Bonus");
case DEAL_TYPE_COMMISSION : return("Additional commission");
case DEAL_TYPE_COMMISSION_DAILY : return("Daily commission");
case DEAL_TYPE_COMMISSION_MONTHLY : return("Monthly commission");
case DEAL_TYPE_COMMISSION_AGENT_DAILY : return("Daily agent commission");
case DEAL_TYPE_COMMISSION_AGENT_MONTHLY: return("Monthly agent commission");
case DEAL_TYPE_INTEREST : return("Interest rate");
case DEAL_TYPE_BUY_CANCELED : return("Canceled buy deal");
case DEAL_TYPE_SELL_CANCELED : return("Canceled sell deal");
case DEAL_DIVIDEND : return("Dividend operations");
case DEAL_DIVIDEND_FRANKED : return("Franked (non-taxable) dividend operations")
case DEAL_TAX : return("Tax charges");
default : return("Unknown deal type: "+(string)type);
}
}
//+------------------------------------------------------------------+
//| Return position change method |
//+------------------------------------------------------------------+
string DealEntryDescription(const ENUM_DEAL_ENTRY entry)
{

© 2000-2025, MetaQuotes Ltd.


2226 Trade Functions

switch(entry)
{
case DEAL_ENTRY_IN : return("In");
case DEAL_ENTRY_OUT : return("Out");
case DEAL_ENTRY_INOUT : return("Reverce");
case DEAL_ENTRY_OUT_BY : return("Out by");
case DEAL_ENTRY_STATE : return("Status record");
default : return("Unknown deal entry: "+(string)entry);
}
}

See also
H istoryS elect(), H istoryDealsTotal(), H istoryDealGetTick et(), Deal Properties

© 2000-2025, MetaQuotes Ltd.


2227 Trade Functions

HistoryDealGetInteger
R eturns the requested property of a deal. The deal property must be of the datetime, int type. There
are 2 variants of the function.
1. Immediately returns the property value.
long HistoryDealGetInteger(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_INTEGER property_id // Property identifier
);

2. R eturns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryDealGetInteger(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_INTEGER property_id, // Property identifier
long& long_var // Here we accept the property value
);

Parameters
ticket_number
[in] Trade ticket.
property_id
[in] Identifier of the deal property. The value can be one of the values of the
ENUM _DEAL _PR OPER T Y_INT EGER enumeration.
long_var
[out] Variable of the long type that accepts the value of the requested property.

Return Value

Value of the long type.


Note

Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
Example:

//+------------------------------------------------------------------+
//| Trade function |
//+------------------------------------------------------------------+
void OnTrade()
{
//--- receive the last deal's ticket from week's trading history
ulong last_deal=GetLastDealTicket();
if(HistoryDealSelect(last_deal))
{

© 2000-2025, MetaQuotes Ltd.


2228 Trade Functions

//--- time of deal execution in milliseconds since 01.01.1970


long deal_time_msc=HistoryDealGetInteger(last_deal,DEAL_TIME_MSC);
PrintFormat("Deal #%d DEAL_TIME_MSC=%i64 => %s",
last_deal,deal_time_msc,TimeToString(deal_time_msc/1000));
}
else
PrintFormat("HistoryDealSelect() failed for #%d. Eror code=%d",
last_deal,GetLastError());
//---
}
//+------------------------------------------------------------------+
//| Returns the last deal ticket in history or -1 |
//+------------------------------------------------------------------+
ulong GetLastDealTicket()
{
//--- request history for the last 7 days
if(!GetTradeHistory(7))
{
//--- notify on unsuccessful call and return -1
Print(__FUNCTION__," HistorySelect() returned false");
return -1;
}
//---
ulong first_deal,last_deal,deals=HistoryDealsTotal();
//--- work with orders if there are any
if(deals>0)
{
Print("Deals = ",deals);
first_deal=HistoryDealGetTicket(0);
PrintFormat("first_deal = %d",first_deal);
if(deals>1)
{
last_deal=HistoryDealGetTicket((int)deals-1);
PrintFormat("last_deal = %d",last_deal);
return last_deal;
}
return first_deal;
}
//--- no deal found, return -1
return -1;
}
//+--------------------------------------------------------------------------+
//| Requests history for the last days and returns false in case of failure |
//+--------------------------------------------------------------------------+
bool GetTradeHistory(int days)
{
//--- set a week period to request trade history
datetime to=TimeCurrent();
datetime from=to-days*PeriodSeconds(PERIOD_D1);

© 2000-2025, MetaQuotes Ltd.


2229 Trade Functions

ResetLastError();
//--- make a request and check the result
if(!HistorySelect(from,to))
{
Print(__FUNCTION__," HistorySelect=false. Error code=",GetLastError());
return false;
}
//--- history received successfully
return true;
}

See also
H istoryDealsTotal(), H istoryS elect(), H istoryDealGetTick et(), Deal Properties

© 2000-2025, MetaQuotes Ltd.


2230 Trade Functions

HistoryDealGetString
R eturns the requested property of a deal. The deal property must be of the string type. There are 2
variants of the function.
1. Immediately returns the property value.
string HistoryDealGetString(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_STRING property_id // Property identifier
);

2. R eturns true or false, depending on the success of the function. If successful, the value of the
property is placed into a target variable passed by reference by the last parameter.
bool HistoryDealGetString(
ulong ticket_number, // Ticket
ENUM_DEAL_PROPERTY_STRING property_id, // Property identifier
string& string_var // Here we accept the property value
);

Parameters
ticket_number
[in] Deal tick et.

property_id
[in] Identifier of the deal property. The value can be one of the values of the
ENUM _DEAL _PR OPER T Y_S T R ING enumeration.

string_var
[out] Variable of the string type that accepts the value of the requested property.

Return Value

Value of the string type.


Note

Do not confuse orders, deals and positions. Each deal is the result of the execution of an order, each
position is the summary result of one or more deals.
Example:

//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- request deal and order history
if(!HistorySelect(0, TimeCurrent()))
{
Print("HistorySelect() failed. Error ", GetLastError());

© 2000-2025, MetaQuotes Ltd.


2231 Trade Functions

return;
}

//--- in a loop by the list of deals in the account history


int total=HistoryDealsTotal();
for(int i=0; i<total; i++)
{
//--- get the ticket of the next deal (the deal is automatically selected to get its properti
ulong ticket=HistoryDealGetTicket(i);
if(ticket==0)
continue;

//--- get the type and direction of the deal and display the header for the list of real prop
string type=DealTypeDescription((ENUM_DEAL_TYPE)HistoryDealGetInteger(ticket, DEAL_TYPE));
string entry=DealEntryDescription((ENUM_DEAL_ENTRY)HistoryDealGetInteger(ticket, DEAL_ENTRY))
PrintFormat("String properties of an deal %s entry %s #%I64u:", type, entry, ticket);

//--- print all the real properties of the selected deal under the header
HistoryDealPropertiesStringPrint(ticket, 13);
}
/*
result:
String properties of an deal Buy entry In #2785021084:
Symbol: EURUSD
Comment: Test PositionGetString
Extarnal ID:
String properties of an deal Buy entry Out #2497993663:
Symbol: EURUSD
Comment: [tp 1.08639]
Extarnal ID:
*/
}
//+------------------------------------------------------------------+
//| Display string properties of the selected deal in the journal |
//+------------------------------------------------------------------+
void HistoryDealPropertiesStringPrint(const ulong ticket, const uint header_width=0)
{
uint w=0;
string header="";
string value ="";

//--- define the header text and the width of the header field
//--- if the header width is passed to the function equal to zero, then the width will be the size
header="Symbol:";
w=(header_width==0 ? header.Length()+1 : header_width);
//--- get and display the deal symbol with the specified header width in the journal
if(!HistoryDealGetString(ticket, DEAL_SYMBOL, value))
return;
PrintFormat("%-*s%-s", w, header, value);

© 2000-2025, MetaQuotes Ltd.


2232 Trade Functions

//--- display the deal comment in the journal


header="Comment:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryDealGetString(ticket, DEAL_COMMENT, value))
return;
PrintFormat("%-*s%-s", w, header, value);

//--- display the deal ID in an external trading system


header="Extarnal ID:";
w=(header_width==0 ? header.Length()+1 : header_width);
if(!HistoryDealGetString(ticket, DEAL_EXTERNAL_ID, value))
return;
PrintFormat("%-*s%-s", w, header, value);
}
//+------------------------------------------------------------------+
//| Return the deal type description |
//+------------------------------------------------------------------+
string DealTypeDescription(const ENUM_DEAL_TYPE type)
{
switch(type)
{
case DEAL_TYPE_BUY : return("Buy");
case DEAL_TYPE_SELL : return("Sell");
case DEAL_TYPE_BALANCE : return("Balance");
case DEAL_TYPE_CREDIT : return("Credit");
case DEAL_TYPE_CHARGE : return("Additional charge");
case DEAL_TYPE_CORRECTION : return("Correction");
case DEAL_TYPE_BONUS : return("Bonus");
case DEAL_TYPE_COMMISSION : return("Additional commission");
case DEAL_TYPE_COMMISSION_DAILY : return("Daily commission");
case DEAL_TYPE_COMMISSION_MONTHLY : return("Monthly commission");
case DEAL_TYPE_COMMISSION_AGENT_DAILY : return("Daily agent commission");
case DEAL_TYPE_COMMISSION_AGENT_MONTHLY: return("Monthly agent commission");
case DEAL_TYPE_INTEREST : return("Interest rate");
case DEAL_TYPE_BUY_CANCELED : return("Canceled buy deal");
case DEAL_TYPE_SELL_CANCELED : return("Canceled sell deal");
case DEAL_DIVIDEND : return("Dividend operations");
case DEAL_DIVIDEND_FRANKED : return("Franked (non-taxable) dividend operations")
case DEAL_TAX : return("Tax charges");
default : return("Unknown deal type: "+(string)type);
}
}
//+------------------------------------------------------------------+
//| Return position change method |
//+------------------------------------------------------------------+
string DealEntryDescription(const ENUM_DEAL_ENTRY entry)
{
switch(entry)

© 2000-2025, MetaQuotes Ltd.


2233 Trade Functions

{
case DEAL_ENTRY_IN : return("In");
case DEAL_ENTRY_OUT : return("Out");
case DEAL_ENTRY_INOUT : return("Reverce");
case DEAL_ENTRY_OUT_BY : return("Out by");
case DEAL_ENTRY_STATE : return("Status record");
default : return("Unknown deal entry: "+(string)entry);
}
}

See also
H istoryDealsTotal(), H istoryS elect(), H istoryDealGetTick et(), Deal Properties

© 2000-2025, MetaQuotes Ltd.


2234 Trade Signals

Trade Signals
This is the group of functions intended for managing trade signals. The functions allow:
· get information about trade signals, available for copying,
· get and set the signal copy settings,
· subscribe and unsubscribe to the signal copying using MQL5 language functions.

Function Action

S ignalBaseGetDouble R eturns the value of double type property for selected signal
S ignalBaseGetInteger R eturns the value of integer type property for selected signal
S ignalBaseGetS tring R eturns the value of string type property for selected signal
S ignalBaseS elect S elects a signal from signals, available in terminal for further
working with it
S ignalBaseTotal R eturns the total amount of signals, available in terminal
S ignalInfoGetDouble R eturns the value of double type property of signal copy settings
S ignalInfoGetInteger R eturns the value of integer type property of signal copy settings
S ignalInfoGetS tring R eturns the value of string type property of signal copy settings
S ignalInfoS etDouble S ets the value of double type property of signal copy settings
S ignalInfoS etInteger S ets the value of integer type property of signal copy settings
S ignalS ubscribe S ubscribes to the trading signal
S ignalUnsubscribe Cancels subscription

© 2000-2025, MetaQuotes Ltd.


2235 Trade Signals

SignalBaseGetDouble
R eturns the value of double type property for selected signal.
double SignalBaseGetDouble(
ENUM_SIGNAL_BASE_DOUBLE property_id, // property identifier
);

Parameters
property_id
[in] S ignal property identifier. The value can be one of the values of the
ENUM _S IGNAL _BASE_DOUBL E enumeration.

Return Value

The value of double type property of the selected signal.

© 2000-2025, MetaQuotes Ltd.


2236 Trade Signals

SignalBaseGetInteger
R eturns the value of integer type property for selected signal.
long SignalBaseGetInteger(
ENUM_SIGNAL_BASE_INTEGER property_id, // property identifier
);

Parameters
property_id
[in] S ignal property identifier. The value can be one of the values of the
ENUM _S IGNAL _BASE_INT EGER enumeration.

Return Value

The value of integer type property of the selected signal.

© 2000-2025, MetaQuotes Ltd.


2237 Trade Signals

SignalBaseGetString
R eturns the value of string type property for selected signal.
string SignalBaseGetString(
ENUM_SIGNAL_BASE_STRING property_id, // property identifier
);

Parameters
property_id
[in] S ignal property identifier. The value can be one of the values of the
ENUM _S IGNAL _BASE_S T R ING enumeration.

Return Value

The value of string type property of the selected signal.

© 2000-2025, MetaQuotes Ltd.


2238 Trade Signals

SignalBaseSelect
S elects a signal from signals, available in terminal for further working with it.
bool SignalBaseSelect(
int index // signal index
);

Parameters
index
[in] S ignal index in base of trading signals.

Return Value

R eturns true if successful, otherwise returns false. To read more about the error call GetLastError().
Example:

void OnStart()
{
//--- get total amount of signals in the terminal
int total=SignalBaseTotal();
//--- process all signals
for(int i=0;i<total;i++)
{
//--- select the signal by index
if(SignalBaseSelect(i))
{
//--- get signal properties
long id =SignalBaseGetInteger(SIGNAL_BASE_ID); // signal id
long pips =SignalBaseGetInteger(SIGNAL_BASE_PIPS); // profit in pips
long subscr=SignalBaseGetInteger(SIGNAL_BASE_SUBSCRIBERS); // number of subscribers
string name =SignalBaseGetString(SIGNAL_BASE_NAME); // signal name
double price =SignalBaseGetDouble(SIGNAL_BASE_PRICE); // signal price
string curr =SignalBaseGetString(SIGNAL_BASE_CURRENCY); // signal currency
//--- print all profitable free signals with subscribers
if(price==0.0 && pips>0 && subscr>0)
PrintFormat("id=%d, name=\"%s\", currency=%s, pips=%d, subscribers=%d",id,name,curr,pip
}
else PrintFormat("Error in call of SignalBaseSelect. Error code=%d",GetLastError());
}
}

© 2000-2025, MetaQuotes Ltd.


2239 Trade Signals

SignalBaseTotal
R eturns the total amount of signals, available in terminal.
int SignalBaseTotal();

Return Value

The total amount of signals, available in terminal.

© 2000-2025, MetaQuotes Ltd.


2240 Trade Signals

SignalInfoGetDouble
R eturns the value of double type property of signal copy settings.
double SignalInfoGetDouble(
ENUM_SIGNAL_INFO_DOUBLE property_id, // property identifier
);

Parameters
property_id
[in] S ignal copy settings property identifier. The value can be one of the values of the
ENUM _S IGNAL _INFO_DOUBL E enumeration.

Return Value

The value of double type property of signal copy settings.

© 2000-2025, MetaQuotes Ltd.


2241 Trade Signals

SignalInfoGetInteger
R eturns the value of integer type property of signal copy settings.
long SignalInfoGetInteger(
ENUM_SIGNAL_INFO_INTEGER property_id, // property identifier
);

Parameters
property_id
[in] S ignal copy settings property identifier. The value can be one of the values of the
ENUM _S IGNAL _INFO_INT EGER enumeration.

Return Value

The value of integer type property of signal copy settings.

© 2000-2025, MetaQuotes Ltd.


2242 Trade Signals

SignalInfoGetString
R eturns the value of string type property of signal copy settings.
string SignalInfoGetString(
ENUM_SIGNAL_INFO_STRING property_id, // property identifier
);

Parameters
property_id
[in] S ignal copy settings property identifier. The value can be one of the values of the
ENUM _S IGNAL _INFO_S T R ING enumeration.

Return Value

The value of string type property of signal copy settings.

© 2000-2025, MetaQuotes Ltd.


2243 Trade Signals

SignalInfoSetDouble
S ets the value of double type property of signal copy settings.
bool SignalInfoSetDouble(
ENUM_SIGNAL_INFO_DOUBLE property_id, // property identifier
double value // new value
);

Parameters
property_id
[in] S ignal copy settings property identifier. The value can be one of the values of the
ENUM _S IGNAL _INFO_DOUBL E enumeration.

value
[in] The value of signal copy settings property.

Return Value

R eturns true if property has been changed, otherwise returns false. To read more about the error
call GetLastError().

© 2000-2025, MetaQuotes Ltd.


2244 Trade Signals

SignalInfoSetInteger
S ets the value of integer type property of signal copy settings.
bool SignalInfoSetInteger(
ENUM_SIGNAL_INFO_INTEGER property_id, // property identifier
long value // new value
);

Parameters
property_id
[in] S ignal copy settings property identifier. The value can be one of the values of the
ENUM _S IGNAL _INFO_INT EGER enumeration.

value
[in] The value of signal copy settings property.

Return Value

R eturns true if property has been changed, otherwise returns false. To read more about the error
call GetLastError().

© 2000-2025, MetaQuotes Ltd.


2245 Trade Signals

SignalSubscribe
S ubscribes to the trading signal.
bool SignalSubscribe(
long signal_id // signal id
);

Parameters
signal_id
[in] S ignal identifier.

Return Value

R eturns true if subscription was successful, otherwise returns false. To read more about the error
call GetLastError().

© 2000-2025, MetaQuotes Ltd.


2246 Trade Signals

SignalUnsubscribe
Cancels subscription.
bool SignalUnsubscribe();

Return Value

R eturnstrue if subscription has been canceled successfully, otherwise returns false. To read more
about the error call GetLastError().

© 2000-2025, MetaQuotes Ltd.


2247 Network Functions

Network functions
MQL5 programs can exchange data with remote servers, as well as send push notifications, emails and
data via FTP.
· The S ocket* group of functions allows establishing a TCP connection (including a secure TLS ) with a
remote host via system sockets. The operation principle is simple: create a socket, connect to the
server and start reading and writing data.
· The W ebRequest function is designed to work with web resources and allows sending HTTP requests
(including GET and POS T) easily.
· S endFTP, S endMail and S endNotification are more simple functions for sending files, emails and
mobile notifications.
For end-user security, the list of allowed IP addresses is implemented on the client terminal side. The
list contains IP addresses the MQL5 program is allowed to connect to via the S ocket* and W ebRequest
functions. For example, if the program needs to connect to https ://www.someserver.com, this
address should be explicitly indicated by a terminal user in the list. An address cannot be added
programmatically.

Add an explicit message to the MQL5 program to notify a user of the need for additional configuration.
You can do that via #property description, Alert or Print.

Function Action

S ock etCreate Create a socket with specified flags and return its handle
S ock etClose Close a socket
S ock etConnect Connect to the server with timeout control
S ock etIsConnected Checks if the socket is currently connected

© 2000-2025, MetaQuotes Ltd.


2248 Network Functions

Function Action

S ock etIs R eadable Get a number of bytes that can be read from a socket
S ock etIs W ritable Check whether data can be written to a socket at the current time
S ock etTimeouts S ettimeouts for receiving and sending data for a socket system
object
S ock etR ead R ead data from a socket
S ock etS end W rite data to a socket
S ock etTls H andshak e Initiate secure TLS (SS L) connection to a specified host via TLS
H andshak e protocol

S ock etTlsCertificate Get data on the certificate used to secure network connection
S ock etTls R ead R ead data from secure TLS connection
S ock etTls R eadAvailable R ead all available data from secure TLS connection
S ock etTls S end S end data via secure TLS connection
W ebR equest S end an H TTP request to a specified server
S endFTP S end a file to an address specified on the FTP tab
S endMail S end an email to an address specified in the Email tab of the
options window
S endNotification S end push notifications to mobile terminals whose MetaQuotes IDs
are specified in the Notifications tab

© 2000-2025, MetaQuotes Ltd.


2249 Network Functions

SocketCreate
Create a socket with specified flags and return its handle.
int SocketCreate(
uint flags // flags
);

Parameters
flags
[in]Combination of flags defining the mode of working with a socket. Currently, only one flag is
supported — S OCKET_DEFAULT.

Return Value

In case of a successful socket creation, return its handle, otherwise INVALID_HANDLE.


Notes

To free up computer memory from an unused socket, call S ocketClose for it.
You can create a maximum of 128 sockets from one MQL5 program. If the limit is exceeded, the
error 5271 (ERR_NETS OCKET_TOO_M ANY_OPENED) is written to _LastError.
The function can be called only from Expert Advisors and scripts, as they run in their own execution
threads. If calling from an indicator, GetLastError() returns the error 4014 – "Function is not allowed
for call" .
Example:

//+------------------------------------------------------------------+
//| SocketExample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "Add Address to the list of allowed ones in the terminal settings to let the
#property script_show_inputs

input string Address="www.mql5.com";


input int Port =80;
bool ExtTLS =false;
//+------------------------------------------------------------------+
//| Send command to the server |
//+------------------------------------------------------------------+
bool HTTPSend(int socket,string request)
{
char req[];
int len=StringToCharArray(request,req)-1;
if(len<0)

© 2000-2025, MetaQuotes Ltd.


2250 Network Functions

return(false);
//--- if secure TLS connection is used via the port 443
if(ExtTLS)
return(SocketTlsSend(socket,req,len)==len);
//--- if standard TCP connection is used
return(SocketSend(socket,req,len)==len);
}
//+------------------------------------------------------------------+
//| Read server response |
//+------------------------------------------------------------------+
bool HTTPRecv(int socket,uint timeout)
{
char rsp[];
string result;
uint timeout_check=GetTickCount()+timeout;
//--- read data from sockets till they are still present but not longer than timeout
do
{
uint len=SocketIsReadable(socket);
if(len)
{
int rsp_len;
//--- various reading commands depending on whether the connection is secure or not
if(ExtTLS)
rsp_len=SocketTlsRead(socket,rsp,len);
else
rsp_len=SocketRead(socket,rsp,len,timeout);
//--- analyze the response
if(rsp_len>0)
{
result+=CharArrayToString(rsp,0,rsp_len);
//--- print only the response header
int header_end=StringFind(result,"\r\n\r\n");
if(header_end>0)
{
Print("HTTP answer header received:");
Print(StringSubstr(result,0,header_end));
return(true);
}
}
}
}
while(GetTickCount()<timeout_check && !IsStopped());
return(false);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()

© 2000-2025, MetaQuotes Ltd.


2251 Network Functions

{
int socket=SocketCreate();
//--- check the handle
if(socket!=INVALID_HANDLE)
{
//--- connect if all is well
if(SocketConnect(socket,Address,Port,1000))
{
Print("Established connection to ",Address,":",Port);

string subject,issuer,serial,thumbprint;
datetime expiration;
//--- if connection is secured by the certificate, display its data
if(SocketTlsCertificate(socket,subject,issuer,serial,thumbprint,expiration))
{
Print("TLS certificate:");
Print(" Owner: ",subject);
Print(" Issuer: ",issuer);
Print(" Number: ",serial);
Print(" Print: ",thumbprint);
Print(" Expiration: ",expiration);
ExtTLS=true;
}
//--- send GET request to the server
if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n"))
{
Print("GET request sent");
//--- read the response
if(!HTTPRecv(socket,1000))
Print("Failed to get a response, error ",GetLastError());
}
else
Print("Failed to send GET request, error ",GetLastError());
}
else
{
Print("Connection to ",Address,":",Port," failed, error ",GetLastError());
}
//--- close a socket after using
SocketClose(socket);
}
else
Print("Failed to create a socket, error ",GetLastError());
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


2252 Network Functions

SocketClose
Close a socket.
bool SocketClose(
const int socket // socket handle
);

Parameters
socket
[in] H andle ofa socket to be closed. The handle is returned by the S ocketCreate function. W hen
an incorrect handle is passed, the error 5270 (ERR_NETS OCKET_INVALIDHANDLE) is written to
_LastError.

Return Value

R eturns true if successful, otherwise false.


Note

If a connection via S ocketConnect was previously created for a socket, it is discontinued.


The function can be called only from Expert Advisors and scripts, as they run in their own execution
threads. If calling from an indicator, GetLastError() returns the error 4014 – "Function is not allowed
for call" .
Example:

//+------------------------------------------------------------------+
//| SocketExample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "Add Address to the list of allowed ones in the terminal settings to let the
#property script_show_inputs

input string Address="www.mql5.com";


input int Port =80;
bool ExtTLS =false;
//+------------------------------------------------------------------+
//| Send command to the server |
//+------------------------------------------------------------------+
bool HTTPSend(int socket,string request)
{
char req[];
int len=StringToCharArray(request,req)-1;
if(len<0)
return(false);

© 2000-2025, MetaQuotes Ltd.


2253 Network Functions

//--- if secure TLS connection is used via the port 443


if(ExtTLS)
return(SocketTlsSend(socket,req,len)==len);
//--- if standard TCP connection is used
return(SocketSend(socket,req,len)==len);
}
//+------------------------------------------------------------------+
//| Read server response |
//+------------------------------------------------------------------+
bool HTTPRecv(int socket,uint timeout)
{
char rsp[];
string result;
uint timeout_check=GetTickCount()+timeout;
//--- read data from sockets till they are still present but not longer than timeout
do
{
uint len=SocketIsReadable(socket);
if(len)
{
int rsp_len;
//--- various reading commands depending on whether the connection is secure or not
if(ExtTLS)
rsp_len=SocketTlsRead(socket,rsp,len);
else
rsp_len=SocketRead(socket,rsp,len,timeout);
//--- analyze the response
if(rsp_len>0)
{
result+=CharArrayToString(rsp,0,rsp_len);
//--- print only the response header
int header_end=StringFind(result,"\r\n\r\n");
if(header_end>0)
{
Print("HTTP answer header received:");
Print(StringSubstr(result,0,header_end));
return(true);
}
}
}
}
while(GetTickCount()<timeout_check && !IsStopped());
return(false);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{

© 2000-2025, MetaQuotes Ltd.


2254 Network Functions

int socket=SocketCreate();
//--- check the handle
if(socket!=INVALID_HANDLE)
{
//--- connect if all is well
if(SocketConnect(socket,Address,Port,1000))
{
Print("Established connection to ",Address,":",Port);

string subject,issuer,serial,thumbprint;
datetime expiration;
//--- if connection is secured by the certificate, display its data
if(SocketTlsCertificate(socket,subject,issuer,serial,thumbprint,expiration))
{
Print("TLS certificate:");
Print(" Owner: ",subject);
Print(" Issuer: ",issuer);
Print(" Number: ",serial);
Print(" Print: ",thumbprint);
Print(" Expiration: ",expiration);
ExtTLS=true;
}
//--- send GET request to the server
if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n"))
{
Print("GET request sent");
//--- read the response
if(!HTTPRecv(socket,1000))
Print("Failed to get a response, error ",GetLastError());
}
else
Print("Failed to send GET request, error ",GetLastError());
}
else
{
Print("Connection to ",Address,":",Port," failed, error ",GetLastError());
}
//--- close a socket after using
SocketClose(socket);
}
else
Print("Failed to create a socket, error ",GetLastError());
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


2255 Network Functions

SocketConnect
Connect to the server with timeout control.
bool SocketConnect(
int socket, // socket
const string server, // connection address
uint port, // connection port
uint timeout_receive_ms // connection timeout
);

Parameters
socket
[in] S ock et handle returned by the S ock etCreate function. W hen an incorrect handle is passed, the
error 5270 (ERR_NETS OCKET_INVALIDHANDLE) is written to _LastError.
server
[in] Domain name of the server you want to connect to or its IP address.
port
[in] Connection port number.
timeout_receive_ms
[in]Connection timeout in milliseconds. If connection is not established within that time interval,
attempts are stopped.

Return Value

If connection is successful, return true, otherwise false.


Note

Connection address should be added to the list of allowed ones on the client terminal side (Tools \
Options \ Expert Advisors).
If connection fails, error 5272 (ERR_NETS OCKET_CANNOT_CONNECT) is written to _LastError.
The function can be called only from Expert Advisors and scripts, as they run in their own execution
threads. If calling from an indicator, GetLastError() returns the error 4014 – "Function is not allowed
for call" .
Example:

//+------------------------------------------------------------------+
//| SocketExample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "Add Address to the list of allowed ones in the terminal settings to let the
#property script_show_inputs

© 2000-2025, MetaQuotes Ltd.


2256 Network Functions

input string Address="www.mql5.com";


input int Port =80;
bool ExtTLS =false;
//+------------------------------------------------------------------+
//| Send command to the server |
//+------------------------------------------------------------------+
bool HTTPSend(int socket,string request)
{
char req[];
int len=StringToCharArray(request,req)-1;
if(len<0)
return(false);
//--- if secure TLS connection is used via the port 443
if(ExtTLS)
return(SocketTlsSend(socket,req,len)==len);
//--- if standard TCP connection is used
return(SocketSend(socket,req,len)==len);
}
//+------------------------------------------------------------------+
//| Read server response |
//+------------------------------------------------------------------+
bool HTTPRecv(int socket,uint timeout)
{
char rsp[];
string result;
uint timeout_check=GetTickCount()+timeout;
//--- read data from sockets till they are still present but not longer than timeout
do
{
uint len=SocketIsReadable(socket);
if(len)
{
int rsp_len;
//--- various reading commands depending on whether the connection is secure or not
if(ExtTLS)
rsp_len=SocketTlsRead(socket,rsp,len);
else
rsp_len=SocketRead(socket,rsp,len,timeout);
//--- analyze the response
if(rsp_len>0)
{
result+=CharArrayToString(rsp,0,rsp_len);
//--- print only the response header
int header_end=StringFind(result,"\r\n\r\n");
if(header_end>0)
{
Print("HTTP answer header received:");
Print(StringSubstr(result,0,header_end));

© 2000-2025, MetaQuotes Ltd.


2257 Network Functions

return(true);
}
}
}
}
while(GetTickCount()<timeout_check && !IsStopped());
return(false);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
int socket=SocketCreate();
//--- check the handle
if(socket!=INVALID_HANDLE)
{
//--- connect if all is well
if(SocketConnect(socket,Address,Port,1000))
{
Print("Established connection to ",Address,":",Port);

string subject,issuer,serial,thumbprint;
datetime expiration;
//--- if connection is secured by the certificate, display its data
if(SocketTlsCertificate(socket,subject,issuer,serial,thumbprint,expiration))
{
Print("TLS certificate:");
Print(" Owner: ",subject);
Print(" Issuer: ",issuer);
Print(" Number: ",serial);
Print(" Print: ",thumbprint);
Print(" Expiration: ",expiration);
ExtTLS=true;
}
//--- send GET request to the server
if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n"))
{
Print("GET request sent");
//--- read the response
if(!HTTPRecv(socket,1000))
Print("Failed to get a response, error ",GetLastError());
}
else
Print("Failed to send GET request, error ",GetLastError());
}
else
{
Print("Connection to ",Address,":",Port," failed, error ",GetLastError());

© 2000-2025, MetaQuotes Ltd.


2258 Network Functions

}
//--- close a socket after using
SocketClose(socket);
}
else
Print("Failed to create a socket, error ",GetLastError());
}
//+------------------------------------------------------------------+

© 2000-2025, MetaQuotes Ltd.


2259 Network Functions

SocketIsConnected
Checks if the socket is currently connected.
bool SocketIsConnected(
const int socket // socket handle
);

Parameters
socket
[in] S ock et handle returned by the S ock etCreate() function. W hen an incorrect handle is passed to
_LastError, the error 5270 (ERR_NET S OCKET _INVALIDHANDL E) is activated.

Return Value

R eturns true if the socket is connected, otherwise - false.


Note

The S ocketIsConnected() function allows checking the current socket connection status.
The function can be called only from Expert Advisors and scripts, as they run in their own execution
threads. If calling from an indicator, GetLastError() returns the error 4014 – "Function is not allowed
for call" .
Example:

//+------------------------------------------------------------------+
//| SocketIsConnected.mq5 |
//| Copyright 2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com
#property version "1.00"
#property description "Add Address to the list of allowed ones in the terminal settings to let the
#property script_show_inputs

input string Address ="www.mql5.com";


input int Port =80;
input bool CloseSocket=true;
bool ExtTLS =false;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart(void)
{
//--- create a socket and get its handle
int socket=SocketCreate();
//--- check the handle
if(socket!=INVALID_HANDLE)

© 2000-2025, MetaQuotes Ltd.


2260 Network Functions

{
//--- if all is well, connect
if(SocketConnect(socket,Address,Port,1000))
{
PrintFormat("Established connection to %s:%d",Address,Port);

string subject,issuer,serial,thumbprint;
datetime expiration;
//--- if connection is protected by certificate, display its data
if(SocketTlsCertificate(socket,subject,issuer,serial,thumbprint,expiration))
{
Print("TLS certificate:");
Print(" Owner: ",subject);
Print(" Issuer: ",issuer);
Print(" Number: ",serial);
Print(" Print: ",thumbprint);
Print(" Expiration: ",expiration);
ExtTLS=true;
}
//--- send GET request to the server
if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n"))
{
Print("GET request sent");
//--- read response
if(!HTTPRecv(socket,1000))
Print("Failed to get a response, error ",GetLastError());
}
else
Print("Failed to send GET request, error ",GetLastError());
}
else
{
PrintFormat("Connection to %s:%d failed, error %d",Address,Port,GetLastError());
}
//--- if the flag is set, close the socket after use
if(CloseSocket)
SocketClose(socket);
}
else
Print("Failed to create a socket, error ",GetLastError());

//--- check server connection


bool connected=SocketIsConnected(socket);
//--- terminate operation if no connection
if(!connected)
{
Print("No connection to server");
}
//--- if server connection is present

© 2000-2025, MetaQuotes Ltd.


2261 Network Functions

else
{
Print("Connection to the server is available\nThe connection needs to be closed. Closing");
//--- close the socket and check the connection status again
SocketClose(socket);
connected=SocketIsConnected(socket);
}

//--- display the current server connection status


Print("Currently connected: ",(connected ? "opened" : "closed"));
/*
result in case CloseSocket = true:
No connection to server
Currently connected: closed

result in case CloseSocket = false:


Connection to the server is available
The connection needs to be closed. Closing
Currently connected: closed
*/
}
//+------------------------------------------------------------------+
//| Send command to server |
//+------------------------------------------------------------------+
bool HTTPSend(int socket,string request)
{
//--- convert the string to a character array, discard the terminating zero
char req[];
int len=StringToCharArray(request,req)-1;

if(len<0)
return(false);
//--- if a secure TLS connection via port 443 is used
if(ExtTLS)
return(SocketTlsSend(socket,req,len)==len);
//--- if a regular TCP connection is used
return(SocketSend(socket,req,len)==len);
}
//+------------------------------------------------------------------+
//| Read server response |
//+------------------------------------------------------------------+
bool HTTPRecv(int socket,uint timeout_ms)
{
char rsp[];
string result;
ulong timeout_check=GetTickCount64()+timeout_ms;
//--- read data from the socket while there is some, but not longer than timeout
do
{

© 2000-2025, MetaQuotes Ltd.


2262 Network Functions

uint len=SocketIsReadable(socket);

if(len)
{
int rsp_len;
//--- different read commands depending on whether the connection is secure or not
if(ExtTLS)
rsp_len=SocketTlsRead(socket,rsp,len);
else
rsp_len=SocketRead(socket,rsp,len,timeout_ms);
//--- parse response
if(rsp_len>0)
{
result+=CharArrayToString(rsp,0,rsp_len);
//--- display response header only
int header_end=StringFind(result,"\r\n\r\n");

if(header_end>0)
{
Print("HTTP answer header received:");
Print(StringSubstr(result,0,header_end));
return(true);
}
//--- update read timeout expiration time
timeout_check=GetTickCount64()+timeout_ms;
}
}
}
while(GetTickCount64()<timeout_check && !IsStopped());

return(false);
}

See also
S ock etConnect, S ock etIs W ritable, S ock etCreate, S ock etClose

© 2000-2025, MetaQuotes Ltd.


2263 Network Functions

SocketIsReadable
Get a number of bytes that can be read from a socket.
uint SocketIsReadable(
const int socket // socket handle
);

Parameters
socket
[in] S ock et handle returned by the S ock etCreate function. W hen an incorrect handle is passed to
_LastError, the error 5270 (ERR_NET S OCKET _INVALIDHANDL E) is activated.

Return Value

Number of bytes that can be read. In case of an error, 0 is returned.


Note

If an error occurs on a system socket when executing the function, connection established via
S ock etConnect is discontinued.

Before calling S ock etR ead, check if the sock et features data for reading. Otherwise, if there are no

You might also like